SemaDeclCXX.cpp revision a8f32e0965ee19ecc53cd796e34268377a20357c
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/CXXInheritance.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/TypeOrdering.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25#include "llvm/Support/Compiler.h" 26#include <algorithm> // for std::equal 27#include <map> 28#include <set> 29 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// CheckDefaultArgumentVisitor 34//===----------------------------------------------------------------------===// 35 36namespace { 37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 38 /// the default argument of a parameter to determine whether it 39 /// contains any ill-formed subexpressions. For example, this will 40 /// diagnose the use of local variables or parameters within the 41 /// default argument expression. 42 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 43 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 44 Expr *DefaultArg; 45 Sema *S; 46 47 public: 48 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 49 : DefaultArg(defarg), S(s) {} 50 51 bool VisitExpr(Expr *Node); 52 bool VisitDeclRefExpr(DeclRefExpr *DRE); 53 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 54 }; 55 56 /// VisitExpr - Visit all of the children of this expression. 57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 58 bool IsInvalid = false; 59 for (Stmt::child_iterator I = Node->child_begin(), 60 E = Node->child_end(); I != E; ++I) 61 IsInvalid |= Visit(*I); 62 return IsInvalid; 63 } 64 65 /// VisitDeclRefExpr - Visit a reference to a declaration, to 66 /// determine whether this declaration can be used in the default 67 /// argument expression. 68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 69 NamedDecl *Decl = DRE->getDecl(); 70 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 71 // C++ [dcl.fct.default]p9 72 // Default arguments are evaluated each time the function is 73 // called. The order of evaluation of function arguments is 74 // unspecified. Consequently, parameters of a function shall not 75 // be used in default argument expressions, even if they are not 76 // evaluated. Parameters of a function declared before a default 77 // argument expression are in scope and can hide namespace and 78 // class member names. 79 return S->Diag(DRE->getSourceRange().getBegin(), 80 diag::err_param_default_argument_references_param) 81 << Param->getDeclName() << DefaultArg->getSourceRange(); 82 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 83 // C++ [dcl.fct.default]p7 84 // Local variables shall not be used in default argument 85 // expressions. 86 if (VDecl->isBlockVarDecl()) 87 return S->Diag(DRE->getSourceRange().getBegin(), 88 diag::err_param_default_argument_references_local) 89 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 90 } 91 92 return false; 93 } 94 95 /// VisitCXXThisExpr - Visit a C++ "this" expression. 96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 97 // C++ [dcl.fct.default]p8: 98 // The keyword this shall not be used in a default argument of a 99 // member function. 100 return S->Diag(ThisE->getSourceRange().getBegin(), 101 diag::err_param_default_argument_references_this) 102 << ThisE->getSourceRange(); 103 } 104} 105 106bool 107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 108 SourceLocation EqualLoc) { 109 QualType ParamType = Param->getType(); 110 111 if (RequireCompleteType(Param->getLocation(), Param->getType(), 112 diag::err_typecheck_decl_incomplete_type)) { 113 Param->setInvalidDecl(); 114 return true; 115 } 116 117 Expr *Arg = (Expr *)DefaultArg.get(); 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 if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 126 Param->getDeclName(), /*DirectInit=*/false)) 127 return true; 128 129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 130 131 // Okay: add the default argument to the parameter 132 Param->setDefaultArg(Arg); 133 134 DefaultArg.release(); 135 136 return false; 137} 138 139/// ActOnParamDefaultArgument - Check whether the default argument 140/// provided for a function parameter is well-formed. If so, attach it 141/// to the parameter declaration. 142void 143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 144 ExprArg defarg) { 145 if (!param || !defarg.get()) 146 return; 147 148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 149 UnparsedDefaultArgLocs.erase(Param); 150 151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 152 QualType ParamType = Param->getType(); 153 154 // Default arguments are only permitted in C++ 155 if (!getLangOptions().CPlusPlus) { 156 Diag(EqualLoc, diag::err_param_default_argument) 157 << DefaultArg->getSourceRange(); 158 Param->setInvalidDecl(); 159 return; 160 } 161 162 // Check that the default argument is well-formed 163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 164 if (DefaultArgChecker.Visit(DefaultArg.get())) { 165 Param->setInvalidDecl(); 166 return; 167 } 168 169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 170} 171 172/// ActOnParamUnparsedDefaultArgument - We've seen a default 173/// argument for a function parameter, but we can't parse it yet 174/// because we're inside a class definition. Note that this default 175/// argument will be parsed later. 176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 177 SourceLocation EqualLoc, 178 SourceLocation ArgLoc) { 179 if (!param) 180 return; 181 182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 183 if (Param) 184 Param->setUnparsedDefaultArg(); 185 186 UnparsedDefaultArgLocs[Param] = ArgLoc; 187} 188 189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 190/// the default argument for the parameter param failed. 191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 192 if (!param) 193 return; 194 195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 196 197 Param->setInvalidDecl(); 198 199 UnparsedDefaultArgLocs.erase(Param); 200} 201 202/// CheckExtraCXXDefaultArguments - Check for any extra default 203/// arguments in the declarator, which is not a function declaration 204/// or definition and therefore is not permitted to have default 205/// arguments. This routine should be invoked for every declarator 206/// that is not a function declaration or definition. 207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 208 // C++ [dcl.fct.default]p3 209 // A default argument expression shall be specified only in the 210 // parameter-declaration-clause of a function declaration or in a 211 // template-parameter (14.1). It shall not be specified for a 212 // parameter pack. If it is specified in a 213 // parameter-declaration-clause, it shall not occur within a 214 // declarator or abstract-declarator of a parameter-declaration. 215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 216 DeclaratorChunk &chunk = D.getTypeObject(i); 217 if (chunk.Kind == DeclaratorChunk::Function) { 218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 219 ParmVarDecl *Param = 220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 221 if (Param->hasUnparsedDefaultArg()) { 222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 225 delete Toks; 226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 227 } else if (Param->getDefaultArg()) { 228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 229 << Param->getDefaultArg()->getSourceRange(); 230 Param->setDefaultArg(0); 231 } 232 } 233 } 234 } 235} 236 237// MergeCXXFunctionDecl - Merge two declarations of the same C++ 238// function, once we already know that they have the same 239// type. Subroutine of MergeFunctionDecl. Returns true if there was an 240// error, false otherwise. 241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 242 bool Invalid = false; 243 244 // C++ [dcl.fct.default]p4: 245 // For non-template functions, default arguments can be added in 246 // later declarations of a function in the same 247 // scope. Declarations in different scopes have completely 248 // distinct sets of default arguments. That is, declarations in 249 // inner scopes do not acquire default arguments from 250 // declarations in outer scopes, and vice versa. In a given 251 // function declaration, all parameters subsequent to a 252 // parameter with a default argument shall have default 253 // arguments supplied in this or previous declarations. A 254 // default argument shall not be redefined by a later 255 // declaration (not even to the same value). 256 // 257 // C++ [dcl.fct.default]p6: 258 // Except for member functions of class templates, the default arguments 259 // in a member function definition that appears outside of the class 260 // definition are added to the set of default arguments provided by the 261 // member function declaration in the class definition. 262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 263 ParmVarDecl *OldParam = Old->getParamDecl(p); 264 ParmVarDecl *NewParam = New->getParamDecl(p); 265 266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 267 Diag(NewParam->getLocation(), 268 diag::err_param_default_argument_redefinition) 269 << NewParam->getDefaultArgRange(); 270 271 // Look for the function declaration where the default argument was 272 // actually written, which may be a declaration prior to Old. 273 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 274 Older; Older = Older->getPreviousDeclaration()) { 275 if (!Older->getParamDecl(p)->hasDefaultArg()) 276 break; 277 278 OldParam = Older->getParamDecl(p); 279 } 280 281 Diag(OldParam->getLocation(), diag::note_previous_definition) 282 << OldParam->getDefaultArgRange(); 283 Invalid = true; 284 } else if (OldParam->hasDefaultArg()) { 285 // Merge the old default argument into the new parameter 286 if (OldParam->hasUninstantiatedDefaultArg()) 287 NewParam->setUninstantiatedDefaultArg( 288 OldParam->getUninstantiatedDefaultArg()); 289 else 290 NewParam->setDefaultArg(OldParam->getDefaultArg()); 291 } else if (NewParam->hasDefaultArg()) { 292 if (New->getDescribedFunctionTemplate()) { 293 // Paragraph 4, quoted above, only applies to non-template functions. 294 Diag(NewParam->getLocation(), 295 diag::err_param_default_argument_template_redecl) 296 << NewParam->getDefaultArgRange(); 297 Diag(Old->getLocation(), diag::note_template_prev_declaration) 298 << false; 299 } else if (New->getDeclContext()->isDependentContext()) { 300 // C++ [dcl.fct.default]p6 (DR217): 301 // Default arguments for a member function of a class template shall 302 // be specified on the initial declaration of the member function 303 // within the class template. 304 // 305 // Reading the tea leaves a bit in DR217 and its reference to DR205 306 // leads me to the conclusion that one cannot add default function 307 // arguments for an out-of-line definition of a member function of a 308 // dependent type. 309 int WhichKind = 2; 310 if (CXXRecordDecl *Record 311 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 312 if (Record->getDescribedClassTemplate()) 313 WhichKind = 0; 314 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 315 WhichKind = 1; 316 else 317 WhichKind = 2; 318 } 319 320 Diag(NewParam->getLocation(), 321 diag::err_param_default_argument_member_template_redecl) 322 << WhichKind 323 << NewParam->getDefaultArgRange(); 324 } 325 } 326 } 327 328 if (CheckEquivalentExceptionSpec( 329 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(), 330 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) { 331 Invalid = true; 332 } 333 334 return Invalid; 335} 336 337/// CheckCXXDefaultArguments - Verify that the default arguments for a 338/// function declaration are well-formed according to C++ 339/// [dcl.fct.default]. 340void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 341 unsigned NumParams = FD->getNumParams(); 342 unsigned p; 343 344 // Find first parameter with a default argument 345 for (p = 0; p < NumParams; ++p) { 346 ParmVarDecl *Param = FD->getParamDecl(p); 347 if (Param->hasDefaultArg()) 348 break; 349 } 350 351 // C++ [dcl.fct.default]p4: 352 // In a given function declaration, all parameters 353 // subsequent to a parameter with a default argument shall 354 // have default arguments supplied in this or previous 355 // declarations. A default argument shall not be redefined 356 // by a later declaration (not even to the same value). 357 unsigned LastMissingDefaultArg = 0; 358 for (; p < NumParams; ++p) { 359 ParmVarDecl *Param = FD->getParamDecl(p); 360 if (!Param->hasDefaultArg()) { 361 if (Param->isInvalidDecl()) 362 /* We already complained about this parameter. */; 363 else if (Param->getIdentifier()) 364 Diag(Param->getLocation(), 365 diag::err_param_default_argument_missing_name) 366 << Param->getIdentifier(); 367 else 368 Diag(Param->getLocation(), 369 diag::err_param_default_argument_missing); 370 371 LastMissingDefaultArg = p; 372 } 373 } 374 375 if (LastMissingDefaultArg > 0) { 376 // Some default arguments were missing. Clear out all of the 377 // default arguments up to (and including) the last missing 378 // default argument, so that we leave the function parameters 379 // in a semantically valid state. 380 for (p = 0; p <= LastMissingDefaultArg; ++p) { 381 ParmVarDecl *Param = FD->getParamDecl(p); 382 if (Param->hasDefaultArg()) { 383 if (!Param->hasUnparsedDefaultArg()) 384 Param->getDefaultArg()->Destroy(Context); 385 Param->setDefaultArg(0); 386 } 387 } 388 } 389} 390 391/// isCurrentClassName - Determine whether the identifier II is the 392/// name of the class type currently being defined. In the case of 393/// nested classes, this will only return true if II is the name of 394/// the innermost class. 395bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 396 const CXXScopeSpec *SS) { 397 CXXRecordDecl *CurDecl; 398 if (SS && SS->isSet() && !SS->isInvalid()) { 399 DeclContext *DC = computeDeclContext(*SS, true); 400 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 401 } else 402 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 403 404 if (CurDecl) 405 return &II == CurDecl->getIdentifier(); 406 else 407 return false; 408} 409 410/// \brief Check the validity of a C++ base class specifier. 411/// 412/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 413/// and returns NULL otherwise. 414CXXBaseSpecifier * 415Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 416 SourceRange SpecifierRange, 417 bool Virtual, AccessSpecifier Access, 418 QualType BaseType, 419 SourceLocation BaseLoc) { 420 // C++ [class.union]p1: 421 // A union shall not have base classes. 422 if (Class->isUnion()) { 423 Diag(Class->getLocation(), diag::err_base_clause_on_union) 424 << SpecifierRange; 425 return 0; 426 } 427 428 if (BaseType->isDependentType()) 429 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 430 Class->getTagKind() == RecordDecl::TK_class, 431 Access, BaseType); 432 433 // Base specifiers must be record types. 434 if (!BaseType->isRecordType()) { 435 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 436 return 0; 437 } 438 439 // C++ [class.union]p1: 440 // A union shall not be used as a base class. 441 if (BaseType->isUnionType()) { 442 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 443 return 0; 444 } 445 446 // C++ [class.derived]p2: 447 // The class-name in a base-specifier shall not be an incompletely 448 // defined class. 449 if (RequireCompleteType(BaseLoc, BaseType, 450 PDiag(diag::err_incomplete_base_class) 451 << SpecifierRange)) 452 return 0; 453 454 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 455 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 456 assert(BaseDecl && "Record type has no declaration"); 457 BaseDecl = BaseDecl->getDefinition(Context); 458 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 459 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 460 assert(CXXBaseDecl && "Base type is not a C++ type"); 461 if (!CXXBaseDecl->isEmpty()) 462 Class->setEmpty(false); 463 if (CXXBaseDecl->isPolymorphic()) 464 Class->setPolymorphic(true); 465 466 // C++ [dcl.init.aggr]p1: 467 // An aggregate is [...] a class with [...] no base classes [...]. 468 Class->setAggregate(false); 469 Class->setPOD(false); 470 471 if (Virtual) { 472 // C++ [class.ctor]p5: 473 // A constructor is trivial if its class has no virtual base classes. 474 Class->setHasTrivialConstructor(false); 475 476 // C++ [class.copy]p6: 477 // A copy constructor is trivial if its class has no virtual base classes. 478 Class->setHasTrivialCopyConstructor(false); 479 480 // C++ [class.copy]p11: 481 // A copy assignment operator is trivial if its class has no virtual 482 // base classes. 483 Class->setHasTrivialCopyAssignment(false); 484 485 // C++0x [meta.unary.prop] is_empty: 486 // T is a class type, but not a union type, with ... no virtual base 487 // classes 488 Class->setEmpty(false); 489 } else { 490 // C++ [class.ctor]p5: 491 // A constructor is trivial if all the direct base classes of its 492 // class have trivial constructors. 493 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 494 Class->setHasTrivialConstructor(false); 495 496 // C++ [class.copy]p6: 497 // A copy constructor is trivial if all the direct base classes of its 498 // class have trivial copy constructors. 499 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 500 Class->setHasTrivialCopyConstructor(false); 501 502 // C++ [class.copy]p11: 503 // A copy assignment operator is trivial if all the direct base classes 504 // of its class have trivial copy assignment operators. 505 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 506 Class->setHasTrivialCopyAssignment(false); 507 } 508 509 // C++ [class.ctor]p3: 510 // A destructor is trivial if all the direct base classes of its class 511 // have trivial destructors. 512 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 513 Class->setHasTrivialDestructor(false); 514 515 // Create the base specifier. 516 // FIXME: Allocate via ASTContext? 517 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 518 Class->getTagKind() == RecordDecl::TK_class, 519 Access, BaseType); 520} 521 522/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 523/// one entry in the base class list of a class specifier, for 524/// example: 525/// class foo : public bar, virtual private baz { 526/// 'public bar' and 'virtual private baz' are each base-specifiers. 527Sema::BaseResult 528Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 529 bool Virtual, AccessSpecifier Access, 530 TypeTy *basetype, SourceLocation BaseLoc) { 531 if (!classdecl) 532 return true; 533 534 AdjustDeclIfTemplate(classdecl); 535 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 536 QualType BaseType = GetTypeFromParser(basetype); 537 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 538 Virtual, Access, 539 BaseType, BaseLoc)) 540 return BaseSpec; 541 542 return true; 543} 544 545/// \brief Performs the actual work of attaching the given base class 546/// specifiers to a C++ class. 547bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 548 unsigned NumBases) { 549 if (NumBases == 0) 550 return false; 551 552 // Used to keep track of which base types we have already seen, so 553 // that we can properly diagnose redundant direct base types. Note 554 // that the key is always the unqualified canonical type of the base 555 // class. 556 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 557 558 // Copy non-redundant base specifiers into permanent storage. 559 unsigned NumGoodBases = 0; 560 bool Invalid = false; 561 for (unsigned idx = 0; idx < NumBases; ++idx) { 562 QualType NewBaseType 563 = Context.getCanonicalType(Bases[idx]->getType()); 564 NewBaseType = NewBaseType.getUnqualifiedType(); 565 566 if (KnownBaseTypes[NewBaseType]) { 567 // C++ [class.mi]p3: 568 // A class shall not be specified as a direct base class of a 569 // derived class more than once. 570 Diag(Bases[idx]->getSourceRange().getBegin(), 571 diag::err_duplicate_base_class) 572 << KnownBaseTypes[NewBaseType]->getType() 573 << Bases[idx]->getSourceRange(); 574 575 // Delete the duplicate base class specifier; we're going to 576 // overwrite its pointer later. 577 Context.Deallocate(Bases[idx]); 578 579 Invalid = true; 580 } else { 581 // Okay, add this new base class. 582 KnownBaseTypes[NewBaseType] = Bases[idx]; 583 Bases[NumGoodBases++] = Bases[idx]; 584 } 585 } 586 587 // Attach the remaining base class specifiers to the derived class. 588 Class->setBases(Context, Bases, NumGoodBases); 589 590 // Delete the remaining (good) base class specifiers, since their 591 // data has been copied into the CXXRecordDecl. 592 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 593 Context.Deallocate(Bases[idx]); 594 595 return Invalid; 596} 597 598/// ActOnBaseSpecifiers - Attach the given base specifiers to the 599/// class, after checking whether there are any duplicate base 600/// classes. 601void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 602 unsigned NumBases) { 603 if (!ClassDecl || !Bases || !NumBases) 604 return; 605 606 AdjustDeclIfTemplate(ClassDecl); 607 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 608 (CXXBaseSpecifier**)(Bases), NumBases); 609} 610 611/// \brief Determine whether the type \p Derived is a C++ class that is 612/// derived from the type \p Base. 613bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 614 if (!getLangOptions().CPlusPlus) 615 return false; 616 617 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 618 if (!DerivedRT) 619 return false; 620 621 const RecordType *BaseRT = Base->getAs<RecordType>(); 622 if (!BaseRT) 623 return false; 624 625 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 626 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 627 return DerivedRD->isDerivedFrom(BaseRD); 628} 629 630/// \brief Determine whether the type \p Derived is a C++ class that is 631/// derived from the type \p Base. 632bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 633 if (!getLangOptions().CPlusPlus) 634 return false; 635 636 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 637 if (!DerivedRT) 638 return false; 639 640 const RecordType *BaseRT = Base->getAs<RecordType>(); 641 if (!BaseRT) 642 return false; 643 644 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 645 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 646 return DerivedRD->isDerivedFrom(BaseRD, Paths); 647} 648 649/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 650/// conversion (where Derived and Base are class types) is 651/// well-formed, meaning that the conversion is unambiguous (and 652/// that all of the base classes are accessible). Returns true 653/// and emits a diagnostic if the code is ill-formed, returns false 654/// otherwise. Loc is the location where this routine should point to 655/// if there is an error, and Range is the source range to highlight 656/// if there is an error. 657bool 658Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 659 unsigned InaccessibleBaseID, 660 unsigned AmbigiousBaseConvID, 661 SourceLocation Loc, SourceRange Range, 662 DeclarationName Name) { 663 // First, determine whether the path from Derived to Base is 664 // ambiguous. This is slightly more expensive than checking whether 665 // the Derived to Base conversion exists, because here we need to 666 // explore multiple paths to determine if there is an ambiguity. 667 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 668 /*DetectVirtual=*/false); 669 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 670 assert(DerivationOkay && 671 "Can only be used with a derived-to-base conversion"); 672 (void)DerivationOkay; 673 674 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 675 // Check that the base class can be accessed. 676 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc, 677 Name); 678 } 679 680 // We know that the derived-to-base conversion is ambiguous, and 681 // we're going to produce a diagnostic. Perform the derived-to-base 682 // search just one more time to compute all of the possible paths so 683 // that we can print them out. This is more expensive than any of 684 // the previous derived-to-base checks we've done, but at this point 685 // performance isn't as much of an issue. 686 Paths.clear(); 687 Paths.setRecordingPaths(true); 688 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 689 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 690 (void)StillOkay; 691 692 // Build up a textual representation of the ambiguous paths, e.g., 693 // D -> B -> A, that will be used to illustrate the ambiguous 694 // conversions in the diagnostic. We only print one of the paths 695 // to each base class subobject. 696 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 697 698 Diag(Loc, AmbigiousBaseConvID) 699 << Derived << Base << PathDisplayStr << Range << Name; 700 return true; 701} 702 703bool 704Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 705 SourceLocation Loc, SourceRange Range) { 706 return CheckDerivedToBaseConversion(Derived, Base, 707 diag::err_conv_to_inaccessible_base, 708 diag::err_ambiguous_derived_to_base_conv, 709 Loc, Range, DeclarationName()); 710} 711 712 713/// @brief Builds a string representing ambiguous paths from a 714/// specific derived class to different subobjects of the same base 715/// class. 716/// 717/// This function builds a string that can be used in error messages 718/// to show the different paths that one can take through the 719/// inheritance hierarchy to go from the derived class to different 720/// subobjects of a base class. The result looks something like this: 721/// @code 722/// struct D -> struct B -> struct A 723/// struct D -> struct C -> struct A 724/// @endcode 725std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 726 std::string PathDisplayStr; 727 std::set<unsigned> DisplayedPaths; 728 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 729 Path != Paths.end(); ++Path) { 730 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 731 // We haven't displayed a path to this particular base 732 // class subobject yet. 733 PathDisplayStr += "\n "; 734 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 735 for (CXXBasePath::const_iterator Element = Path->begin(); 736 Element != Path->end(); ++Element) 737 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 738 } 739 } 740 741 return PathDisplayStr; 742} 743 744//===----------------------------------------------------------------------===// 745// C++ class member Handling 746//===----------------------------------------------------------------------===// 747 748/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 749/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 750/// bitfield width if there is one and 'InitExpr' specifies the initializer if 751/// any. 752Sema::DeclPtrTy 753Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 754 MultiTemplateParamsArg TemplateParameterLists, 755 ExprTy *BW, ExprTy *InitExpr, bool Deleted) { 756 const DeclSpec &DS = D.getDeclSpec(); 757 DeclarationName Name = GetNameForDeclarator(D); 758 Expr *BitWidth = static_cast<Expr*>(BW); 759 Expr *Init = static_cast<Expr*>(InitExpr); 760 SourceLocation Loc = D.getIdentifierLoc(); 761 762 bool isFunc = D.isFunctionDeclarator(); 763 764 assert(!DS.isFriendSpecified()); 765 766 // C++ 9.2p6: A member shall not be declared to have automatic storage 767 // duration (auto, register) or with the extern storage-class-specifier. 768 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 769 // data members and cannot be applied to names declared const or static, 770 // and cannot be applied to reference members. 771 switch (DS.getStorageClassSpec()) { 772 case DeclSpec::SCS_unspecified: 773 case DeclSpec::SCS_typedef: 774 case DeclSpec::SCS_static: 775 // FALL THROUGH. 776 break; 777 case DeclSpec::SCS_mutable: 778 if (isFunc) { 779 if (DS.getStorageClassSpecLoc().isValid()) 780 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 781 else 782 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 783 784 // FIXME: It would be nicer if the keyword was ignored only for this 785 // declarator. Otherwise we could get follow-up errors. 786 D.getMutableDeclSpec().ClearStorageClassSpecs(); 787 } else { 788 QualType T = GetTypeForDeclarator(D, S); 789 diag::kind err = static_cast<diag::kind>(0); 790 if (T->isReferenceType()) 791 err = diag::err_mutable_reference; 792 else if (T.isConstQualified()) 793 err = diag::err_mutable_const; 794 if (err != 0) { 795 if (DS.getStorageClassSpecLoc().isValid()) 796 Diag(DS.getStorageClassSpecLoc(), err); 797 else 798 Diag(DS.getThreadSpecLoc(), err); 799 // FIXME: It would be nicer if the keyword was ignored only for this 800 // declarator. Otherwise we could get follow-up errors. 801 D.getMutableDeclSpec().ClearStorageClassSpecs(); 802 } 803 } 804 break; 805 default: 806 if (DS.getStorageClassSpecLoc().isValid()) 807 Diag(DS.getStorageClassSpecLoc(), 808 diag::err_storageclass_invalid_for_member); 809 else 810 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 811 D.getMutableDeclSpec().ClearStorageClassSpecs(); 812 } 813 814 if (!isFunc && 815 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 816 D.getNumTypeObjects() == 0) { 817 // Check also for this case: 818 // 819 // typedef int f(); 820 // f a; 821 // 822 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 823 isFunc = TDType->isFunctionType(); 824 } 825 826 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 827 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 828 !isFunc); 829 830 Decl *Member; 831 if (isInstField) { 832 // FIXME: Check for template parameters! 833 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 834 AS); 835 assert(Member && "HandleField never returns null"); 836 } else { 837 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false) 838 .getAs<Decl>(); 839 if (!Member) { 840 if (BitWidth) DeleteExpr(BitWidth); 841 return DeclPtrTy(); 842 } 843 844 // Non-instance-fields can't have a bitfield. 845 if (BitWidth) { 846 if (Member->isInvalidDecl()) { 847 // don't emit another diagnostic. 848 } else if (isa<VarDecl>(Member)) { 849 // C++ 9.6p3: A bit-field shall not be a static member. 850 // "static member 'A' cannot be a bit-field" 851 Diag(Loc, diag::err_static_not_bitfield) 852 << Name << BitWidth->getSourceRange(); 853 } else if (isa<TypedefDecl>(Member)) { 854 // "typedef member 'x' cannot be a bit-field" 855 Diag(Loc, diag::err_typedef_not_bitfield) 856 << Name << BitWidth->getSourceRange(); 857 } else { 858 // A function typedef ("typedef int f(); f a;"). 859 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 860 Diag(Loc, diag::err_not_integral_type_bitfield) 861 << Name << cast<ValueDecl>(Member)->getType() 862 << BitWidth->getSourceRange(); 863 } 864 865 DeleteExpr(BitWidth); 866 BitWidth = 0; 867 Member->setInvalidDecl(); 868 } 869 870 Member->setAccess(AS); 871 872 // If we have declared a member function template, set the access of the 873 // templated declaration as well. 874 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 875 FunTmpl->getTemplatedDecl()->setAccess(AS); 876 } 877 878 assert((Name || isInstField) && "No identifier for non-field ?"); 879 880 if (Init) 881 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 882 if (Deleted) // FIXME: Source location is not very good. 883 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 884 885 if (isInstField) { 886 FieldCollector->Add(cast<FieldDecl>(Member)); 887 return DeclPtrTy(); 888 } 889 return DeclPtrTy::make(Member); 890} 891 892/// ActOnMemInitializer - Handle a C++ member initializer. 893Sema::MemInitResult 894Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 895 Scope *S, 896 const CXXScopeSpec &SS, 897 IdentifierInfo *MemberOrBase, 898 TypeTy *TemplateTypeTy, 899 SourceLocation IdLoc, 900 SourceLocation LParenLoc, 901 ExprTy **Args, unsigned NumArgs, 902 SourceLocation *CommaLocs, 903 SourceLocation RParenLoc) { 904 if (!ConstructorD) 905 return true; 906 907 AdjustDeclIfTemplate(ConstructorD); 908 909 CXXConstructorDecl *Constructor 910 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 911 if (!Constructor) { 912 // The user wrote a constructor initializer on a function that is 913 // not a C++ constructor. Ignore the error for now, because we may 914 // have more member initializers coming; we'll diagnose it just 915 // once in ActOnMemInitializers. 916 return true; 917 } 918 919 CXXRecordDecl *ClassDecl = Constructor->getParent(); 920 921 // C++ [class.base.init]p2: 922 // Names in a mem-initializer-id are looked up in the scope of the 923 // constructor’s class and, if not found in that scope, are looked 924 // up in the scope containing the constructor’s 925 // definition. [Note: if the constructor’s class contains a member 926 // with the same name as a direct or virtual base class of the 927 // class, a mem-initializer-id naming the member or base class and 928 // composed of a single identifier refers to the class member. A 929 // mem-initializer-id for the hidden base class may be specified 930 // using a qualified name. ] 931 if (!SS.getScopeRep() && !TemplateTypeTy) { 932 // Look for a member, first. 933 FieldDecl *Member = 0; 934 DeclContext::lookup_result Result 935 = ClassDecl->lookup(MemberOrBase); 936 if (Result.first != Result.second) 937 Member = dyn_cast<FieldDecl>(*Result.first); 938 939 // FIXME: Handle members of an anonymous union. 940 941 if (Member) 942 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 943 RParenLoc); 944 } 945 // It didn't name a member, so see if it names a class. 946 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 947 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 948 if (!BaseTy) 949 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 950 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 951 952 QualType BaseType = GetTypeFromParser(BaseTy); 953 954 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 955 RParenLoc, ClassDecl); 956} 957 958Sema::MemInitResult 959Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 960 unsigned NumArgs, SourceLocation IdLoc, 961 SourceLocation RParenLoc) { 962 bool HasDependentArg = false; 963 for (unsigned i = 0; i < NumArgs; i++) 964 HasDependentArg |= Args[i]->isTypeDependent(); 965 966 CXXConstructorDecl *C = 0; 967 QualType FieldType = Member->getType(); 968 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 969 FieldType = Array->getElementType(); 970 if (FieldType->isDependentType()) { 971 // Can't check init for dependent type. 972 } else if (FieldType->getAs<RecordType>()) { 973 if (!HasDependentArg) { 974 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 975 976 C = PerformInitializationByConstructor(FieldType, 977 MultiExprArg(*this, 978 (void**)Args, 979 NumArgs), 980 IdLoc, 981 SourceRange(IdLoc, RParenLoc), 982 Member->getDeclName(), IK_Direct, 983 ConstructorArgs); 984 985 if (C) { 986 // Take over the constructor arguments as our own. 987 NumArgs = ConstructorArgs.size(); 988 Args = (Expr **)ConstructorArgs.take(); 989 } 990 } 991 } else if (NumArgs != 1 && NumArgs != 0) { 992 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 993 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 994 } else if (!HasDependentArg) { 995 Expr *NewExp; 996 if (NumArgs == 0) { 997 if (FieldType->isReferenceType()) { 998 Diag(IdLoc, diag::err_null_intialized_reference_member) 999 << Member->getDeclName(); 1000 return Diag(Member->getLocation(), diag::note_declared_at); 1001 } 1002 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc); 1003 NumArgs = 1; 1004 } 1005 else 1006 NewExp = (Expr*)Args[0]; 1007 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 1008 return true; 1009 Args[0] = NewExp; 1010 } 1011 // FIXME: Perform direct initialization of the member. 1012 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 1013 NumArgs, C, IdLoc, RParenLoc); 1014} 1015 1016Sema::MemInitResult 1017Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 1018 unsigned NumArgs, SourceLocation IdLoc, 1019 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 1020 bool HasDependentArg = false; 1021 for (unsigned i = 0; i < NumArgs; i++) 1022 HasDependentArg |= Args[i]->isTypeDependent(); 1023 1024 if (!BaseType->isDependentType()) { 1025 if (!BaseType->isRecordType()) 1026 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 1027 << BaseType << SourceRange(IdLoc, RParenLoc); 1028 1029 // C++ [class.base.init]p2: 1030 // [...] Unless the mem-initializer-id names a nonstatic data 1031 // member of the constructor’s class or a direct or virtual base 1032 // of that class, the mem-initializer is ill-formed. A 1033 // mem-initializer-list can initialize a base class using any 1034 // name that denotes that base class type. 1035 1036 // First, check for a direct base class. 1037 const CXXBaseSpecifier *DirectBaseSpec = 0; 1038 for (CXXRecordDecl::base_class_const_iterator Base = 1039 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 1040 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 1041 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 1042 // We found a direct base of this type. That's what we're 1043 // initializing. 1044 DirectBaseSpec = &*Base; 1045 break; 1046 } 1047 } 1048 1049 // Check for a virtual base class. 1050 // FIXME: We might be able to short-circuit this if we know in advance that 1051 // there are no virtual bases. 1052 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1053 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1054 // We haven't found a base yet; search the class hierarchy for a 1055 // virtual base class. 1056 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1057 /*DetectVirtual=*/false); 1058 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 1059 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1060 Path != Paths.end(); ++Path) { 1061 if (Path->back().Base->isVirtual()) { 1062 VirtualBaseSpec = Path->back().Base; 1063 break; 1064 } 1065 } 1066 } 1067 } 1068 1069 // C++ [base.class.init]p2: 1070 // If a mem-initializer-id is ambiguous because it designates both 1071 // a direct non-virtual base class and an inherited virtual base 1072 // class, the mem-initializer is ill-formed. 1073 if (DirectBaseSpec && VirtualBaseSpec) 1074 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 1075 << BaseType << SourceRange(IdLoc, RParenLoc); 1076 // C++ [base.class.init]p2: 1077 // Unless the mem-initializer-id names a nonstatic data membeer of the 1078 // constructor's class ot a direst or virtual base of that class, the 1079 // mem-initializer is ill-formed. 1080 if (!DirectBaseSpec && !VirtualBaseSpec) 1081 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 1082 << BaseType << ClassDecl->getNameAsCString() 1083 << SourceRange(IdLoc, RParenLoc); 1084 } 1085 1086 CXXConstructorDecl *C = 0; 1087 if (!BaseType->isDependentType() && !HasDependentArg) { 1088 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 1089 Context.getCanonicalType(BaseType)); 1090 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1091 1092 C = PerformInitializationByConstructor(BaseType, 1093 MultiExprArg(*this, 1094 (void**)Args, NumArgs), 1095 IdLoc, SourceRange(IdLoc, RParenLoc), 1096 Name, IK_Direct, 1097 ConstructorArgs); 1098 if (C) { 1099 // Take over the constructor arguments as our own. 1100 NumArgs = ConstructorArgs.size(); 1101 Args = (Expr **)ConstructorArgs.take(); 1102 } 1103 } 1104 1105 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 1106 NumArgs, C, IdLoc, RParenLoc); 1107} 1108 1109void 1110Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1111 CXXBaseOrMemberInitializer **Initializers, 1112 unsigned NumInitializers, 1113 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases, 1114 llvm::SmallVectorImpl<FieldDecl *>&Fields) { 1115 // We need to build the initializer AST according to order of construction 1116 // and not what user specified in the Initializers list. 1117 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1118 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 1119 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1120 bool HasDependentBaseInit = false; 1121 1122 for (unsigned i = 0; i < NumInitializers; i++) { 1123 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1124 if (Member->isBaseInitializer()) { 1125 if (Member->getBaseClass()->isDependentType()) 1126 HasDependentBaseInit = true; 1127 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1128 } else { 1129 AllBaseFields[Member->getMember()] = Member; 1130 } 1131 } 1132 1133 if (HasDependentBaseInit) { 1134 // FIXME. This does not preserve the ordering of the initializers. 1135 // Try (with -Wreorder) 1136 // template<class X> struct A {}; 1137 // template<class X> struct B : A<X> { 1138 // B() : x1(10), A<X>() {} 1139 // int x1; 1140 // }; 1141 // B<int> x; 1142 // On seeing one dependent type, we should essentially exit this routine 1143 // while preserving user-declared initializer list. When this routine is 1144 // called during instantiatiation process, this routine will rebuild the 1145 // oderdered initializer list correctly. 1146 1147 // If we have a dependent base initialization, we can't determine the 1148 // association between initializers and bases; just dump the known 1149 // initializers into the list, and don't try to deal with other bases. 1150 for (unsigned i = 0; i < NumInitializers; i++) { 1151 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1152 if (Member->isBaseInitializer()) 1153 AllToInit.push_back(Member); 1154 } 1155 } else { 1156 // Push virtual bases before others. 1157 for (CXXRecordDecl::base_class_iterator VBase = 1158 ClassDecl->vbases_begin(), 1159 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1160 if (VBase->getType()->isDependentType()) 1161 continue; 1162 if (CXXBaseOrMemberInitializer *Value = 1163 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1164 CXXRecordDecl *BaseDecl = 1165 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1166 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1167 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 1168 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1169 AllToInit.push_back(Value); 1170 } 1171 else { 1172 CXXRecordDecl *VBaseDecl = 1173 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1174 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null"); 1175 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context); 1176 if (!Ctor) 1177 Bases.push_back(VBase); 1178 else 1179 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1180 1181 CXXBaseOrMemberInitializer *Member = 1182 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0, 1183 Ctor, 1184 SourceLocation(), 1185 SourceLocation()); 1186 AllToInit.push_back(Member); 1187 } 1188 } 1189 1190 for (CXXRecordDecl::base_class_iterator Base = 1191 ClassDecl->bases_begin(), 1192 E = ClassDecl->bases_end(); Base != E; ++Base) { 1193 // Virtuals are in the virtual base list and already constructed. 1194 if (Base->isVirtual()) 1195 continue; 1196 // Skip dependent types. 1197 if (Base->getType()->isDependentType()) 1198 continue; 1199 if (CXXBaseOrMemberInitializer *Value = 1200 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1201 CXXRecordDecl *BaseDecl = 1202 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1203 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1204 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 1205 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1206 AllToInit.push_back(Value); 1207 } 1208 else { 1209 CXXRecordDecl *BaseDecl = 1210 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1211 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1212 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context); 1213 if (!Ctor) 1214 Bases.push_back(Base); 1215 else 1216 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1217 1218 CXXBaseOrMemberInitializer *Member = 1219 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0, 1220 BaseDecl->getDefaultConstructor(Context), 1221 SourceLocation(), 1222 SourceLocation()); 1223 AllToInit.push_back(Member); 1224 } 1225 } 1226 } 1227 1228 // non-static data members. 1229 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1230 E = ClassDecl->field_end(); Field != E; ++Field) { 1231 if ((*Field)->isAnonymousStructOrUnion()) { 1232 if (const RecordType *FieldClassType = 1233 Field->getType()->getAs<RecordType>()) { 1234 CXXRecordDecl *FieldClassDecl 1235 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1236 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1237 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1238 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1239 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1240 // set to the anonymous union data member used in the initializer 1241 // list. 1242 Value->setMember(*Field); 1243 Value->setAnonUnionMember(*FA); 1244 AllToInit.push_back(Value); 1245 break; 1246 } 1247 } 1248 } 1249 continue; 1250 } 1251 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1252 QualType FT = (*Field)->getType(); 1253 if (const RecordType* RT = FT->getAs<RecordType>()) { 1254 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl()); 1255 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1256 if (CXXConstructorDecl *Ctor = 1257 FieldRecDecl->getDefaultConstructor(Context)) 1258 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1259 } 1260 AllToInit.push_back(Value); 1261 continue; 1262 } 1263 1264 QualType FT = Context.getBaseElementType((*Field)->getType()); 1265 if (const RecordType* RT = FT->getAs<RecordType>()) { 1266 CXXConstructorDecl *Ctor = 1267 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context); 1268 if (!Ctor && !FT->isDependentType()) 1269 Fields.push_back(*Field); 1270 CXXBaseOrMemberInitializer *Member = 1271 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0, 1272 Ctor, 1273 SourceLocation(), 1274 SourceLocation()); 1275 AllToInit.push_back(Member); 1276 if (Ctor) 1277 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1278 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) { 1279 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1280 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1281 Diag((*Field)->getLocation(), diag::note_declared_at); 1282 } 1283 } 1284 else if (FT->isReferenceType()) { 1285 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1286 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName(); 1287 Diag((*Field)->getLocation(), diag::note_declared_at); 1288 } 1289 else if (FT.isConstQualified()) { 1290 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1291 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1292 Diag((*Field)->getLocation(), diag::note_declared_at); 1293 } 1294 } 1295 1296 NumInitializers = AllToInit.size(); 1297 if (NumInitializers > 0) { 1298 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1299 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1300 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1301 1302 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1303 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) 1304 baseOrMemberInitializers[Idx] = AllToInit[Idx]; 1305 } 1306} 1307 1308void 1309Sema::BuildBaseOrMemberInitializers(ASTContext &C, 1310 CXXConstructorDecl *Constructor, 1311 CXXBaseOrMemberInitializer **Initializers, 1312 unsigned NumInitializers 1313 ) { 1314 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases; 1315 llvm::SmallVector<FieldDecl *, 4>Members; 1316 1317 setBaseOrMemberInitializers(Constructor, 1318 Initializers, NumInitializers, Bases, Members); 1319 for (unsigned int i = 0; i < Bases.size(); i++) 1320 Diag(Bases[i]->getSourceRange().getBegin(), 1321 diag::err_missing_default_constructor) << 0 << Bases[i]->getType(); 1322 for (unsigned int i = 0; i < Members.size(); i++) 1323 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor) 1324 << 1 << Members[i]->getType(); 1325} 1326 1327static void *GetKeyForTopLevelField(FieldDecl *Field) { 1328 // For anonymous unions, use the class declaration as the key. 1329 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1330 if (RT->getDecl()->isAnonymousStructOrUnion()) 1331 return static_cast<void *>(RT->getDecl()); 1332 } 1333 return static_cast<void *>(Field); 1334} 1335 1336static void *GetKeyForBase(QualType BaseType) { 1337 if (const RecordType *RT = BaseType->getAs<RecordType>()) 1338 return (void *)RT; 1339 1340 assert(0 && "Unexpected base type!"); 1341 return 0; 1342} 1343 1344static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 1345 bool MemberMaybeAnon = false) { 1346 // For fields injected into the class via declaration of an anonymous union, 1347 // use its anonymous union class declaration as the unique key. 1348 if (Member->isMemberInitializer()) { 1349 FieldDecl *Field = Member->getMember(); 1350 1351 // After BuildBaseOrMemberInitializers call, Field is the anonymous union 1352 // data member of the class. Data member used in the initializer list is 1353 // in AnonUnionMember field. 1354 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1355 Field = Member->getAnonUnionMember(); 1356 if (Field->getDeclContext()->isRecord()) { 1357 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 1358 if (RD->isAnonymousStructOrUnion()) 1359 return static_cast<void *>(RD); 1360 } 1361 return static_cast<void *>(Field); 1362 } 1363 1364 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 1365} 1366 1367void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1368 SourceLocation ColonLoc, 1369 MemInitTy **MemInits, unsigned NumMemInits) { 1370 if (!ConstructorDecl) 1371 return; 1372 1373 AdjustDeclIfTemplate(ConstructorDecl); 1374 1375 CXXConstructorDecl *Constructor 1376 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1377 1378 if (!Constructor) { 1379 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1380 return; 1381 } 1382 1383 if (!Constructor->isDependentContext()) { 1384 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 1385 bool err = false; 1386 for (unsigned i = 0; i < NumMemInits; i++) { 1387 CXXBaseOrMemberInitializer *Member = 1388 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1389 void *KeyToMember = GetKeyForMember(Member); 1390 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1391 if (!PrevMember) { 1392 PrevMember = Member; 1393 continue; 1394 } 1395 if (FieldDecl *Field = Member->getMember()) 1396 Diag(Member->getSourceLocation(), 1397 diag::error_multiple_mem_initialization) 1398 << Field->getNameAsString(); 1399 else { 1400 Type *BaseClass = Member->getBaseClass(); 1401 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1402 Diag(Member->getSourceLocation(), 1403 diag::error_multiple_base_initialization) 1404 << QualType(BaseClass, 0); 1405 } 1406 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1407 << 0; 1408 err = true; 1409 } 1410 1411 if (err) 1412 return; 1413 } 1414 1415 BuildBaseOrMemberInitializers(Context, Constructor, 1416 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 1417 NumMemInits); 1418 1419 if (Constructor->isDependentContext()) 1420 return; 1421 1422 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1423 Diagnostic::Ignored && 1424 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1425 Diagnostic::Ignored) 1426 return; 1427 1428 // Also issue warning if order of ctor-initializer list does not match order 1429 // of 1) base class declarations and 2) order of non-static data members. 1430 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1431 1432 CXXRecordDecl *ClassDecl 1433 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1434 // Push virtual bases before others. 1435 for (CXXRecordDecl::base_class_iterator VBase = 1436 ClassDecl->vbases_begin(), 1437 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1438 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 1439 1440 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1441 E = ClassDecl->bases_end(); Base != E; ++Base) { 1442 // Virtuals are alread in the virtual base list and are constructed 1443 // first. 1444 if (Base->isVirtual()) 1445 continue; 1446 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 1447 } 1448 1449 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1450 E = ClassDecl->field_end(); Field != E; ++Field) 1451 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1452 1453 int Last = AllBaseOrMembers.size(); 1454 int curIndex = 0; 1455 CXXBaseOrMemberInitializer *PrevMember = 0; 1456 for (unsigned i = 0; i < NumMemInits; i++) { 1457 CXXBaseOrMemberInitializer *Member = 1458 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1459 void *MemberInCtorList = GetKeyForMember(Member, true); 1460 1461 for (; curIndex < Last; curIndex++) 1462 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1463 break; 1464 if (curIndex == Last) { 1465 assert(PrevMember && "Member not in member list?!"); 1466 // Initializer as specified in ctor-initializer list is out of order. 1467 // Issue a warning diagnostic. 1468 if (PrevMember->isBaseInitializer()) { 1469 // Diagnostics is for an initialized base class. 1470 Type *BaseClass = PrevMember->getBaseClass(); 1471 Diag(PrevMember->getSourceLocation(), 1472 diag::warn_base_initialized) 1473 << QualType(BaseClass, 0); 1474 } else { 1475 FieldDecl *Field = PrevMember->getMember(); 1476 Diag(PrevMember->getSourceLocation(), 1477 diag::warn_field_initialized) 1478 << Field->getNameAsString(); 1479 } 1480 // Also the note! 1481 if (FieldDecl *Field = Member->getMember()) 1482 Diag(Member->getSourceLocation(), 1483 diag::note_fieldorbase_initialized_here) << 0 1484 << Field->getNameAsString(); 1485 else { 1486 Type *BaseClass = Member->getBaseClass(); 1487 Diag(Member->getSourceLocation(), 1488 diag::note_fieldorbase_initialized_here) << 1 1489 << QualType(BaseClass, 0); 1490 } 1491 for (curIndex = 0; curIndex < Last; curIndex++) 1492 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1493 break; 1494 } 1495 PrevMember = Member; 1496 } 1497} 1498 1499void 1500Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) { 1501 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext()); 1502 llvm::SmallVector<uintptr_t, 32> AllToDestruct; 1503 1504 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1505 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1506 if (VBase->getType()->isDependentType()) 1507 continue; 1508 // Skip over virtual bases which have trivial destructors. 1509 CXXRecordDecl *BaseClassDecl 1510 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1511 if (BaseClassDecl->hasTrivialDestructor()) 1512 continue; 1513 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1514 MarkDeclarationReferenced(Destructor->getLocation(), 1515 const_cast<CXXDestructorDecl*>(Dtor)); 1516 1517 uintptr_t Member = 1518 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr()) 1519 | CXXDestructorDecl::VBASE; 1520 AllToDestruct.push_back(Member); 1521 } 1522 for (CXXRecordDecl::base_class_iterator Base = 1523 ClassDecl->bases_begin(), 1524 E = ClassDecl->bases_end(); Base != E; ++Base) { 1525 if (Base->isVirtual()) 1526 continue; 1527 if (Base->getType()->isDependentType()) 1528 continue; 1529 // Skip over virtual bases which have trivial destructors. 1530 CXXRecordDecl *BaseClassDecl 1531 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1532 if (BaseClassDecl->hasTrivialDestructor()) 1533 continue; 1534 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1535 MarkDeclarationReferenced(Destructor->getLocation(), 1536 const_cast<CXXDestructorDecl*>(Dtor)); 1537 uintptr_t Member = 1538 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr()) 1539 | CXXDestructorDecl::DRCTNONVBASE; 1540 AllToDestruct.push_back(Member); 1541 } 1542 1543 // non-static data members. 1544 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1545 E = ClassDecl->field_end(); Field != E; ++Field) { 1546 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 1547 1548 if (const RecordType* RT = FieldType->getAs<RecordType>()) { 1549 // Skip over virtual bases which have trivial destructors. 1550 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1551 if (FieldClassDecl->hasTrivialDestructor()) 1552 continue; 1553 if (const CXXDestructorDecl *Dtor = 1554 FieldClassDecl->getDestructor(Context)) 1555 MarkDeclarationReferenced(Destructor->getLocation(), 1556 const_cast<CXXDestructorDecl*>(Dtor)); 1557 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field); 1558 AllToDestruct.push_back(Member); 1559 } 1560 } 1561 1562 unsigned NumDestructions = AllToDestruct.size(); 1563 if (NumDestructions > 0) { 1564 Destructor->setNumBaseOrMemberDestructions(NumDestructions); 1565 uintptr_t *BaseOrMemberDestructions = 1566 new (Context) uintptr_t [NumDestructions]; 1567 // Insert in reverse order. 1568 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx) 1569 BaseOrMemberDestructions[i++] = AllToDestruct[Idx]; 1570 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions); 1571 } 1572} 1573 1574void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1575 if (!CDtorDecl) 1576 return; 1577 1578 AdjustDeclIfTemplate(CDtorDecl); 1579 1580 if (CXXConstructorDecl *Constructor 1581 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1582 BuildBaseOrMemberInitializers(Context, 1583 Constructor, 1584 (CXXBaseOrMemberInitializer **)0, 0); 1585} 1586 1587namespace { 1588 /// PureVirtualMethodCollector - traverses a class and its superclasses 1589 /// and determines if it has any pure virtual methods. 1590 class VISIBILITY_HIDDEN PureVirtualMethodCollector { 1591 ASTContext &Context; 1592 1593 public: 1594 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1595 1596 private: 1597 MethodList Methods; 1598 1599 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1600 1601 public: 1602 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1603 : Context(Ctx) { 1604 1605 MethodList List; 1606 Collect(RD, List); 1607 1608 // Copy the temporary list to methods, and make sure to ignore any 1609 // null entries. 1610 for (size_t i = 0, e = List.size(); i != e; ++i) { 1611 if (List[i]) 1612 Methods.push_back(List[i]); 1613 } 1614 } 1615 1616 bool empty() const { return Methods.empty(); } 1617 1618 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1619 MethodList::const_iterator methods_end() { return Methods.end(); } 1620 }; 1621 1622 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1623 MethodList& Methods) { 1624 // First, collect the pure virtual methods for the base classes. 1625 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1626 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1627 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1628 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1629 if (BaseDecl && BaseDecl->isAbstract()) 1630 Collect(BaseDecl, Methods); 1631 } 1632 } 1633 1634 // Next, zero out any pure virtual methods that this class overrides. 1635 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1636 1637 MethodSetTy OverriddenMethods; 1638 size_t MethodsSize = Methods.size(); 1639 1640 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1641 i != e; ++i) { 1642 // Traverse the record, looking for methods. 1643 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1644 // If the method is pure virtual, add it to the methods vector. 1645 if (MD->isPure()) { 1646 Methods.push_back(MD); 1647 continue; 1648 } 1649 1650 // Otherwise, record all the overridden methods in our set. 1651 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1652 E = MD->end_overridden_methods(); I != E; ++I) { 1653 // Keep track of the overridden methods. 1654 OverriddenMethods.insert(*I); 1655 } 1656 } 1657 } 1658 1659 // Now go through the methods and zero out all the ones we know are 1660 // overridden. 1661 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1662 if (OverriddenMethods.count(Methods[i])) 1663 Methods[i] = 0; 1664 } 1665 1666 } 1667} 1668 1669 1670bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1671 unsigned DiagID, AbstractDiagSelID SelID, 1672 const CXXRecordDecl *CurrentRD) { 1673 if (SelID == -1) 1674 return RequireNonAbstractType(Loc, T, 1675 PDiag(DiagID), CurrentRD); 1676 else 1677 return RequireNonAbstractType(Loc, T, 1678 PDiag(DiagID) << SelID, CurrentRD); 1679} 1680 1681bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1682 const PartialDiagnostic &PD, 1683 const CXXRecordDecl *CurrentRD) { 1684 if (!getLangOptions().CPlusPlus) 1685 return false; 1686 1687 if (const ArrayType *AT = Context.getAsArrayType(T)) 1688 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1689 CurrentRD); 1690 1691 if (const PointerType *PT = T->getAs<PointerType>()) { 1692 // Find the innermost pointer type. 1693 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1694 PT = T; 1695 1696 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1697 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1698 } 1699 1700 const RecordType *RT = T->getAs<RecordType>(); 1701 if (!RT) 1702 return false; 1703 1704 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1705 if (!RD) 1706 return false; 1707 1708 if (CurrentRD && CurrentRD != RD) 1709 return false; 1710 1711 if (!RD->isAbstract()) 1712 return false; 1713 1714 Diag(Loc, PD) << RD->getDeclName(); 1715 1716 // Check if we've already emitted the list of pure virtual functions for this 1717 // class. 1718 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1719 return true; 1720 1721 PureVirtualMethodCollector Collector(Context, RD); 1722 1723 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1724 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1725 const CXXMethodDecl *MD = *I; 1726 1727 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1728 MD->getDeclName(); 1729 } 1730 1731 if (!PureVirtualClassDiagSet) 1732 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1733 PureVirtualClassDiagSet->insert(RD); 1734 1735 return true; 1736} 1737 1738namespace { 1739 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser 1740 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1741 Sema &SemaRef; 1742 CXXRecordDecl *AbstractClass; 1743 1744 bool VisitDeclContext(const DeclContext *DC) { 1745 bool Invalid = false; 1746 1747 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1748 E = DC->decls_end(); I != E; ++I) 1749 Invalid |= Visit(*I); 1750 1751 return Invalid; 1752 } 1753 1754 public: 1755 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1756 : SemaRef(SemaRef), AbstractClass(ac) { 1757 Visit(SemaRef.Context.getTranslationUnitDecl()); 1758 } 1759 1760 bool VisitFunctionDecl(const FunctionDecl *FD) { 1761 if (FD->isThisDeclarationADefinition()) { 1762 // No need to do the check if we're in a definition, because it requires 1763 // that the return/param types are complete. 1764 // because that requires 1765 return VisitDeclContext(FD); 1766 } 1767 1768 // Check the return type. 1769 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 1770 bool Invalid = 1771 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1772 diag::err_abstract_type_in_decl, 1773 Sema::AbstractReturnType, 1774 AbstractClass); 1775 1776 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1777 E = FD->param_end(); I != E; ++I) { 1778 const ParmVarDecl *VD = *I; 1779 Invalid |= 1780 SemaRef.RequireNonAbstractType(VD->getLocation(), 1781 VD->getOriginalType(), 1782 diag::err_abstract_type_in_decl, 1783 Sema::AbstractParamType, 1784 AbstractClass); 1785 } 1786 1787 return Invalid; 1788 } 1789 1790 bool VisitDecl(const Decl* D) { 1791 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1792 return VisitDeclContext(DC); 1793 1794 return false; 1795 } 1796 }; 1797} 1798 1799void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1800 DeclPtrTy TagDecl, 1801 SourceLocation LBrac, 1802 SourceLocation RBrac) { 1803 if (!TagDecl) 1804 return; 1805 1806 AdjustDeclIfTemplate(TagDecl); 1807 ActOnFields(S, RLoc, TagDecl, 1808 (DeclPtrTy*)FieldCollector->getCurFields(), 1809 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1810 1811 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1812 if (!RD->isAbstract()) { 1813 // Collect all the pure virtual methods and see if this is an abstract 1814 // class after all. 1815 PureVirtualMethodCollector Collector(Context, RD); 1816 if (!Collector.empty()) 1817 RD->setAbstract(true); 1818 } 1819 1820 if (RD->isAbstract()) 1821 AbstractClassUsageDiagnoser(*this, RD); 1822 1823 if (!RD->isDependentType()) 1824 AddImplicitlyDeclaredMembersToClass(RD); 1825} 1826 1827/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1828/// special functions, such as the default constructor, copy 1829/// constructor, or destructor, to the given C++ class (C++ 1830/// [special]p1). This routine can only be executed just before the 1831/// definition of the class is complete. 1832void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1833 CanQualType ClassType 1834 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1835 1836 // FIXME: Implicit declarations have exception specifications, which are 1837 // the union of the specifications of the implicitly called functions. 1838 1839 if (!ClassDecl->hasUserDeclaredConstructor()) { 1840 // C++ [class.ctor]p5: 1841 // A default constructor for a class X is a constructor of class X 1842 // that can be called without an argument. If there is no 1843 // user-declared constructor for class X, a default constructor is 1844 // implicitly declared. An implicitly-declared default constructor 1845 // is an inline public member of its class. 1846 DeclarationName Name 1847 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1848 CXXConstructorDecl *DefaultCon = 1849 CXXConstructorDecl::Create(Context, ClassDecl, 1850 ClassDecl->getLocation(), Name, 1851 Context.getFunctionType(Context.VoidTy, 1852 0, 0, false, 0), 1853 /*DInfo=*/0, 1854 /*isExplicit=*/false, 1855 /*isInline=*/true, 1856 /*isImplicitlyDeclared=*/true); 1857 DefaultCon->setAccess(AS_public); 1858 DefaultCon->setImplicit(); 1859 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1860 ClassDecl->addDecl(DefaultCon); 1861 } 1862 1863 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1864 // C++ [class.copy]p4: 1865 // If the class definition does not explicitly declare a copy 1866 // constructor, one is declared implicitly. 1867 1868 // C++ [class.copy]p5: 1869 // The implicitly-declared copy constructor for a class X will 1870 // have the form 1871 // 1872 // X::X(const X&) 1873 // 1874 // if 1875 bool HasConstCopyConstructor = true; 1876 1877 // -- each direct or virtual base class B of X has a copy 1878 // constructor whose first parameter is of type const B& or 1879 // const volatile B&, and 1880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1881 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 1882 const CXXRecordDecl *BaseClassDecl 1883 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1884 HasConstCopyConstructor 1885 = BaseClassDecl->hasConstCopyConstructor(Context); 1886 } 1887 1888 // -- for all the nonstatic data members of X that are of a 1889 // class type M (or array thereof), each such class type 1890 // has a copy constructor whose first parameter is of type 1891 // const M& or const volatile M&. 1892 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1893 HasConstCopyConstructor && Field != ClassDecl->field_end(); 1894 ++Field) { 1895 QualType FieldType = (*Field)->getType(); 1896 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1897 FieldType = Array->getElementType(); 1898 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1899 const CXXRecordDecl *FieldClassDecl 1900 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1901 HasConstCopyConstructor 1902 = FieldClassDecl->hasConstCopyConstructor(Context); 1903 } 1904 } 1905 1906 // Otherwise, the implicitly declared copy constructor will have 1907 // the form 1908 // 1909 // X::X(X&) 1910 QualType ArgType = ClassType; 1911 if (HasConstCopyConstructor) 1912 ArgType = ArgType.withConst(); 1913 ArgType = Context.getLValueReferenceType(ArgType); 1914 1915 // An implicitly-declared copy constructor is an inline public 1916 // member of its class. 1917 DeclarationName Name 1918 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1919 CXXConstructorDecl *CopyConstructor 1920 = CXXConstructorDecl::Create(Context, ClassDecl, 1921 ClassDecl->getLocation(), Name, 1922 Context.getFunctionType(Context.VoidTy, 1923 &ArgType, 1, 1924 false, 0), 1925 /*DInfo=*/0, 1926 /*isExplicit=*/false, 1927 /*isInline=*/true, 1928 /*isImplicitlyDeclared=*/true); 1929 CopyConstructor->setAccess(AS_public); 1930 CopyConstructor->setImplicit(); 1931 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 1932 1933 // Add the parameter to the constructor. 1934 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 1935 ClassDecl->getLocation(), 1936 /*IdentifierInfo=*/0, 1937 ArgType, /*DInfo=*/0, 1938 VarDecl::None, 0); 1939 CopyConstructor->setParams(Context, &FromParam, 1); 1940 ClassDecl->addDecl(CopyConstructor); 1941 } 1942 1943 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 1944 // Note: The following rules are largely analoguous to the copy 1945 // constructor rules. Note that virtual bases are not taken into account 1946 // for determining the argument type of the operator. Note also that 1947 // operators taking an object instead of a reference are allowed. 1948 // 1949 // C++ [class.copy]p10: 1950 // If the class definition does not explicitly declare a copy 1951 // assignment operator, one is declared implicitly. 1952 // The implicitly-defined copy assignment operator for a class X 1953 // will have the form 1954 // 1955 // X& X::operator=(const X&) 1956 // 1957 // if 1958 bool HasConstCopyAssignment = true; 1959 1960 // -- each direct base class B of X has a copy assignment operator 1961 // whose parameter is of type const B&, const volatile B& or B, 1962 // and 1963 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1964 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 1965 const CXXRecordDecl *BaseClassDecl 1966 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1967 const CXXMethodDecl *MD = 0; 1968 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 1969 MD); 1970 } 1971 1972 // -- for all the nonstatic data members of X that are of a class 1973 // type M (or array thereof), each such class type has a copy 1974 // assignment operator whose parameter is of type const M&, 1975 // const volatile M& or M. 1976 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1977 HasConstCopyAssignment && Field != ClassDecl->field_end(); 1978 ++Field) { 1979 QualType FieldType = (*Field)->getType(); 1980 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1981 FieldType = Array->getElementType(); 1982 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1983 const CXXRecordDecl *FieldClassDecl 1984 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1985 const CXXMethodDecl *MD = 0; 1986 HasConstCopyAssignment 1987 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 1988 } 1989 } 1990 1991 // Otherwise, the implicitly declared copy assignment operator will 1992 // have the form 1993 // 1994 // X& X::operator=(X&) 1995 QualType ArgType = ClassType; 1996 QualType RetType = Context.getLValueReferenceType(ArgType); 1997 if (HasConstCopyAssignment) 1998 ArgType = ArgType.withConst(); 1999 ArgType = Context.getLValueReferenceType(ArgType); 2000 2001 // An implicitly-declared copy assignment operator is an inline public 2002 // member of its class. 2003 DeclarationName Name = 2004 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2005 CXXMethodDecl *CopyAssignment = 2006 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2007 Context.getFunctionType(RetType, &ArgType, 1, 2008 false, 0), 2009 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 2010 CopyAssignment->setAccess(AS_public); 2011 CopyAssignment->setImplicit(); 2012 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2013 CopyAssignment->setCopyAssignment(true); 2014 2015 // Add the parameter to the operator. 2016 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2017 ClassDecl->getLocation(), 2018 /*IdentifierInfo=*/0, 2019 ArgType, /*DInfo=*/0, 2020 VarDecl::None, 0); 2021 CopyAssignment->setParams(Context, &FromParam, 1); 2022 2023 // Don't call addedAssignmentOperator. There is no way to distinguish an 2024 // implicit from an explicit assignment operator. 2025 ClassDecl->addDecl(CopyAssignment); 2026 } 2027 2028 if (!ClassDecl->hasUserDeclaredDestructor()) { 2029 // C++ [class.dtor]p2: 2030 // If a class has no user-declared destructor, a destructor is 2031 // declared implicitly. An implicitly-declared destructor is an 2032 // inline public member of its class. 2033 DeclarationName Name 2034 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2035 CXXDestructorDecl *Destructor 2036 = CXXDestructorDecl::Create(Context, ClassDecl, 2037 ClassDecl->getLocation(), Name, 2038 Context.getFunctionType(Context.VoidTy, 2039 0, 0, false, 0), 2040 /*isInline=*/true, 2041 /*isImplicitlyDeclared=*/true); 2042 Destructor->setAccess(AS_public); 2043 Destructor->setImplicit(); 2044 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2045 ClassDecl->addDecl(Destructor); 2046 } 2047} 2048 2049void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2050 Decl *D = TemplateD.getAs<Decl>(); 2051 if (!D) 2052 return; 2053 2054 TemplateParameterList *Params = 0; 2055 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2056 Params = Template->getTemplateParameters(); 2057 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2058 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2059 Params = PartialSpec->getTemplateParameters(); 2060 else 2061 return; 2062 2063 for (TemplateParameterList::iterator Param = Params->begin(), 2064 ParamEnd = Params->end(); 2065 Param != ParamEnd; ++Param) { 2066 NamedDecl *Named = cast<NamedDecl>(*Param); 2067 if (Named->getDeclName()) { 2068 S->AddDecl(DeclPtrTy::make(Named)); 2069 IdResolver.AddDecl(Named); 2070 } 2071 } 2072} 2073 2074/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2075/// parsing a top-level (non-nested) C++ class, and we are now 2076/// parsing those parts of the given Method declaration that could 2077/// not be parsed earlier (C++ [class.mem]p2), such as default 2078/// arguments. This action should enter the scope of the given 2079/// Method declaration as if we had just parsed the qualified method 2080/// name. However, it should not bring the parameters into scope; 2081/// that will be performed by ActOnDelayedCXXMethodParameter. 2082void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2083 if (!MethodD) 2084 return; 2085 2086 AdjustDeclIfTemplate(MethodD); 2087 2088 CXXScopeSpec SS; 2089 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2090 QualType ClassTy 2091 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 2092 SS.setScopeRep( 2093 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 2094 ActOnCXXEnterDeclaratorScope(S, SS); 2095} 2096 2097/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2098/// C++ method declaration. We're (re-)introducing the given 2099/// function parameter into scope for use in parsing later parts of 2100/// the method declaration. For example, we could see an 2101/// ActOnParamDefaultArgument event for this parameter. 2102void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2103 if (!ParamD) 2104 return; 2105 2106 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2107 2108 // If this parameter has an unparsed default argument, clear it out 2109 // to make way for the parsed default argument. 2110 if (Param->hasUnparsedDefaultArg()) 2111 Param->setDefaultArg(0); 2112 2113 S->AddDecl(DeclPtrTy::make(Param)); 2114 if (Param->getDeclName()) 2115 IdResolver.AddDecl(Param); 2116} 2117 2118/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2119/// processing the delayed method declaration for Method. The method 2120/// declaration is now considered finished. There may be a separate 2121/// ActOnStartOfFunctionDef action later (not necessarily 2122/// immediately!) for this method, if it was also defined inside the 2123/// class body. 2124void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2125 if (!MethodD) 2126 return; 2127 2128 AdjustDeclIfTemplate(MethodD); 2129 2130 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2131 CXXScopeSpec SS; 2132 QualType ClassTy 2133 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 2134 SS.setScopeRep( 2135 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 2136 ActOnCXXExitDeclaratorScope(S, SS); 2137 2138 // Now that we have our default arguments, check the constructor 2139 // again. It could produce additional diagnostics or affect whether 2140 // the class has implicitly-declared destructors, among other 2141 // things. 2142 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2143 CheckConstructor(Constructor); 2144 2145 // Check the default arguments, which we may have added. 2146 if (!Method->isInvalidDecl()) 2147 CheckCXXDefaultArguments(Method); 2148} 2149 2150/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2151/// the well-formedness of the constructor declarator @p D with type @p 2152/// R. If there are any errors in the declarator, this routine will 2153/// emit diagnostics and set the invalid bit to true. In any case, the type 2154/// will be updated to reflect a well-formed type for the constructor and 2155/// returned. 2156QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2157 FunctionDecl::StorageClass &SC) { 2158 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2159 2160 // C++ [class.ctor]p3: 2161 // A constructor shall not be virtual (10.3) or static (9.4). A 2162 // constructor can be invoked for a const, volatile or const 2163 // volatile object. A constructor shall not be declared const, 2164 // volatile, or const volatile (9.3.2). 2165 if (isVirtual) { 2166 if (!D.isInvalidType()) 2167 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2168 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2169 << SourceRange(D.getIdentifierLoc()); 2170 D.setInvalidType(); 2171 } 2172 if (SC == FunctionDecl::Static) { 2173 if (!D.isInvalidType()) 2174 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2175 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2176 << SourceRange(D.getIdentifierLoc()); 2177 D.setInvalidType(); 2178 SC = FunctionDecl::None; 2179 } 2180 2181 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2182 if (FTI.TypeQuals != 0) { 2183 if (FTI.TypeQuals & Qualifiers::Const) 2184 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2185 << "const" << SourceRange(D.getIdentifierLoc()); 2186 if (FTI.TypeQuals & Qualifiers::Volatile) 2187 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2188 << "volatile" << SourceRange(D.getIdentifierLoc()); 2189 if (FTI.TypeQuals & Qualifiers::Restrict) 2190 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2191 << "restrict" << SourceRange(D.getIdentifierLoc()); 2192 } 2193 2194 // Rebuild the function type "R" without any type qualifiers (in 2195 // case any of the errors above fired) and with "void" as the 2196 // return type, since constructors don't have return types. We 2197 // *always* have to do this, because GetTypeForDeclarator will 2198 // put in a result type of "int" when none was specified. 2199 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2200 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2201 Proto->getNumArgs(), 2202 Proto->isVariadic(), 0); 2203} 2204 2205/// CheckConstructor - Checks a fully-formed constructor for 2206/// well-formedness, issuing any diagnostics required. Returns true if 2207/// the constructor declarator is invalid. 2208void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2209 CXXRecordDecl *ClassDecl 2210 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2211 if (!ClassDecl) 2212 return Constructor->setInvalidDecl(); 2213 2214 // C++ [class.copy]p3: 2215 // A declaration of a constructor for a class X is ill-formed if 2216 // its first parameter is of type (optionally cv-qualified) X and 2217 // either there are no other parameters or else all other 2218 // parameters have default arguments. 2219 if (!Constructor->isInvalidDecl() && 2220 ((Constructor->getNumParams() == 1) || 2221 (Constructor->getNumParams() > 1 && 2222 Constructor->getParamDecl(1)->hasDefaultArg()))) { 2223 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2224 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2225 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2226 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2227 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2228 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 2229 Constructor->setInvalidDecl(); 2230 } 2231 } 2232 2233 // Notify the class that we've added a constructor. 2234 ClassDecl->addedConstructor(Context, Constructor); 2235} 2236 2237static inline bool 2238FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2239 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2240 FTI.ArgInfo[0].Param && 2241 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2242} 2243 2244/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2245/// the well-formednes of the destructor declarator @p D with type @p 2246/// R. If there are any errors in the declarator, this routine will 2247/// emit diagnostics and set the declarator to invalid. Even if this happens, 2248/// will be updated to reflect a well-formed type for the destructor and 2249/// returned. 2250QualType Sema::CheckDestructorDeclarator(Declarator &D, 2251 FunctionDecl::StorageClass& SC) { 2252 // C++ [class.dtor]p1: 2253 // [...] A typedef-name that names a class is a class-name 2254 // (7.1.3); however, a typedef-name that names a class shall not 2255 // be used as the identifier in the declarator for a destructor 2256 // declaration. 2257 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType()); 2258 if (isa<TypedefType>(DeclaratorType)) { 2259 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2260 << DeclaratorType; 2261 D.setInvalidType(); 2262 } 2263 2264 // C++ [class.dtor]p2: 2265 // A destructor is used to destroy objects of its class type. A 2266 // destructor takes no parameters, and no return type can be 2267 // specified for it (not even void). The address of a destructor 2268 // shall not be taken. A destructor shall not be static. A 2269 // destructor can be invoked for a const, volatile or const 2270 // volatile object. A destructor shall not be declared const, 2271 // volatile or const volatile (9.3.2). 2272 if (SC == FunctionDecl::Static) { 2273 if (!D.isInvalidType()) 2274 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2275 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2276 << SourceRange(D.getIdentifierLoc()); 2277 SC = FunctionDecl::None; 2278 D.setInvalidType(); 2279 } 2280 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2281 // Destructors don't have return types, but the parser will 2282 // happily parse something like: 2283 // 2284 // class X { 2285 // float ~X(); 2286 // }; 2287 // 2288 // The return type will be eliminated later. 2289 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2290 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2291 << SourceRange(D.getIdentifierLoc()); 2292 } 2293 2294 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2295 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2296 if (FTI.TypeQuals & Qualifiers::Const) 2297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2298 << "const" << SourceRange(D.getIdentifierLoc()); 2299 if (FTI.TypeQuals & Qualifiers::Volatile) 2300 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2301 << "volatile" << SourceRange(D.getIdentifierLoc()); 2302 if (FTI.TypeQuals & Qualifiers::Restrict) 2303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2304 << "restrict" << SourceRange(D.getIdentifierLoc()); 2305 D.setInvalidType(); 2306 } 2307 2308 // Make sure we don't have any parameters. 2309 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2310 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2311 2312 // Delete the parameters. 2313 FTI.freeArgs(); 2314 D.setInvalidType(); 2315 } 2316 2317 // Make sure the destructor isn't variadic. 2318 if (FTI.isVariadic) { 2319 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2320 D.setInvalidType(); 2321 } 2322 2323 // Rebuild the function type "R" without any type qualifiers or 2324 // parameters (in case any of the errors above fired) and with 2325 // "void" as the return type, since destructors don't have return 2326 // types. We *always* have to do this, because GetTypeForDeclarator 2327 // will put in a result type of "int" when none was specified. 2328 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 2329} 2330 2331/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2332/// well-formednes of the conversion function declarator @p D with 2333/// type @p R. If there are any errors in the declarator, this routine 2334/// will emit diagnostics and return true. Otherwise, it will return 2335/// false. Either way, the type @p R will be updated to reflect a 2336/// well-formed type for the conversion operator. 2337void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2338 FunctionDecl::StorageClass& SC) { 2339 // C++ [class.conv.fct]p1: 2340 // Neither parameter types nor return type can be specified. The 2341 // type of a conversion function (8.3.5) is "function taking no 2342 // parameter returning conversion-type-id." 2343 if (SC == FunctionDecl::Static) { 2344 if (!D.isInvalidType()) 2345 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2346 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2347 << SourceRange(D.getIdentifierLoc()); 2348 D.setInvalidType(); 2349 SC = FunctionDecl::None; 2350 } 2351 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2352 // Conversion functions don't have return types, but the parser will 2353 // happily parse something like: 2354 // 2355 // class X { 2356 // float operator bool(); 2357 // }; 2358 // 2359 // The return type will be changed later anyway. 2360 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2361 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2362 << SourceRange(D.getIdentifierLoc()); 2363 } 2364 2365 // Make sure we don't have any parameters. 2366 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 2367 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2368 2369 // Delete the parameters. 2370 D.getTypeObject(0).Fun.freeArgs(); 2371 D.setInvalidType(); 2372 } 2373 2374 // Make sure the conversion function isn't variadic. 2375 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 2376 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2377 D.setInvalidType(); 2378 } 2379 2380 // C++ [class.conv.fct]p4: 2381 // The conversion-type-id shall not represent a function type nor 2382 // an array type. 2383 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType()); 2384 if (ConvType->isArrayType()) { 2385 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2386 ConvType = Context.getPointerType(ConvType); 2387 D.setInvalidType(); 2388 } else if (ConvType->isFunctionType()) { 2389 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2390 ConvType = Context.getPointerType(ConvType); 2391 D.setInvalidType(); 2392 } 2393 2394 // Rebuild the function type "R" without any parameters (in case any 2395 // of the errors above fired) and with the conversion type as the 2396 // return type. 2397 R = Context.getFunctionType(ConvType, 0, 0, false, 2398 R->getAs<FunctionProtoType>()->getTypeQuals()); 2399 2400 // C++0x explicit conversion operators. 2401 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2402 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2403 diag::warn_explicit_conversion_functions) 2404 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2405} 2406 2407/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2408/// the declaration of the given C++ conversion function. This routine 2409/// is responsible for recording the conversion function in the C++ 2410/// class, if possible. 2411Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2412 assert(Conversion && "Expected to receive a conversion function declaration"); 2413 2414 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2415 2416 // Make sure we aren't redeclaring the conversion function. 2417 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2418 2419 // C++ [class.conv.fct]p1: 2420 // [...] A conversion function is never used to convert a 2421 // (possibly cv-qualified) object to the (possibly cv-qualified) 2422 // same object type (or a reference to it), to a (possibly 2423 // cv-qualified) base class of that type (or a reference to it), 2424 // or to (possibly cv-qualified) void. 2425 // FIXME: Suppress this warning if the conversion function ends up being a 2426 // virtual function that overrides a virtual function in a base class. 2427 QualType ClassType 2428 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2429 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2430 ConvType = ConvTypeRef->getPointeeType(); 2431 if (ConvType->isRecordType()) { 2432 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2433 if (ConvType == ClassType) 2434 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2435 << ClassType; 2436 else if (IsDerivedFrom(ClassType, ConvType)) 2437 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2438 << ClassType << ConvType; 2439 } else if (ConvType->isVoidType()) { 2440 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2441 << ClassType << ConvType; 2442 } 2443 2444 if (Conversion->getPreviousDeclaration()) { 2445 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 2446 if (FunctionTemplateDecl *ConversionTemplate 2447 = Conversion->getDescribedFunctionTemplate()) 2448 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 2449 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 2450 for (OverloadedFunctionDecl::function_iterator 2451 Conv = Conversions->function_begin(), 2452 ConvEnd = Conversions->function_end(); 2453 Conv != ConvEnd; ++Conv) { 2454 if (*Conv == ExpectedPrevDecl) { 2455 *Conv = Conversion; 2456 return DeclPtrTy::make(Conversion); 2457 } 2458 } 2459 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2460 } else if (FunctionTemplateDecl *ConversionTemplate 2461 = Conversion->getDescribedFunctionTemplate()) 2462 ClassDecl->addConversionFunction(ConversionTemplate); 2463 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 2464 ClassDecl->addConversionFunction(Conversion); 2465 2466 return DeclPtrTy::make(Conversion); 2467} 2468 2469//===----------------------------------------------------------------------===// 2470// Namespace Handling 2471//===----------------------------------------------------------------------===// 2472 2473/// ActOnStartNamespaceDef - This is called at the start of a namespace 2474/// definition. 2475Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2476 SourceLocation IdentLoc, 2477 IdentifierInfo *II, 2478 SourceLocation LBrace) { 2479 NamespaceDecl *Namespc = 2480 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2481 Namespc->setLBracLoc(LBrace); 2482 2483 Scope *DeclRegionScope = NamespcScope->getParent(); 2484 2485 if (II) { 2486 // C++ [namespace.def]p2: 2487 // The identifier in an original-namespace-definition shall not have been 2488 // previously defined in the declarative region in which the 2489 // original-namespace-definition appears. The identifier in an 2490 // original-namespace-definition is the name of the namespace. Subsequently 2491 // in that declarative region, it is treated as an original-namespace-name. 2492 2493 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 2494 true); 2495 2496 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2497 // This is an extended namespace definition. 2498 // Attach this namespace decl to the chain of extended namespace 2499 // definitions. 2500 OrigNS->setNextNamespace(Namespc); 2501 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2502 2503 // Remove the previous declaration from the scope. 2504 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2505 IdResolver.RemoveDecl(OrigNS); 2506 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2507 } 2508 } else if (PrevDecl) { 2509 // This is an invalid name redefinition. 2510 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2511 << Namespc->getDeclName(); 2512 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2513 Namespc->setInvalidDecl(); 2514 // Continue on to push Namespc as current DeclContext and return it. 2515 } else if (II->isStr("std") && 2516 CurContext->getLookupContext()->isTranslationUnit()) { 2517 // This is the first "real" definition of the namespace "std", so update 2518 // our cache of the "std" namespace to point at this definition. 2519 if (StdNamespace) { 2520 // We had already defined a dummy namespace "std". Link this new 2521 // namespace definition to the dummy namespace "std". 2522 StdNamespace->setNextNamespace(Namespc); 2523 StdNamespace->setLocation(IdentLoc); 2524 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 2525 } 2526 2527 // Make our StdNamespace cache point at the first real definition of the 2528 // "std" namespace. 2529 StdNamespace = Namespc; 2530 } 2531 2532 PushOnScopeChains(Namespc, DeclRegionScope); 2533 } else { 2534 // Anonymous namespaces. 2535 2536 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 2537 // behaves as if it were replaced by 2538 // namespace unique { /* empty body */ } 2539 // using namespace unique; 2540 // namespace unique { namespace-body } 2541 // where all occurrences of 'unique' in a translation unit are 2542 // replaced by the same identifier and this identifier differs 2543 // from all other identifiers in the entire program. 2544 2545 // We just create the namespace with an empty name and then add an 2546 // implicit using declaration, just like the standard suggests. 2547 // 2548 // CodeGen enforces the "universally unique" aspect by giving all 2549 // declarations semantically contained within an anonymous 2550 // namespace internal linkage. 2551 2552 assert(Namespc->isAnonymousNamespace()); 2553 CurContext->addDecl(Namespc); 2554 2555 UsingDirectiveDecl* UD 2556 = UsingDirectiveDecl::Create(Context, CurContext, 2557 /* 'using' */ LBrace, 2558 /* 'namespace' */ SourceLocation(), 2559 /* qualifier */ SourceRange(), 2560 /* NNS */ NULL, 2561 /* identifier */ SourceLocation(), 2562 Namespc, 2563 /* Ancestor */ CurContext); 2564 UD->setImplicit(); 2565 CurContext->addDecl(UD); 2566 } 2567 2568 // Although we could have an invalid decl (i.e. the namespace name is a 2569 // redefinition), push it as current DeclContext and try to continue parsing. 2570 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2571 // for the namespace has the declarations that showed up in that particular 2572 // namespace definition. 2573 PushDeclContext(NamespcScope, Namespc); 2574 return DeclPtrTy::make(Namespc); 2575} 2576 2577/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2578/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2579void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2580 Decl *Dcl = D.getAs<Decl>(); 2581 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2582 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2583 Namespc->setRBracLoc(RBrace); 2584 PopDeclContext(); 2585} 2586 2587Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2588 SourceLocation UsingLoc, 2589 SourceLocation NamespcLoc, 2590 const CXXScopeSpec &SS, 2591 SourceLocation IdentLoc, 2592 IdentifierInfo *NamespcName, 2593 AttributeList *AttrList) { 2594 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2595 assert(NamespcName && "Invalid NamespcName."); 2596 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2597 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2598 2599 UsingDirectiveDecl *UDir = 0; 2600 2601 // Lookup namespace name. 2602 LookupResult R = LookupParsedName(S, &SS, NamespcName, 2603 LookupNamespaceName, false); 2604 if (R.isAmbiguous()) { 2605 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 2606 return DeclPtrTy(); 2607 } 2608 if (NamedDecl *NS = R) { 2609 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 2610 // C++ [namespace.udir]p1: 2611 // A using-directive specifies that the names in the nominated 2612 // namespace can be used in the scope in which the 2613 // using-directive appears after the using-directive. During 2614 // unqualified name lookup (3.4.1), the names appear as if they 2615 // were declared in the nearest enclosing namespace which 2616 // contains both the using-directive and the nominated 2617 // namespace. [Note: in this context, "contains" means "contains 2618 // directly or indirectly". ] 2619 2620 // Find enclosing context containing both using-directive and 2621 // nominated namespace. 2622 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2623 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2624 CommonAncestor = CommonAncestor->getParent(); 2625 2626 UDir = UsingDirectiveDecl::Create(Context, 2627 CurContext, UsingLoc, 2628 NamespcLoc, 2629 SS.getRange(), 2630 (NestedNameSpecifier *)SS.getScopeRep(), 2631 IdentLoc, 2632 cast<NamespaceDecl>(NS), 2633 CommonAncestor); 2634 PushUsingDirective(S, UDir); 2635 } else { 2636 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2637 } 2638 2639 // FIXME: We ignore attributes for now. 2640 delete AttrList; 2641 return DeclPtrTy::make(UDir); 2642} 2643 2644void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2645 // If scope has associated entity, then using directive is at namespace 2646 // or translation unit scope. We add UsingDirectiveDecls, into 2647 // it's lookup structure. 2648 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2649 Ctx->addDecl(UDir); 2650 else 2651 // Otherwise it is block-sope. using-directives will affect lookup 2652 // only to the end of scope. 2653 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2654} 2655 2656 2657Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2658 AccessSpecifier AS, 2659 SourceLocation UsingLoc, 2660 const CXXScopeSpec &SS, 2661 SourceLocation IdentLoc, 2662 IdentifierInfo *TargetName, 2663 OverloadedOperatorKind Op, 2664 AttributeList *AttrList, 2665 bool IsTypeName) { 2666 assert((TargetName || Op) && "Invalid TargetName."); 2667 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2668 2669 DeclarationName Name; 2670 if (TargetName) 2671 Name = TargetName; 2672 else 2673 Name = Context.DeclarationNames.getCXXOperatorName(Op); 2674 2675 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc, 2676 Name, AttrList, IsTypeName); 2677 if (UD) { 2678 PushOnScopeChains(UD, S); 2679 UD->setAccess(AS); 2680 } 2681 2682 return DeclPtrTy::make(UD); 2683} 2684 2685NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc, 2686 const CXXScopeSpec &SS, 2687 SourceLocation IdentLoc, 2688 DeclarationName Name, 2689 AttributeList *AttrList, 2690 bool IsTypeName) { 2691 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2692 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2693 2694 // FIXME: We ignore attributes for now. 2695 delete AttrList; 2696 2697 if (SS.isEmpty()) { 2698 Diag(IdentLoc, diag::err_using_requires_qualname); 2699 return 0; 2700 } 2701 2702 NestedNameSpecifier *NNS = 2703 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2704 2705 if (isUnknownSpecialization(SS)) { 2706 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc, 2707 SS.getRange(), NNS, 2708 IdentLoc, Name, IsTypeName); 2709 } 2710 2711 DeclContext *LookupContext = 0; 2712 2713 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 2714 // C++0x N2914 [namespace.udecl]p3: 2715 // A using-declaration used as a member-declaration shall refer to a member 2716 // of a base class of the class being defined, shall refer to a member of an 2717 // anonymous union that is a member of a base class of the class being 2718 // defined, or shall refer to an enumerator for an enumeration type that is 2719 // a member of a base class of the class being defined. 2720 const Type *Ty = NNS->getAsType(); 2721 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) { 2722 Diag(SS.getRange().getBegin(), 2723 diag::err_using_decl_nested_name_specifier_is_not_a_base_class) 2724 << NNS << RD->getDeclName(); 2725 return 0; 2726 } 2727 2728 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0)); 2729 LookupContext = BaseTy->getAs<RecordType>()->getDecl(); 2730 } else { 2731 // C++0x N2914 [namespace.udecl]p8: 2732 // A using-declaration for a class member shall be a member-declaration. 2733 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) { 2734 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member) 2735 << SS.getRange(); 2736 return 0; 2737 } 2738 2739 // C++0x N2914 [namespace.udecl]p9: 2740 // In a using-declaration, a prefix :: refers to the global namespace. 2741 if (NNS->getKind() == NestedNameSpecifier::Global) 2742 LookupContext = Context.getTranslationUnitDecl(); 2743 else 2744 LookupContext = NNS->getAsNamespace(); 2745 } 2746 2747 2748 // Lookup target name. 2749 LookupResult R = LookupQualifiedName(LookupContext, 2750 Name, LookupOrdinaryName); 2751 2752 if (!R) { 2753 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange()); 2754 return 0; 2755 } 2756 2757 NamedDecl *ND = R.getAsDecl(); 2758 2759 if (IsTypeName && !isa<TypeDecl>(ND)) { 2760 Diag(IdentLoc, diag::err_using_typename_non_type); 2761 return 0; 2762 } 2763 2764 // C++0x N2914 [namespace.udecl]p6: 2765 // A using-declaration shall not name a namespace. 2766 if (isa<NamespaceDecl>(ND)) { 2767 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 2768 << SS.getRange(); 2769 return 0; 2770 } 2771 2772 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(), 2773 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName); 2774} 2775 2776/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2777/// is a namespace alias, returns the namespace it points to. 2778static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2779 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2780 return AD->getNamespace(); 2781 return dyn_cast_or_null<NamespaceDecl>(D); 2782} 2783 2784Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 2785 SourceLocation NamespaceLoc, 2786 SourceLocation AliasLoc, 2787 IdentifierInfo *Alias, 2788 const CXXScopeSpec &SS, 2789 SourceLocation IdentLoc, 2790 IdentifierInfo *Ident) { 2791 2792 // Lookup the namespace name. 2793 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false); 2794 2795 // Check if we have a previous declaration with the same name. 2796 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) { 2797 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 2798 // We already have an alias with the same name that points to the same 2799 // namespace, so don't create a new one. 2800 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R)) 2801 return DeclPtrTy(); 2802 } 2803 2804 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 2805 diag::err_redefinition_different_kind; 2806 Diag(AliasLoc, DiagID) << Alias; 2807 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2808 return DeclPtrTy(); 2809 } 2810 2811 if (R.isAmbiguous()) { 2812 DiagnoseAmbiguousLookup(R, Ident, IdentLoc); 2813 return DeclPtrTy(); 2814 } 2815 2816 if (!R) { 2817 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 2818 return DeclPtrTy(); 2819 } 2820 2821 NamespaceAliasDecl *AliasDecl = 2822 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 2823 Alias, SS.getRange(), 2824 (NestedNameSpecifier *)SS.getScopeRep(), 2825 IdentLoc, R); 2826 2827 CurContext->addDecl(AliasDecl); 2828 return DeclPtrTy::make(AliasDecl); 2829} 2830 2831void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2832 CXXConstructorDecl *Constructor) { 2833 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 2834 !Constructor->isUsed()) && 2835 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 2836 2837 CXXRecordDecl *ClassDecl 2838 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 2839 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 2840 // Before the implicitly-declared default constructor for a class is 2841 // implicitly defined, all the implicitly-declared default constructors 2842 // for its base class and its non-static data members shall have been 2843 // implicitly defined. 2844 bool err = false; 2845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2846 E = ClassDecl->bases_end(); Base != E; ++Base) { 2847 CXXRecordDecl *BaseClassDecl 2848 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2849 if (!BaseClassDecl->hasTrivialConstructor()) { 2850 if (CXXConstructorDecl *BaseCtor = 2851 BaseClassDecl->getDefaultConstructor(Context)) 2852 MarkDeclarationReferenced(CurrentLocation, BaseCtor); 2853 else { 2854 Diag(CurrentLocation, diag::err_defining_default_ctor) 2855 << Context.getTagDeclType(ClassDecl) << 1 2856 << Context.getTagDeclType(BaseClassDecl); 2857 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl) 2858 << Context.getTagDeclType(BaseClassDecl); 2859 err = true; 2860 } 2861 } 2862 } 2863 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2864 E = ClassDecl->field_end(); Field != E; ++Field) { 2865 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2866 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2867 FieldType = Array->getElementType(); 2868 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2869 CXXRecordDecl *FieldClassDecl 2870 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2871 if (!FieldClassDecl->hasTrivialConstructor()) { 2872 if (CXXConstructorDecl *FieldCtor = 2873 FieldClassDecl->getDefaultConstructor(Context)) 2874 MarkDeclarationReferenced(CurrentLocation, FieldCtor); 2875 else { 2876 Diag(CurrentLocation, diag::err_defining_default_ctor) 2877 << Context.getTagDeclType(ClassDecl) << 0 << 2878 Context.getTagDeclType(FieldClassDecl); 2879 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl) 2880 << Context.getTagDeclType(FieldClassDecl); 2881 err = true; 2882 } 2883 } 2884 } else if (FieldType->isReferenceType()) { 2885 Diag(CurrentLocation, diag::err_unintialized_member) 2886 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2887 Diag((*Field)->getLocation(), diag::note_declared_at); 2888 err = true; 2889 } else if (FieldType.isConstQualified()) { 2890 Diag(CurrentLocation, diag::err_unintialized_member) 2891 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2892 Diag((*Field)->getLocation(), diag::note_declared_at); 2893 err = true; 2894 } 2895 } 2896 if (!err) 2897 Constructor->setUsed(); 2898 else 2899 Constructor->setInvalidDecl(); 2900} 2901 2902void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 2903 CXXDestructorDecl *Destructor) { 2904 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 2905 "DefineImplicitDestructor - call it for implicit default dtor"); 2906 2907 CXXRecordDecl *ClassDecl 2908 = cast<CXXRecordDecl>(Destructor->getDeclContext()); 2909 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 2910 // C++ [class.dtor] p5 2911 // Before the implicitly-declared default destructor for a class is 2912 // implicitly defined, all the implicitly-declared default destructors 2913 // for its base class and its non-static data members shall have been 2914 // implicitly defined. 2915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2916 E = ClassDecl->bases_end(); Base != E; ++Base) { 2917 CXXRecordDecl *BaseClassDecl 2918 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2919 if (!BaseClassDecl->hasTrivialDestructor()) { 2920 if (CXXDestructorDecl *BaseDtor = 2921 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 2922 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 2923 else 2924 assert(false && 2925 "DefineImplicitDestructor - missing dtor in a base class"); 2926 } 2927 } 2928 2929 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2930 E = ClassDecl->field_end(); Field != E; ++Field) { 2931 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2932 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2933 FieldType = Array->getElementType(); 2934 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2935 CXXRecordDecl *FieldClassDecl 2936 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2937 if (!FieldClassDecl->hasTrivialDestructor()) { 2938 if (CXXDestructorDecl *FieldDtor = 2939 const_cast<CXXDestructorDecl*>( 2940 FieldClassDecl->getDestructor(Context))) 2941 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 2942 else 2943 assert(false && 2944 "DefineImplicitDestructor - missing dtor in class of a data member"); 2945 } 2946 } 2947 } 2948 Destructor->setUsed(); 2949} 2950 2951void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 2952 CXXMethodDecl *MethodDecl) { 2953 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 2954 MethodDecl->getOverloadedOperator() == OO_Equal && 2955 !MethodDecl->isUsed()) && 2956 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 2957 2958 CXXRecordDecl *ClassDecl 2959 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 2960 2961 // C++[class.copy] p12 2962 // Before the implicitly-declared copy assignment operator for a class is 2963 // implicitly defined, all implicitly-declared copy assignment operators 2964 // for its direct base classes and its nonstatic data members shall have 2965 // been implicitly defined. 2966 bool err = false; 2967 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2968 E = ClassDecl->bases_end(); Base != E; ++Base) { 2969 CXXRecordDecl *BaseClassDecl 2970 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2971 if (CXXMethodDecl *BaseAssignOpMethod = 2972 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 2973 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 2974 } 2975 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2976 E = ClassDecl->field_end(); Field != E; ++Field) { 2977 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2978 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2979 FieldType = Array->getElementType(); 2980 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2981 CXXRecordDecl *FieldClassDecl 2982 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2983 if (CXXMethodDecl *FieldAssignOpMethod = 2984 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 2985 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 2986 } else if (FieldType->isReferenceType()) { 2987 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2988 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2989 Diag(Field->getLocation(), diag::note_declared_at); 2990 Diag(CurrentLocation, diag::note_first_required_here); 2991 err = true; 2992 } else if (FieldType.isConstQualified()) { 2993 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2994 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2995 Diag(Field->getLocation(), diag::note_declared_at); 2996 Diag(CurrentLocation, diag::note_first_required_here); 2997 err = true; 2998 } 2999 } 3000 if (!err) 3001 MethodDecl->setUsed(); 3002} 3003 3004CXXMethodDecl * 3005Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 3006 CXXRecordDecl *ClassDecl) { 3007 QualType LHSType = Context.getTypeDeclType(ClassDecl); 3008 QualType RHSType(LHSType); 3009 // If class's assignment operator argument is const/volatile qualified, 3010 // look for operator = (const/volatile B&). Otherwise, look for 3011 // operator = (B&). 3012 RHSType = Context.getCVRQualifiedType(RHSType, 3013 ParmDecl->getType().getCVRQualifiers()); 3014 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 3015 LHSType, 3016 SourceLocation())); 3017 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 3018 RHSType, 3019 SourceLocation())); 3020 Expr *Args[2] = { &*LHS, &*RHS }; 3021 OverloadCandidateSet CandidateSet; 3022 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 3023 CandidateSet); 3024 OverloadCandidateSet::iterator Best; 3025 if (BestViableFunction(CandidateSet, 3026 ClassDecl->getLocation(), Best) == OR_Success) 3027 return cast<CXXMethodDecl>(Best->Function); 3028 assert(false && 3029 "getAssignOperatorMethod - copy assignment operator method not found"); 3030 return 0; 3031} 3032 3033void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3034 CXXConstructorDecl *CopyConstructor, 3035 unsigned TypeQuals) { 3036 assert((CopyConstructor->isImplicit() && 3037 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 3038 !CopyConstructor->isUsed()) && 3039 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 3040 3041 CXXRecordDecl *ClassDecl 3042 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 3043 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 3044 // C++ [class.copy] p209 3045 // Before the implicitly-declared copy constructor for a class is 3046 // implicitly defined, all the implicitly-declared copy constructors 3047 // for its base class and its non-static data members shall have been 3048 // implicitly defined. 3049 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 3050 Base != ClassDecl->bases_end(); ++Base) { 3051 CXXRecordDecl *BaseClassDecl 3052 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3053 if (CXXConstructorDecl *BaseCopyCtor = 3054 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 3055 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 3056 } 3057 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3058 FieldEnd = ClassDecl->field_end(); 3059 Field != FieldEnd; ++Field) { 3060 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3061 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3062 FieldType = Array->getElementType(); 3063 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3064 CXXRecordDecl *FieldClassDecl 3065 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3066 if (CXXConstructorDecl *FieldCopyCtor = 3067 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 3068 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 3069 } 3070 } 3071 CopyConstructor->setUsed(); 3072} 3073 3074Sema::OwningExprResult 3075Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3076 CXXConstructorDecl *Constructor, 3077 MultiExprArg ExprArgs) { 3078 bool Elidable = false; 3079 3080 // C++ [class.copy]p15: 3081 // Whenever a temporary class object is copied using a copy constructor, and 3082 // this object and the copy have the same cv-unqualified type, an 3083 // implementation is permitted to treat the original and the copy as two 3084 // different ways of referring to the same object and not perform a copy at 3085 // all, even if the class copy constructor or destructor have side effects. 3086 3087 // FIXME: Is this enough? 3088 if (Constructor->isCopyConstructor(Context)) { 3089 Expr *E = ((Expr **)ExprArgs.get())[0]; 3090 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 3091 E = BE->getSubExpr(); 3092 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 3093 if (ICE->getCastKind() == CastExpr::CK_NoOp) 3094 E = ICE->getSubExpr(); 3095 3096 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 3097 Elidable = true; 3098 } 3099 3100 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 3101 Elidable, move(ExprArgs)); 3102} 3103 3104/// BuildCXXConstructExpr - Creates a complete call to a constructor, 3105/// including handling of its default argument expressions. 3106Sema::OwningExprResult 3107Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3108 CXXConstructorDecl *Constructor, bool Elidable, 3109 MultiExprArg ExprArgs) { 3110 unsigned NumExprs = ExprArgs.size(); 3111 Expr **Exprs = (Expr **)ExprArgs.release(); 3112 3113 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor, 3114 Elidable, Exprs, NumExprs)); 3115} 3116 3117Sema::OwningExprResult 3118Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 3119 QualType Ty, 3120 SourceLocation TyBeginLoc, 3121 MultiExprArg Args, 3122 SourceLocation RParenLoc) { 3123 unsigned NumExprs = Args.size(); 3124 Expr **Exprs = (Expr **)Args.release(); 3125 3126 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, 3127 TyBeginLoc, Exprs, 3128 NumExprs, RParenLoc)); 3129} 3130 3131 3132bool Sema::InitializeVarWithConstructor(VarDecl *VD, 3133 CXXConstructorDecl *Constructor, 3134 QualType DeclInitType, 3135 MultiExprArg Exprs) { 3136 OwningExprResult TempResult = 3137 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor, 3138 move(Exprs)); 3139 if (TempResult.isInvalid()) 3140 return true; 3141 3142 Expr *Temp = TempResult.takeAs<Expr>(); 3143 MarkDeclarationReferenced(VD->getLocation(), Constructor); 3144 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 3145 VD->setInit(Context, Temp); 3146 3147 return false; 3148} 3149 3150void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) { 3151 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 3152 DeclInitType->getAs<RecordType>()->getDecl()); 3153 if (!ClassDecl->hasTrivialDestructor()) 3154 if (CXXDestructorDecl *Destructor = 3155 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 3156 MarkDeclarationReferenced(VD->getLocation(), Destructor); 3157} 3158 3159/// AddCXXDirectInitializerToDecl - This action is called immediately after 3160/// ActOnDeclarator, when a C++ direct initializer is present. 3161/// e.g: "int x(1);" 3162void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 3163 SourceLocation LParenLoc, 3164 MultiExprArg Exprs, 3165 SourceLocation *CommaLocs, 3166 SourceLocation RParenLoc) { 3167 unsigned NumExprs = Exprs.size(); 3168 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 3169 Decl *RealDecl = Dcl.getAs<Decl>(); 3170 3171 // If there is no declaration, there was an error parsing it. Just ignore 3172 // the initializer. 3173 if (RealDecl == 0) 3174 return; 3175 3176 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 3177 if (!VDecl) { 3178 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3179 RealDecl->setInvalidDecl(); 3180 return; 3181 } 3182 3183 // We will represent direct-initialization similarly to copy-initialization: 3184 // int x(1); -as-> int x = 1; 3185 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 3186 // 3187 // Clients that want to distinguish between the two forms, can check for 3188 // direct initializer using VarDecl::hasCXXDirectInitializer(). 3189 // A major benefit is that clients that don't particularly care about which 3190 // exactly form was it (like the CodeGen) can handle both cases without 3191 // special case code. 3192 3193 // If either the declaration has a dependent type or if any of the expressions 3194 // is type-dependent, we represent the initialization via a ParenListExpr for 3195 // later use during template instantiation. 3196 if (VDecl->getType()->isDependentType() || 3197 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 3198 // Let clients know that initialization was done with a direct initializer. 3199 VDecl->setCXXDirectInitializer(true); 3200 3201 // Store the initialization expressions as a ParenListExpr. 3202 unsigned NumExprs = Exprs.size(); 3203 VDecl->setInit(Context, 3204 new (Context) ParenListExpr(Context, LParenLoc, 3205 (Expr **)Exprs.release(), 3206 NumExprs, RParenLoc)); 3207 return; 3208 } 3209 3210 3211 // C++ 8.5p11: 3212 // The form of initialization (using parentheses or '=') is generally 3213 // insignificant, but does matter when the entity being initialized has a 3214 // class type. 3215 QualType DeclInitType = VDecl->getType(); 3216 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 3217 DeclInitType = Array->getElementType(); 3218 3219 // FIXME: This isn't the right place to complete the type. 3220 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3221 diag::err_typecheck_decl_incomplete_type)) { 3222 VDecl->setInvalidDecl(); 3223 return; 3224 } 3225 3226 if (VDecl->getType()->isRecordType()) { 3227 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 3228 3229 CXXConstructorDecl *Constructor 3230 = PerformInitializationByConstructor(DeclInitType, 3231 move(Exprs), 3232 VDecl->getLocation(), 3233 SourceRange(VDecl->getLocation(), 3234 RParenLoc), 3235 VDecl->getDeclName(), 3236 IK_Direct, 3237 ConstructorArgs); 3238 if (!Constructor) 3239 RealDecl->setInvalidDecl(); 3240 else { 3241 VDecl->setCXXDirectInitializer(true); 3242 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType, 3243 move_arg(ConstructorArgs))) 3244 RealDecl->setInvalidDecl(); 3245 FinalizeVarWithDestructor(VDecl, DeclInitType); 3246 } 3247 return; 3248 } 3249 3250 if (NumExprs > 1) { 3251 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 3252 << SourceRange(VDecl->getLocation(), RParenLoc); 3253 RealDecl->setInvalidDecl(); 3254 return; 3255 } 3256 3257 // Let clients know that initialization was done with a direct initializer. 3258 VDecl->setCXXDirectInitializer(true); 3259 3260 assert(NumExprs == 1 && "Expected 1 expression"); 3261 // Set the init expression, handles conversions. 3262 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 3263 /*DirectInit=*/true); 3264} 3265 3266/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which 3267/// may occur as part of direct-initialization or copy-initialization. 3268/// 3269/// \param ClassType the type of the object being initialized, which must have 3270/// class type. 3271/// 3272/// \param ArgsPtr the arguments provided to initialize the object 3273/// 3274/// \param Loc the source location where the initialization occurs 3275/// 3276/// \param Range the source range that covers the entire initialization 3277/// 3278/// \param InitEntity the name of the entity being initialized, if known 3279/// 3280/// \param Kind the type of initialization being performed 3281/// 3282/// \param ConvertedArgs a vector that will be filled in with the 3283/// appropriately-converted arguments to the constructor (if initialization 3284/// succeeded). 3285/// 3286/// \returns the constructor used to initialize the object, if successful. 3287/// Otherwise, emits a diagnostic and returns NULL. 3288CXXConstructorDecl * 3289Sema::PerformInitializationByConstructor(QualType ClassType, 3290 MultiExprArg ArgsPtr, 3291 SourceLocation Loc, SourceRange Range, 3292 DeclarationName InitEntity, 3293 InitializationKind Kind, 3294 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3295 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 3296 assert(ClassRec && "Can only initialize a class type here"); 3297 Expr **Args = (Expr **)ArgsPtr.get(); 3298 unsigned NumArgs = ArgsPtr.size(); 3299 3300 // C++ [dcl.init]p14: 3301 // If the initialization is direct-initialization, or if it is 3302 // copy-initialization where the cv-unqualified version of the 3303 // source type is the same class as, or a derived class of, the 3304 // class of the destination, constructors are considered. The 3305 // applicable constructors are enumerated (13.3.1.3), and the 3306 // best one is chosen through overload resolution (13.3). The 3307 // constructor so selected is called to initialize the object, 3308 // with the initializer expression(s) as its argument(s). If no 3309 // constructor applies, or the overload resolution is ambiguous, 3310 // the initialization is ill-formed. 3311 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 3312 OverloadCandidateSet CandidateSet; 3313 3314 // Add constructors to the overload set. 3315 DeclarationName ConstructorName 3316 = Context.DeclarationNames.getCXXConstructorName( 3317 Context.getCanonicalType(ClassType.getUnqualifiedType())); 3318 DeclContext::lookup_const_iterator Con, ConEnd; 3319 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 3320 Con != ConEnd; ++Con) { 3321 // Find the constructor (which may be a template). 3322 CXXConstructorDecl *Constructor = 0; 3323 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 3324 if (ConstructorTmpl) 3325 Constructor 3326 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3327 else 3328 Constructor = cast<CXXConstructorDecl>(*Con); 3329 3330 if ((Kind == IK_Direct) || 3331 (Kind == IK_Copy && 3332 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 3333 (Kind == IK_Default && Constructor->isDefaultConstructor())) { 3334 if (ConstructorTmpl) 3335 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, 3336 Args, NumArgs, CandidateSet); 3337 else 3338 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 3339 } 3340 } 3341 3342 // FIXME: When we decide not to synthesize the implicitly-declared 3343 // constructors, we'll need to make them appear here. 3344 3345 OverloadCandidateSet::iterator Best; 3346 switch (BestViableFunction(CandidateSet, Loc, Best)) { 3347 case OR_Success: 3348 // We found a constructor. Break out so that we can convert the arguments 3349 // appropriately. 3350 break; 3351 3352 case OR_No_Viable_Function: 3353 if (InitEntity) 3354 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3355 << InitEntity << Range; 3356 else 3357 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3358 << ClassType << Range; 3359 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3360 return 0; 3361 3362 case OR_Ambiguous: 3363 if (InitEntity) 3364 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 3365 else 3366 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 3367 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3368 return 0; 3369 3370 case OR_Deleted: 3371 if (InitEntity) 3372 Diag(Loc, diag::err_ovl_deleted_init) 3373 << Best->Function->isDeleted() 3374 << InitEntity << Range; 3375 else 3376 Diag(Loc, diag::err_ovl_deleted_init) 3377 << Best->Function->isDeleted() 3378 << InitEntity << Range; 3379 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3380 return 0; 3381 } 3382 3383 // Convert the arguments, fill in default arguments, etc. 3384 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3385 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs)) 3386 return 0; 3387 3388 return Constructor; 3389} 3390 3391/// \brief Given a constructor and the set of arguments provided for the 3392/// constructor, convert the arguments and add any required default arguments 3393/// to form a proper call to this constructor. 3394/// 3395/// \returns true if an error occurred, false otherwise. 3396bool 3397Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 3398 MultiExprArg ArgsPtr, 3399 SourceLocation Loc, 3400 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3401 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 3402 unsigned NumArgs = ArgsPtr.size(); 3403 Expr **Args = (Expr **)ArgsPtr.get(); 3404 3405 const FunctionProtoType *Proto 3406 = Constructor->getType()->getAs<FunctionProtoType>(); 3407 assert(Proto && "Constructor without a prototype?"); 3408 unsigned NumArgsInProto = Proto->getNumArgs(); 3409 unsigned NumArgsToCheck = NumArgs; 3410 3411 // If too few arguments are available, we'll fill in the rest with defaults. 3412 if (NumArgs < NumArgsInProto) { 3413 NumArgsToCheck = NumArgsInProto; 3414 ConvertedArgs.reserve(NumArgsInProto); 3415 } else { 3416 ConvertedArgs.reserve(NumArgs); 3417 if (NumArgs > NumArgsInProto) 3418 NumArgsToCheck = NumArgsInProto; 3419 } 3420 3421 // Convert arguments 3422 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3423 QualType ProtoArgType = Proto->getArgType(i); 3424 3425 Expr *Arg; 3426 if (i < NumArgs) { 3427 Arg = Args[i]; 3428 3429 // Pass the argument. 3430 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3431 return true; 3432 3433 Args[i] = 0; 3434 } else { 3435 ParmVarDecl *Param = Constructor->getParamDecl(i); 3436 3437 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param); 3438 if (DefArg.isInvalid()) 3439 return true; 3440 3441 Arg = DefArg.takeAs<Expr>(); 3442 } 3443 3444 ConvertedArgs.push_back(Arg); 3445 } 3446 3447 // If this is a variadic call, handle args passed through "...". 3448 if (Proto->isVariadic()) { 3449 // Promote the arguments (C99 6.5.2.2p7). 3450 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3451 Expr *Arg = Args[i]; 3452 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor)) 3453 return true; 3454 3455 ConvertedArgs.push_back(Arg); 3456 Args[i] = 0; 3457 } 3458 } 3459 3460 return false; 3461} 3462 3463/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3464/// determine whether they are reference-related, 3465/// reference-compatible, reference-compatible with added 3466/// qualification, or incompatible, for use in C++ initialization by 3467/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3468/// type, and the first type (T1) is the pointee type of the reference 3469/// type being initialized. 3470Sema::ReferenceCompareResult 3471Sema::CompareReferenceRelationship(QualType T1, QualType T2, 3472 bool& DerivedToBase) { 3473 assert(!T1->isReferenceType() && 3474 "T1 must be the pointee type of the reference type"); 3475 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 3476 3477 T1 = Context.getCanonicalType(T1); 3478 T2 = Context.getCanonicalType(T2); 3479 QualType UnqualT1 = T1.getUnqualifiedType(); 3480 QualType UnqualT2 = T2.getUnqualifiedType(); 3481 3482 // C++ [dcl.init.ref]p4: 3483 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3484 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3485 // T1 is a base class of T2. 3486 if (UnqualT1 == UnqualT2) 3487 DerivedToBase = false; 3488 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 3489 DerivedToBase = true; 3490 else 3491 return Ref_Incompatible; 3492 3493 // At this point, we know that T1 and T2 are reference-related (at 3494 // least). 3495 3496 // C++ [dcl.init.ref]p4: 3497 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3498 // reference-related to T2 and cv1 is the same cv-qualification 3499 // as, or greater cv-qualification than, cv2. For purposes of 3500 // overload resolution, cases for which cv1 is greater 3501 // cv-qualification than cv2 are identified as 3502 // reference-compatible with added qualification (see 13.3.3.2). 3503 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3504 return Ref_Compatible; 3505 else if (T1.isMoreQualifiedThan(T2)) 3506 return Ref_Compatible_With_Added_Qualification; 3507 else 3508 return Ref_Related; 3509} 3510 3511/// CheckReferenceInit - Check the initialization of a reference 3512/// variable with the given initializer (C++ [dcl.init.ref]). Init is 3513/// the initializer (either a simple initializer or an initializer 3514/// list), and DeclType is the type of the declaration. When ICS is 3515/// non-null, this routine will compute the implicit conversion 3516/// sequence according to C++ [over.ics.ref] and will not produce any 3517/// diagnostics; when ICS is null, it will emit diagnostics when any 3518/// errors are found. Either way, a return value of true indicates 3519/// that there was a failure, a return value of false indicates that 3520/// the reference initialization succeeded. 3521/// 3522/// When @p SuppressUserConversions, user-defined conversions are 3523/// suppressed. 3524/// When @p AllowExplicit, we also permit explicit user-defined 3525/// conversion functions. 3526/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 3527bool 3528Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 3529 SourceLocation DeclLoc, 3530 bool SuppressUserConversions, 3531 bool AllowExplicit, bool ForceRValue, 3532 ImplicitConversionSequence *ICS) { 3533 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3534 3535 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3536 QualType T2 = Init->getType(); 3537 3538 // If the initializer is the address of an overloaded function, try 3539 // to resolve the overloaded function. If all goes well, T2 is the 3540 // type of the resulting function. 3541 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 3542 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 3543 ICS != 0); 3544 if (Fn) { 3545 // Since we're performing this reference-initialization for 3546 // real, update the initializer with the resulting function. 3547 if (!ICS) { 3548 if (DiagnoseUseOfDecl(Fn, DeclLoc)) 3549 return true; 3550 3551 FixOverloadedFunctionReference(Init, Fn); 3552 } 3553 3554 T2 = Fn->getType(); 3555 } 3556 } 3557 3558 // Compute some basic properties of the types and the initializer. 3559 bool isRValRef = DeclType->isRValueReferenceType(); 3560 bool DerivedToBase = false; 3561 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 3562 Init->isLvalue(Context); 3563 ReferenceCompareResult RefRelationship 3564 = CompareReferenceRelationship(T1, T2, DerivedToBase); 3565 3566 // Most paths end in a failed conversion. 3567 if (ICS) 3568 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 3569 3570 // C++ [dcl.init.ref]p5: 3571 // A reference to type "cv1 T1" is initialized by an expression 3572 // of type "cv2 T2" as follows: 3573 3574 // -- If the initializer expression 3575 3576 // Rvalue references cannot bind to lvalues (N2812). 3577 // There is absolutely no situation where they can. In particular, note that 3578 // this is ill-formed, even if B has a user-defined conversion to A&&: 3579 // B b; 3580 // A&& r = b; 3581 if (isRValRef && InitLvalue == Expr::LV_Valid) { 3582 if (!ICS) 3583 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 3584 << Init->getSourceRange(); 3585 return true; 3586 } 3587 3588 bool BindsDirectly = false; 3589 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3590 // reference-compatible with "cv2 T2," or 3591 // 3592 // Note that the bit-field check is skipped if we are just computing 3593 // the implicit conversion sequence (C++ [over.best.ics]p2). 3594 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 3595 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3596 BindsDirectly = true; 3597 3598 if (ICS) { 3599 // C++ [over.ics.ref]p1: 3600 // When a parameter of reference type binds directly (8.5.3) 3601 // to an argument expression, the implicit conversion sequence 3602 // is the identity conversion, unless the argument expression 3603 // has a type that is a derived class of the parameter type, 3604 // in which case the implicit conversion sequence is a 3605 // derived-to-base Conversion (13.3.3.1). 3606 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3607 ICS->Standard.First = ICK_Identity; 3608 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3609 ICS->Standard.Third = ICK_Identity; 3610 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3611 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3612 ICS->Standard.ReferenceBinding = true; 3613 ICS->Standard.DirectBinding = true; 3614 ICS->Standard.RRefBinding = false; 3615 ICS->Standard.CopyConstructor = 0; 3616 3617 // Nothing more to do: the inaccessibility/ambiguity check for 3618 // derived-to-base conversions is suppressed when we're 3619 // computing the implicit conversion sequence (C++ 3620 // [over.best.ics]p2). 3621 return false; 3622 } else { 3623 // Perform the conversion. 3624 CastExpr::CastKind CK = CastExpr::CK_NoOp; 3625 if (DerivedToBase) 3626 CK = CastExpr::CK_DerivedToBase; 3627 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 3628 } 3629 } 3630 3631 // -- has a class type (i.e., T2 is a class type) and can be 3632 // implicitly converted to an lvalue of type "cv3 T3," 3633 // where "cv1 T1" is reference-compatible with "cv3 T3" 3634 // 92) (this conversion is selected by enumerating the 3635 // applicable conversion functions (13.3.1.6) and choosing 3636 // the best one through overload resolution (13.3)), 3637 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 3638 !RequireCompleteType(SourceLocation(), T2, 0)) { 3639 CXXRecordDecl *T2RecordDecl 3640 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3641 3642 OverloadCandidateSet CandidateSet; 3643 OverloadedFunctionDecl *Conversions 3644 = T2RecordDecl->getVisibleConversionFunctions(); 3645 for (OverloadedFunctionDecl::function_iterator Func 3646 = Conversions->function_begin(); 3647 Func != Conversions->function_end(); ++Func) { 3648 FunctionTemplateDecl *ConvTemplate 3649 = dyn_cast<FunctionTemplateDecl>(*Func); 3650 CXXConversionDecl *Conv; 3651 if (ConvTemplate) 3652 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3653 else 3654 Conv = cast<CXXConversionDecl>(*Func); 3655 3656 // If the conversion function doesn't return a reference type, 3657 // it can't be considered for this conversion. 3658 if (Conv->getConversionType()->isLValueReferenceType() && 3659 (AllowExplicit || !Conv->isExplicit())) { 3660 if (ConvTemplate) 3661 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 3662 CandidateSet); 3663 else 3664 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 3665 } 3666 } 3667 3668 OverloadCandidateSet::iterator Best; 3669 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) { 3670 case OR_Success: 3671 // This is a direct binding. 3672 BindsDirectly = true; 3673 3674 if (ICS) { 3675 // C++ [over.ics.ref]p1: 3676 // 3677 // [...] If the parameter binds directly to the result of 3678 // applying a conversion function to the argument 3679 // expression, the implicit conversion sequence is a 3680 // user-defined conversion sequence (13.3.3.1.2), with the 3681 // second standard conversion sequence either an identity 3682 // conversion or, if the conversion function returns an 3683 // entity of a type that is a derived class of the parameter 3684 // type, a derived-to-base Conversion. 3685 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 3686 ICS->UserDefined.Before = Best->Conversions[0].Standard; 3687 ICS->UserDefined.After = Best->FinalConversion; 3688 ICS->UserDefined.ConversionFunction = Best->Function; 3689 assert(ICS->UserDefined.After.ReferenceBinding && 3690 ICS->UserDefined.After.DirectBinding && 3691 "Expected a direct reference binding!"); 3692 return false; 3693 } else { 3694 OwningExprResult InitConversion = 3695 BuildCXXCastArgument(DeclLoc, QualType(), 3696 CastExpr::CK_UserDefinedConversion, 3697 cast<CXXMethodDecl>(Best->Function), 3698 Owned(Init)); 3699 Init = InitConversion.takeAs<Expr>(); 3700 3701 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion, 3702 /*isLvalue=*/true); 3703 } 3704 break; 3705 3706 case OR_Ambiguous: 3707 assert(false && "Ambiguous reference binding conversions not implemented."); 3708 return true; 3709 3710 case OR_No_Viable_Function: 3711 case OR_Deleted: 3712 // There was no suitable conversion, or we found a deleted 3713 // conversion; continue with other checks. 3714 break; 3715 } 3716 } 3717 3718 if (BindsDirectly) { 3719 // C++ [dcl.init.ref]p4: 3720 // [...] In all cases where the reference-related or 3721 // reference-compatible relationship of two types is used to 3722 // establish the validity of a reference binding, and T1 is a 3723 // base class of T2, a program that necessitates such a binding 3724 // is ill-formed if T1 is an inaccessible (clause 11) or 3725 // ambiguous (10.2) base class of T2. 3726 // 3727 // Note that we only check this condition when we're allowed to 3728 // complain about errors, because we should not be checking for 3729 // ambiguity (or inaccessibility) unless the reference binding 3730 // actually happens. 3731 if (DerivedToBase) 3732 return CheckDerivedToBaseConversion(T2, T1, DeclLoc, 3733 Init->getSourceRange()); 3734 else 3735 return false; 3736 } 3737 3738 // -- Otherwise, the reference shall be to a non-volatile const 3739 // type (i.e., cv1 shall be const), or the reference shall be an 3740 // rvalue reference and the initializer expression shall be an rvalue. 3741 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) { 3742 if (!ICS) 3743 Diag(DeclLoc, diag::err_not_reference_to_const_init) 3744 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3745 << T2 << Init->getSourceRange(); 3746 return true; 3747 } 3748 3749 // -- If the initializer expression is an rvalue, with T2 a 3750 // class type, and "cv1 T1" is reference-compatible with 3751 // "cv2 T2," the reference is bound in one of the 3752 // following ways (the choice is implementation-defined): 3753 // 3754 // -- The reference is bound to the object represented by 3755 // the rvalue (see 3.10) or to a sub-object within that 3756 // object. 3757 // 3758 // -- A temporary of type "cv1 T2" [sic] is created, and 3759 // a constructor is called to copy the entire rvalue 3760 // object into the temporary. The reference is bound to 3761 // the temporary or to a sub-object within the 3762 // temporary. 3763 // 3764 // The constructor that would be used to make the copy 3765 // shall be callable whether or not the copy is actually 3766 // done. 3767 // 3768 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 3769 // freedom, so we will always take the first option and never build 3770 // a temporary in this case. FIXME: We will, however, have to check 3771 // for the presence of a copy constructor in C++98/03 mode. 3772 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 3773 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3774 if (ICS) { 3775 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3776 ICS->Standard.First = ICK_Identity; 3777 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3778 ICS->Standard.Third = ICK_Identity; 3779 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3780 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3781 ICS->Standard.ReferenceBinding = true; 3782 ICS->Standard.DirectBinding = false; 3783 ICS->Standard.RRefBinding = isRValRef; 3784 ICS->Standard.CopyConstructor = 0; 3785 } else { 3786 CastExpr::CastKind CK = CastExpr::CK_NoOp; 3787 if (DerivedToBase) 3788 CK = CastExpr::CK_DerivedToBase; 3789 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 3790 } 3791 return false; 3792 } 3793 3794 // -- Otherwise, a temporary of type "cv1 T1" is created and 3795 // initialized from the initializer expression using the 3796 // rules for a non-reference copy initialization (8.5). The 3797 // reference is then bound to the temporary. If T1 is 3798 // reference-related to T2, cv1 must be the same 3799 // cv-qualification as, or greater cv-qualification than, 3800 // cv2; otherwise, the program is ill-formed. 3801 if (RefRelationship == Ref_Related) { 3802 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3803 // we would be reference-compatible or reference-compatible with 3804 // added qualification. But that wasn't the case, so the reference 3805 // initialization fails. 3806 if (!ICS) 3807 Diag(DeclLoc, diag::err_reference_init_drops_quals) 3808 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3809 << T2 << Init->getSourceRange(); 3810 return true; 3811 } 3812 3813 // If at least one of the types is a class type, the types are not 3814 // related, and we aren't allowed any user conversions, the 3815 // reference binding fails. This case is important for breaking 3816 // recursion, since TryImplicitConversion below will attempt to 3817 // create a temporary through the use of a copy constructor. 3818 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 3819 (T1->isRecordType() || T2->isRecordType())) { 3820 if (!ICS) 3821 Diag(DeclLoc, diag::err_typecheck_convert_incompatible) 3822 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 3823 return true; 3824 } 3825 3826 // Actually try to convert the initializer to T1. 3827 if (ICS) { 3828 // C++ [over.ics.ref]p2: 3829 // 3830 // When a parameter of reference type is not bound directly to 3831 // an argument expression, the conversion sequence is the one 3832 // required to convert the argument expression to the 3833 // underlying type of the reference according to 3834 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3835 // to copy-initializing a temporary of the underlying type with 3836 // the argument expression. Any difference in top-level 3837 // cv-qualification is subsumed by the initialization itself 3838 // and does not constitute a conversion. 3839 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 3840 /*AllowExplicit=*/false, 3841 /*ForceRValue=*/false, 3842 /*InOverloadResolution=*/false); 3843 3844 // Of course, that's still a reference binding. 3845 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 3846 ICS->Standard.ReferenceBinding = true; 3847 ICS->Standard.RRefBinding = isRValRef; 3848 } else if (ICS->ConversionKind == 3849 ImplicitConversionSequence::UserDefinedConversion) { 3850 ICS->UserDefined.After.ReferenceBinding = true; 3851 ICS->UserDefined.After.RRefBinding = isRValRef; 3852 } 3853 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 3854 } else { 3855 ImplicitConversionSequence Conversions; 3856 bool badConversion = PerformImplicitConversion(Init, T1, "initializing", 3857 false, false, 3858 Conversions); 3859 if (badConversion) { 3860 if ((Conversions.ConversionKind == 3861 ImplicitConversionSequence::BadConversion) 3862 && !Conversions.ConversionFunctionSet.empty()) { 3863 Diag(DeclLoc, 3864 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 3865 for (int j = Conversions.ConversionFunctionSet.size()-1; 3866 j >= 0; j--) { 3867 FunctionDecl *Func = Conversions.ConversionFunctionSet[j]; 3868 Diag(Func->getLocation(), diag::err_ovl_candidate); 3869 } 3870 } 3871 else { 3872 if (isRValRef) 3873 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 3874 << Init->getSourceRange(); 3875 else 3876 Diag(DeclLoc, diag::err_invalid_initialization) 3877 << DeclType << Init->getType() << Init->getSourceRange(); 3878 } 3879 } 3880 return badConversion; 3881 } 3882} 3883 3884/// CheckOverloadedOperatorDeclaration - Check whether the declaration 3885/// of this overloaded operator is well-formed. If so, returns false; 3886/// otherwise, emits appropriate diagnostics and returns true. 3887bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 3888 assert(FnDecl && FnDecl->isOverloadedOperator() && 3889 "Expected an overloaded operator declaration"); 3890 3891 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 3892 3893 // C++ [over.oper]p5: 3894 // The allocation and deallocation functions, operator new, 3895 // operator new[], operator delete and operator delete[], are 3896 // described completely in 3.7.3. The attributes and restrictions 3897 // found in the rest of this subclause do not apply to them unless 3898 // explicitly stated in 3.7.3. 3899 // FIXME: Write a separate routine for checking this. For now, just allow it. 3900 if (Op == OO_New || Op == OO_Array_New || 3901 Op == OO_Delete || Op == OO_Array_Delete) 3902 return false; 3903 3904 // C++ [over.oper]p6: 3905 // An operator function shall either be a non-static member 3906 // function or be a non-member function and have at least one 3907 // parameter whose type is a class, a reference to a class, an 3908 // enumeration, or a reference to an enumeration. 3909 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 3910 if (MethodDecl->isStatic()) 3911 return Diag(FnDecl->getLocation(), 3912 diag::err_operator_overload_static) << FnDecl->getDeclName(); 3913 } else { 3914 bool ClassOrEnumParam = false; 3915 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 3916 ParamEnd = FnDecl->param_end(); 3917 Param != ParamEnd; ++Param) { 3918 QualType ParamType = (*Param)->getType().getNonReferenceType(); 3919 if (ParamType->isDependentType() || ParamType->isRecordType() || 3920 ParamType->isEnumeralType()) { 3921 ClassOrEnumParam = true; 3922 break; 3923 } 3924 } 3925 3926 if (!ClassOrEnumParam) 3927 return Diag(FnDecl->getLocation(), 3928 diag::err_operator_overload_needs_class_or_enum) 3929 << FnDecl->getDeclName(); 3930 } 3931 3932 // C++ [over.oper]p8: 3933 // An operator function cannot have default arguments (8.3.6), 3934 // except where explicitly stated below. 3935 // 3936 // Only the function-call operator allows default arguments 3937 // (C++ [over.call]p1). 3938 if (Op != OO_Call) { 3939 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 3940 Param != FnDecl->param_end(); ++Param) { 3941 if ((*Param)->hasUnparsedDefaultArg()) 3942 return Diag((*Param)->getLocation(), 3943 diag::err_operator_overload_default_arg) 3944 << FnDecl->getDeclName(); 3945 else if (Expr *DefArg = (*Param)->getDefaultArg()) 3946 return Diag((*Param)->getLocation(), 3947 diag::err_operator_overload_default_arg) 3948 << FnDecl->getDeclName() << DefArg->getSourceRange(); 3949 } 3950 } 3951 3952 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 3953 { false, false, false } 3954#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3955 , { Unary, Binary, MemberOnly } 3956#include "clang/Basic/OperatorKinds.def" 3957 }; 3958 3959 bool CanBeUnaryOperator = OperatorUses[Op][0]; 3960 bool CanBeBinaryOperator = OperatorUses[Op][1]; 3961 bool MustBeMemberOperator = OperatorUses[Op][2]; 3962 3963 // C++ [over.oper]p8: 3964 // [...] Operator functions cannot have more or fewer parameters 3965 // than the number required for the corresponding operator, as 3966 // described in the rest of this subclause. 3967 unsigned NumParams = FnDecl->getNumParams() 3968 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 3969 if (Op != OO_Call && 3970 ((NumParams == 1 && !CanBeUnaryOperator) || 3971 (NumParams == 2 && !CanBeBinaryOperator) || 3972 (NumParams < 1) || (NumParams > 2))) { 3973 // We have the wrong number of parameters. 3974 unsigned ErrorKind; 3975 if (CanBeUnaryOperator && CanBeBinaryOperator) { 3976 ErrorKind = 2; // 2 -> unary or binary. 3977 } else if (CanBeUnaryOperator) { 3978 ErrorKind = 0; // 0 -> unary 3979 } else { 3980 assert(CanBeBinaryOperator && 3981 "All non-call overloaded operators are unary or binary!"); 3982 ErrorKind = 1; // 1 -> binary 3983 } 3984 3985 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 3986 << FnDecl->getDeclName() << NumParams << ErrorKind; 3987 } 3988 3989 // Overloaded operators other than operator() cannot be variadic. 3990 if (Op != OO_Call && 3991 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 3992 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 3993 << FnDecl->getDeclName(); 3994 } 3995 3996 // Some operators must be non-static member functions. 3997 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 3998 return Diag(FnDecl->getLocation(), 3999 diag::err_operator_overload_must_be_member) 4000 << FnDecl->getDeclName(); 4001 } 4002 4003 // C++ [over.inc]p1: 4004 // The user-defined function called operator++ implements the 4005 // prefix and postfix ++ operator. If this function is a member 4006 // function with no parameters, or a non-member function with one 4007 // parameter of class or enumeration type, it defines the prefix 4008 // increment operator ++ for objects of that type. If the function 4009 // is a member function with one parameter (which shall be of type 4010 // int) or a non-member function with two parameters (the second 4011 // of which shall be of type int), it defines the postfix 4012 // increment operator ++ for objects of that type. 4013 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 4014 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 4015 bool ParamIsInt = false; 4016 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 4017 ParamIsInt = BT->getKind() == BuiltinType::Int; 4018 4019 if (!ParamIsInt) 4020 return Diag(LastParam->getLocation(), 4021 diag::err_operator_overload_post_incdec_must_be_int) 4022 << LastParam->getType() << (Op == OO_MinusMinus); 4023 } 4024 4025 // Notify the class if it got an assignment operator. 4026 if (Op == OO_Equal) { 4027 // Would have returned earlier otherwise. 4028 assert(isa<CXXMethodDecl>(FnDecl) && 4029 "Overloaded = not member, but not filtered."); 4030 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 4031 Method->setCopyAssignment(true); 4032 Method->getParent()->addedAssignmentOperator(Context, Method); 4033 } 4034 4035 return false; 4036} 4037 4038/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 4039/// linkage specification, including the language and (if present) 4040/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 4041/// the location of the language string literal, which is provided 4042/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 4043/// the '{' brace. Otherwise, this linkage specification does not 4044/// have any braces. 4045Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 4046 SourceLocation ExternLoc, 4047 SourceLocation LangLoc, 4048 const char *Lang, 4049 unsigned StrSize, 4050 SourceLocation LBraceLoc) { 4051 LinkageSpecDecl::LanguageIDs Language; 4052 if (strncmp(Lang, "\"C\"", StrSize) == 0) 4053 Language = LinkageSpecDecl::lang_c; 4054 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 4055 Language = LinkageSpecDecl::lang_cxx; 4056 else { 4057 Diag(LangLoc, diag::err_bad_language); 4058 return DeclPtrTy(); 4059 } 4060 4061 // FIXME: Add all the various semantics of linkage specifications 4062 4063 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 4064 LangLoc, Language, 4065 LBraceLoc.isValid()); 4066 CurContext->addDecl(D); 4067 PushDeclContext(S, D); 4068 return DeclPtrTy::make(D); 4069} 4070 4071/// ActOnFinishLinkageSpecification - Completely the definition of 4072/// the C++ linkage specification LinkageSpec. If RBraceLoc is 4073/// valid, it's the position of the closing '}' brace in a linkage 4074/// specification that uses braces. 4075Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 4076 DeclPtrTy LinkageSpec, 4077 SourceLocation RBraceLoc) { 4078 if (LinkageSpec) 4079 PopDeclContext(); 4080 return LinkageSpec; 4081} 4082 4083/// \brief Perform semantic analysis for the variable declaration that 4084/// occurs within a C++ catch clause, returning the newly-created 4085/// variable. 4086VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 4087 DeclaratorInfo *DInfo, 4088 IdentifierInfo *Name, 4089 SourceLocation Loc, 4090 SourceRange Range) { 4091 bool Invalid = false; 4092 4093 // Arrays and functions decay. 4094 if (ExDeclType->isArrayType()) 4095 ExDeclType = Context.getArrayDecayedType(ExDeclType); 4096 else if (ExDeclType->isFunctionType()) 4097 ExDeclType = Context.getPointerType(ExDeclType); 4098 4099 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 4100 // The exception-declaration shall not denote a pointer or reference to an 4101 // incomplete type, other than [cv] void*. 4102 // N2844 forbids rvalue references. 4103 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 4104 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 4105 Invalid = true; 4106 } 4107 4108 QualType BaseType = ExDeclType; 4109 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 4110 unsigned DK = diag::err_catch_incomplete; 4111 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 4112 BaseType = Ptr->getPointeeType(); 4113 Mode = 1; 4114 DK = diag::err_catch_incomplete_ptr; 4115 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 4116 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 4117 BaseType = Ref->getPointeeType(); 4118 Mode = 2; 4119 DK = diag::err_catch_incomplete_ref; 4120 } 4121 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 4122 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 4123 Invalid = true; 4124 4125 if (!Invalid && !ExDeclType->isDependentType() && 4126 RequireNonAbstractType(Loc, ExDeclType, 4127 diag::err_abstract_type_in_decl, 4128 AbstractVariableType)) 4129 Invalid = true; 4130 4131 // FIXME: Need to test for ability to copy-construct and destroy the 4132 // exception variable. 4133 4134 // FIXME: Need to check for abstract classes. 4135 4136 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 4137 Name, ExDeclType, DInfo, VarDecl::None); 4138 4139 if (Invalid) 4140 ExDecl->setInvalidDecl(); 4141 4142 return ExDecl; 4143} 4144 4145/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 4146/// handler. 4147Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 4148 DeclaratorInfo *DInfo = 0; 4149 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 4150 4151 bool Invalid = D.isInvalidType(); 4152 IdentifierInfo *II = D.getIdentifier(); 4153 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 4154 // The scope should be freshly made just for us. There is just no way 4155 // it contains any previous declaration. 4156 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 4157 if (PrevDecl->isTemplateParameter()) { 4158 // Maybe we will complain about the shadowed template parameter. 4159 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4160 } 4161 } 4162 4163 if (D.getCXXScopeSpec().isSet() && !Invalid) { 4164 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 4165 << D.getCXXScopeSpec().getRange(); 4166 Invalid = true; 4167 } 4168 4169 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 4170 D.getIdentifier(), 4171 D.getIdentifierLoc(), 4172 D.getDeclSpec().getSourceRange()); 4173 4174 if (Invalid) 4175 ExDecl->setInvalidDecl(); 4176 4177 // Add the exception declaration into this scope. 4178 if (II) 4179 PushOnScopeChains(ExDecl, S); 4180 else 4181 CurContext->addDecl(ExDecl); 4182 4183 ProcessDeclAttributes(S, ExDecl, D); 4184 return DeclPtrTy::make(ExDecl); 4185} 4186 4187Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 4188 ExprArg assertexpr, 4189 ExprArg assertmessageexpr) { 4190 Expr *AssertExpr = (Expr *)assertexpr.get(); 4191 StringLiteral *AssertMessage = 4192 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 4193 4194 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 4195 llvm::APSInt Value(32); 4196 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 4197 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 4198 AssertExpr->getSourceRange(); 4199 return DeclPtrTy(); 4200 } 4201 4202 if (Value == 0) { 4203 std::string str(AssertMessage->getStrData(), 4204 AssertMessage->getByteLength()); 4205 Diag(AssertLoc, diag::err_static_assert_failed) 4206 << str << AssertExpr->getSourceRange(); 4207 } 4208 } 4209 4210 assertexpr.release(); 4211 assertmessageexpr.release(); 4212 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 4213 AssertExpr, AssertMessage); 4214 4215 CurContext->addDecl(Decl); 4216 return DeclPtrTy::make(Decl); 4217} 4218 4219/// Handle a friend type declaration. This works in tandem with 4220/// ActOnTag. 4221/// 4222/// Notes on friend class templates: 4223/// 4224/// We generally treat friend class declarations as if they were 4225/// declaring a class. So, for example, the elaborated type specifier 4226/// in a friend declaration is required to obey the restrictions of a 4227/// class-head (i.e. no typedefs in the scope chain), template 4228/// parameters are required to match up with simple template-ids, &c. 4229/// However, unlike when declaring a template specialization, it's 4230/// okay to refer to a template specialization without an empty 4231/// template parameter declaration, e.g. 4232/// friend class A<T>::B<unsigned>; 4233/// We permit this as a special case; if there are any template 4234/// parameters present at all, require proper matching, i.e. 4235/// template <> template <class T> friend class A<int>::B; 4236Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, 4237 const DeclSpec &DS, 4238 MultiTemplateParamsArg TempParams) { 4239 SourceLocation Loc = DS.getSourceRange().getBegin(); 4240 4241 assert(DS.isFriendSpecified()); 4242 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4243 4244 // Try to convert the decl specifier to a type. This works for 4245 // friend templates because ActOnTag never produces a ClassTemplateDecl 4246 // for a TUK_Friend. 4247 bool invalid = false; 4248 QualType SourceTy; 4249 QualType T = ConvertDeclSpecToType(DS, Loc, invalid, SourceTy); 4250 if (invalid) return DeclPtrTy(); 4251 4252 // This is definitely an error in C++98. It's probably meant to 4253 // be forbidden in C++0x, too, but the specification is just 4254 // poorly written. 4255 // 4256 // The problem is with declarations like the following: 4257 // template <T> friend A<T>::foo; 4258 // where deciding whether a class C is a friend or not now hinges 4259 // on whether there exists an instantiation of A that causes 4260 // 'foo' to equal C. There are restrictions on class-heads 4261 // (which we declare (by fiat) elaborated friend declarations to 4262 // be) that makes this tractable. 4263 // 4264 // FIXME: handle "template <> friend class A<T>;", which 4265 // is possibly well-formed? Who even knows? 4266 if (TempParams.size() && !isa<ElaboratedType>(T)) { 4267 Diag(Loc, diag::err_tagless_friend_type_template) 4268 << DS.getSourceRange(); 4269 return DeclPtrTy(); 4270 } 4271 4272 // C++ [class.friend]p2: 4273 // An elaborated-type-specifier shall be used in a friend declaration 4274 // for a class.* 4275 // * The class-key of the elaborated-type-specifier is required. 4276 // This is one of the rare places in Clang where it's legitimate to 4277 // ask about the "spelling" of the type. 4278 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 4279 // If we evaluated the type to a record type, suggest putting 4280 // a tag in front. 4281 if (const RecordType *RT = T->getAs<RecordType>()) { 4282 RecordDecl *RD = RT->getDecl(); 4283 4284 std::string InsertionText = std::string(" ") + RD->getKindName(); 4285 4286 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type) 4287 << (RD->isUnion()) 4288 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 4289 InsertionText); 4290 return DeclPtrTy(); 4291 }else { 4292 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 4293 << DS.getSourceRange(); 4294 return DeclPtrTy(); 4295 } 4296 } 4297 4298 bool IsDefinition = false; 4299 4300 // We want to do a few things differently if the type was declared with 4301 // a tag: specifically, we want to use the associated RecordDecl as 4302 // the object of our friend declaration, and we want to disallow 4303 // class definitions. 4304 switch (DS.getTypeSpecType()) { 4305 default: break; 4306 case DeclSpec::TST_class: 4307 case DeclSpec::TST_struct: 4308 case DeclSpec::TST_union: 4309 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep()); 4310 if (RD) 4311 IsDefinition |= RD->isDefinition(); 4312 break; 4313 } 4314 4315 // C++98 [class.friend]p1: A friend of a class is a function 4316 // or class that is not a member of the class . . . 4317 // But that's a silly restriction which nobody implements for 4318 // inner classes, and C++0x removes it anyway, so we only report 4319 // this (as a warning) if we're being pedantic. 4320 if (!getLangOptions().CPlusPlus0x) 4321 if (const RecordType *RT = T->getAs<RecordType>()) 4322 if (RT->getDecl()->getDeclContext() == CurContext) 4323 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 4324 4325 Decl *D; 4326 if (TempParams.size()) 4327 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 4328 TempParams.size(), 4329 (TemplateParameterList**) TempParams.release(), 4330 T.getTypePtr(), 4331 DS.getFriendSpecLoc()); 4332 else 4333 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(), 4334 DS.getFriendSpecLoc()); 4335 D->setAccess(AS_public); 4336 CurContext->addDecl(D); 4337 4338 return DeclPtrTy::make(D); 4339} 4340 4341Sema::DeclPtrTy 4342Sema::ActOnFriendFunctionDecl(Scope *S, 4343 Declarator &D, 4344 bool IsDefinition, 4345 MultiTemplateParamsArg TemplateParams) { 4346 // FIXME: do something with template parameters 4347 4348 const DeclSpec &DS = D.getDeclSpec(); 4349 4350 assert(DS.isFriendSpecified()); 4351 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4352 4353 SourceLocation Loc = D.getIdentifierLoc(); 4354 DeclaratorInfo *DInfo = 0; 4355 QualType T = GetTypeForDeclarator(D, S, &DInfo); 4356 4357 // C++ [class.friend]p1 4358 // A friend of a class is a function or class.... 4359 // Note that this sees through typedefs, which is intended. 4360 // It *doesn't* see through dependent types, which is correct 4361 // according to [temp.arg.type]p3: 4362 // If a declaration acquires a function type through a 4363 // type dependent on a template-parameter and this causes 4364 // a declaration that does not use the syntactic form of a 4365 // function declarator to have a function type, the program 4366 // is ill-formed. 4367 if (!T->isFunctionType()) { 4368 Diag(Loc, diag::err_unexpected_friend); 4369 4370 // It might be worthwhile to try to recover by creating an 4371 // appropriate declaration. 4372 return DeclPtrTy(); 4373 } 4374 4375 // C++ [namespace.memdef]p3 4376 // - If a friend declaration in a non-local class first declares a 4377 // class or function, the friend class or function is a member 4378 // of the innermost enclosing namespace. 4379 // - The name of the friend is not found by simple name lookup 4380 // until a matching declaration is provided in that namespace 4381 // scope (either before or after the class declaration granting 4382 // friendship). 4383 // - If a friend function is called, its name may be found by the 4384 // name lookup that considers functions from namespaces and 4385 // classes associated with the types of the function arguments. 4386 // - When looking for a prior declaration of a class or a function 4387 // declared as a friend, scopes outside the innermost enclosing 4388 // namespace scope are not considered. 4389 4390 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 4391 DeclarationName Name = GetNameForDeclarator(D); 4392 assert(Name); 4393 4394 // The context we found the declaration in, or in which we should 4395 // create the declaration. 4396 DeclContext *DC; 4397 4398 // FIXME: handle local classes 4399 4400 // Recover from invalid scope qualifiers as if they just weren't there. 4401 NamedDecl *PrevDecl = 0; 4402 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 4403 DC = computeDeclContext(ScopeQual); 4404 4405 // FIXME: handle dependent contexts 4406 if (!DC) return DeclPtrTy(); 4407 4408 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 4409 4410 // If searching in that context implicitly found a declaration in 4411 // a different context, treat it like it wasn't found at all. 4412 // TODO: better diagnostics for this case. Suggesting the right 4413 // qualified scope would be nice... 4414 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) { 4415 D.setInvalidType(); 4416 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 4417 return DeclPtrTy(); 4418 } 4419 4420 // C++ [class.friend]p1: A friend of a class is a function or 4421 // class that is not a member of the class . . . 4422 if (DC->Equals(CurContext)) 4423 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4424 4425 // Otherwise walk out to the nearest namespace scope looking for matches. 4426 } else { 4427 // TODO: handle local class contexts. 4428 4429 DC = CurContext; 4430 while (true) { 4431 // Skip class contexts. If someone can cite chapter and verse 4432 // for this behavior, that would be nice --- it's what GCC and 4433 // EDG do, and it seems like a reasonable intent, but the spec 4434 // really only says that checks for unqualified existing 4435 // declarations should stop at the nearest enclosing namespace, 4436 // not that they should only consider the nearest enclosing 4437 // namespace. 4438 while (DC->isRecord()) 4439 DC = DC->getParent(); 4440 4441 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 4442 4443 // TODO: decide what we think about using declarations. 4444 if (PrevDecl) 4445 break; 4446 4447 if (DC->isFileContext()) break; 4448 DC = DC->getParent(); 4449 } 4450 4451 // C++ [class.friend]p1: A friend of a class is a function or 4452 // class that is not a member of the class . . . 4453 // C++0x changes this for both friend types and functions. 4454 // Most C++ 98 compilers do seem to give an error here, so 4455 // we do, too. 4456 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x) 4457 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4458 } 4459 4460 if (DC->isFileContext()) { 4461 // This implies that it has to be an operator or function. 4462 if (D.getKind() == Declarator::DK_Constructor || 4463 D.getKind() == Declarator::DK_Destructor || 4464 D.getKind() == Declarator::DK_Conversion) { 4465 Diag(Loc, diag::err_introducing_special_friend) << 4466 (D.getKind() == Declarator::DK_Constructor ? 0 : 4467 D.getKind() == Declarator::DK_Destructor ? 1 : 2); 4468 return DeclPtrTy(); 4469 } 4470 } 4471 4472 bool Redeclaration = false; 4473 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl, 4474 MultiTemplateParamsArg(*this), 4475 IsDefinition, 4476 Redeclaration); 4477 if (!ND) return DeclPtrTy(); 4478 4479 assert(ND->getDeclContext() == DC); 4480 assert(ND->getLexicalDeclContext() == CurContext); 4481 4482 // Add the function declaration to the appropriate lookup tables, 4483 // adjusting the redeclarations list as necessary. We don't 4484 // want to do this yet if the friending class is dependent. 4485 // 4486 // Also update the scope-based lookup if the target context's 4487 // lookup context is in lexical scope. 4488 if (!CurContext->isDependentContext()) { 4489 DC = DC->getLookupContext(); 4490 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 4491 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4492 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 4493 } 4494 4495 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 4496 D.getIdentifierLoc(), ND, 4497 DS.getFriendSpecLoc()); 4498 FrD->setAccess(AS_public); 4499 CurContext->addDecl(FrD); 4500 4501 return DeclPtrTy::make(ND); 4502} 4503 4504void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 4505 AdjustDeclIfTemplate(dcl); 4506 4507 Decl *Dcl = dcl.getAs<Decl>(); 4508 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 4509 if (!Fn) { 4510 Diag(DelLoc, diag::err_deleted_non_function); 4511 return; 4512 } 4513 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 4514 Diag(DelLoc, diag::err_deleted_decl_not_first); 4515 Diag(Prev->getLocation(), diag::note_previous_declaration); 4516 // If the declaration wasn't the first, we delete the function anyway for 4517 // recovery. 4518 } 4519 Fn->setDeleted(); 4520} 4521 4522static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 4523 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 4524 ++CI) { 4525 Stmt *SubStmt = *CI; 4526 if (!SubStmt) 4527 continue; 4528 if (isa<ReturnStmt>(SubStmt)) 4529 Self.Diag(SubStmt->getSourceRange().getBegin(), 4530 diag::err_return_in_constructor_handler); 4531 if (!isa<Expr>(SubStmt)) 4532 SearchForReturnInStmt(Self, SubStmt); 4533 } 4534} 4535 4536void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 4537 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 4538 CXXCatchStmt *Handler = TryBlock->getHandler(I); 4539 SearchForReturnInStmt(*this, Handler); 4540 } 4541} 4542 4543bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4544 const CXXMethodDecl *Old) { 4545 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 4546 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 4547 4548 QualType CNewTy = Context.getCanonicalType(NewTy); 4549 QualType COldTy = Context.getCanonicalType(OldTy); 4550 4551 if (CNewTy == COldTy && 4552 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers()) 4553 return false; 4554 4555 // Check if the return types are covariant 4556 QualType NewClassTy, OldClassTy; 4557 4558 /// Both types must be pointers or references to classes. 4559 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 4560 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 4561 NewClassTy = NewPT->getPointeeType(); 4562 OldClassTy = OldPT->getPointeeType(); 4563 } 4564 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 4565 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 4566 NewClassTy = NewRT->getPointeeType(); 4567 OldClassTy = OldRT->getPointeeType(); 4568 } 4569 } 4570 4571 // The return types aren't either both pointers or references to a class type. 4572 if (NewClassTy.isNull()) { 4573 Diag(New->getLocation(), 4574 diag::err_different_return_type_for_overriding_virtual_function) 4575 << New->getDeclName() << NewTy << OldTy; 4576 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4577 4578 return true; 4579 } 4580 4581 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) { 4582 // Check if the new class derives from the old class. 4583 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 4584 Diag(New->getLocation(), 4585 diag::err_covariant_return_not_derived) 4586 << New->getDeclName() << NewTy << OldTy; 4587 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4588 return true; 4589 } 4590 4591 // Check if we the conversion from derived to base is valid. 4592 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 4593 diag::err_covariant_return_inaccessible_base, 4594 diag::err_covariant_return_ambiguous_derived_to_base_conv, 4595 // FIXME: Should this point to the return type? 4596 New->getLocation(), SourceRange(), New->getDeclName())) { 4597 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4598 return true; 4599 } 4600 } 4601 4602 // The qualifiers of the return types must be the same. 4603 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) { 4604 Diag(New->getLocation(), 4605 diag::err_covariant_return_type_different_qualifications) 4606 << New->getDeclName() << NewTy << OldTy; 4607 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4608 return true; 4609 }; 4610 4611 4612 // The new class type must have the same or less qualifiers as the old type. 4613 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 4614 Diag(New->getLocation(), 4615 diag::err_covariant_return_type_class_type_more_qualified) 4616 << New->getDeclName() << NewTy << OldTy; 4617 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4618 return true; 4619 }; 4620 4621 return false; 4622} 4623 4624bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4625 const CXXMethodDecl *Old) { 4626 return CheckExceptionSpecSubset(diag::err_override_exception_spec, 4627 diag::note_overridden_virtual_function, 4628 Old->getType()->getAs<FunctionProtoType>(), 4629 Old->getLocation(), 4630 New->getType()->getAs<FunctionProtoType>(), 4631 New->getLocation()); 4632} 4633 4634/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4635/// initializer for the declaration 'Dcl'. 4636/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4637/// static data member of class X, names should be looked up in the scope of 4638/// class X. 4639void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4640 AdjustDeclIfTemplate(Dcl); 4641 4642 Decl *D = Dcl.getAs<Decl>(); 4643 // If there is no declaration, there was an error parsing it. 4644 if (D == 0) 4645 return; 4646 4647 // Check whether it is a declaration with a nested name specifier like 4648 // int foo::bar; 4649 if (!D->isOutOfLine()) 4650 return; 4651 4652 // C++ [basic.lookup.unqual]p13 4653 // 4654 // A name used in the definition of a static data member of class X 4655 // (after the qualified-id of the static member) is looked up as if the name 4656 // was used in a member function of X. 4657 4658 // Change current context into the context of the initializing declaration. 4659 EnterDeclaratorContext(S, D->getDeclContext()); 4660} 4661 4662/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4663/// initializer for the declaration 'Dcl'. 4664void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4665 AdjustDeclIfTemplate(Dcl); 4666 4667 Decl *D = Dcl.getAs<Decl>(); 4668 // If there is no declaration, there was an error parsing it. 4669 if (D == 0) 4670 return; 4671 4672 // Check whether it is a declaration with a nested name specifier like 4673 // int foo::bar; 4674 if (!D->isOutOfLine()) 4675 return; 4676 4677 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 4678 ExitDeclaratorContext(S); 4679} 4680