SemaDeclCXX.cpp revision e3129df6079a8e0028250d71a10b71dcf728d78a
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 "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/RecordLayout.h" 20#include "clang/AST/CXXInheritance.h" 21#include "clang/AST/DeclVisitor.h" 22#include "clang/AST/TypeLoc.h" 23#include "clang/AST/TypeOrdering.h" 24#include "clang/AST/StmtVisitor.h" 25#include "clang/Parse/DeclSpec.h" 26#include "clang/Parse/Template.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Lex/Preprocessor.h" 29#include "llvm/ADT/STLExtras.h" 30#include <map> 31#include <set> 32 33using namespace clang; 34 35//===----------------------------------------------------------------------===// 36// CheckDefaultArgumentVisitor 37//===----------------------------------------------------------------------===// 38 39namespace { 40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 41 /// the default argument of a parameter to determine whether it 42 /// contains any ill-formed subexpressions. For example, this will 43 /// diagnose the use of local variables or parameters within the 44 /// default argument expression. 45 class CheckDefaultArgumentVisitor 46 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 47 Expr *DefaultArg; 48 Sema *S; 49 50 public: 51 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 52 : DefaultArg(defarg), S(s) {} 53 54 bool VisitExpr(Expr *Node); 55 bool VisitDeclRefExpr(DeclRefExpr *DRE); 56 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 57 }; 58 59 /// VisitExpr - Visit all of the children of this expression. 60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 61 bool IsInvalid = false; 62 for (Stmt::child_iterator I = Node->child_begin(), 63 E = Node->child_end(); I != E; ++I) 64 IsInvalid |= Visit(*I); 65 return IsInvalid; 66 } 67 68 /// VisitDeclRefExpr - Visit a reference to a declaration, to 69 /// determine whether this declaration can be used in the default 70 /// argument expression. 71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 72 NamedDecl *Decl = DRE->getDecl(); 73 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 74 // C++ [dcl.fct.default]p9 75 // Default arguments are evaluated each time the function is 76 // called. The order of evaluation of function arguments is 77 // unspecified. Consequently, parameters of a function shall not 78 // be used in default argument expressions, even if they are not 79 // evaluated. Parameters of a function declared before a default 80 // argument expression are in scope and can hide namespace and 81 // class member names. 82 return S->Diag(DRE->getSourceRange().getBegin(), 83 diag::err_param_default_argument_references_param) 84 << Param->getDeclName() << DefaultArg->getSourceRange(); 85 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p7 87 // Local variables shall not be used in default argument 88 // expressions. 89 if (VDecl->isBlockVarDecl()) 90 return S->Diag(DRE->getSourceRange().getBegin(), 91 diag::err_param_default_argument_references_local) 92 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 93 } 94 95 return false; 96 } 97 98 /// VisitCXXThisExpr - Visit a C++ "this" expression. 99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 100 // C++ [dcl.fct.default]p8: 101 // The keyword this shall not be used in a default argument of a 102 // member function. 103 return S->Diag(ThisE->getSourceRange().getBegin(), 104 diag::err_param_default_argument_references_this) 105 << ThisE->getSourceRange(); 106 } 107} 108 109bool 110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 111 SourceLocation EqualLoc) { 112 if (RequireCompleteType(Param->getLocation(), Param->getType(), 113 diag::err_typecheck_decl_incomplete_type)) { 114 Param->setInvalidDecl(); 115 return true; 116 } 117 118 Expr *Arg = (Expr *)DefaultArg.get(); 119 120 // C++ [dcl.fct.default]p5 121 // A default argument expression is implicitly converted (clause 122 // 4) to the parameter type. The default argument expression has 123 // the same semantic constraints as the initializer expression in 124 // a declaration of a variable of the parameter type, using the 125 // copy-initialization semantics (8.5). 126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 128 EqualLoc); 129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 131 MultiExprArg(*this, (void**)&Arg, 1)); 132 if (Result.isInvalid()) 133 return true; 134 Arg = Result.takeAs<Expr>(); 135 136 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 137 138 // Okay: add the default argument to the parameter 139 Param->setDefaultArg(Arg); 140 141 DefaultArg.release(); 142 143 return false; 144} 145 146/// ActOnParamDefaultArgument - Check whether the default argument 147/// provided for a function parameter is well-formed. If so, attach it 148/// to the parameter declaration. 149void 150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 151 ExprArg defarg) { 152 if (!param || !defarg.get()) 153 return; 154 155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 156 UnparsedDefaultArgLocs.erase(Param); 157 158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 159 160 // Default arguments are only permitted in C++ 161 if (!getLangOptions().CPlusPlus) { 162 Diag(EqualLoc, diag::err_param_default_argument) 163 << DefaultArg->getSourceRange(); 164 Param->setInvalidDecl(); 165 return; 166 } 167 168 // Check that the default argument is well-formed 169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 170 if (DefaultArgChecker.Visit(DefaultArg.get())) { 171 Param->setInvalidDecl(); 172 return; 173 } 174 175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 176} 177 178/// ActOnParamUnparsedDefaultArgument - We've seen a default 179/// argument for a function parameter, but we can't parse it yet 180/// because we're inside a class definition. Note that this default 181/// argument will be parsed later. 182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 183 SourceLocation EqualLoc, 184 SourceLocation ArgLoc) { 185 if (!param) 186 return; 187 188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 189 if (Param) 190 Param->setUnparsedDefaultArg(); 191 192 UnparsedDefaultArgLocs[Param] = ArgLoc; 193} 194 195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 196/// the default argument for the parameter param failed. 197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 198 if (!param) 199 return; 200 201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 202 203 Param->setInvalidDecl(); 204 205 UnparsedDefaultArgLocs.erase(Param); 206} 207 208/// CheckExtraCXXDefaultArguments - Check for any extra default 209/// arguments in the declarator, which is not a function declaration 210/// or definition and therefore is not permitted to have default 211/// arguments. This routine should be invoked for every declarator 212/// that is not a function declaration or definition. 213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 214 // C++ [dcl.fct.default]p3 215 // A default argument expression shall be specified only in the 216 // parameter-declaration-clause of a function declaration or in a 217 // template-parameter (14.1). It shall not be specified for a 218 // parameter pack. If it is specified in a 219 // parameter-declaration-clause, it shall not occur within a 220 // declarator or abstract-declarator of a parameter-declaration. 221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 222 DeclaratorChunk &chunk = D.getTypeObject(i); 223 if (chunk.Kind == DeclaratorChunk::Function) { 224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 225 ParmVarDecl *Param = 226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 227 if (Param->hasUnparsedDefaultArg()) { 228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 231 delete Toks; 232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 233 } else if (Param->getDefaultArg()) { 234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 235 << Param->getDefaultArg()->getSourceRange(); 236 Param->setDefaultArg(0); 237 } 238 } 239 } 240 } 241} 242 243// MergeCXXFunctionDecl - Merge two declarations of the same C++ 244// function, once we already know that they have the same 245// type. Subroutine of MergeFunctionDecl. Returns true if there was an 246// error, false otherwise. 247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 248 bool Invalid = false; 249 250 // C++ [dcl.fct.default]p4: 251 // For non-template functions, default arguments can be added in 252 // later declarations of a function in the same 253 // scope. Declarations in different scopes have completely 254 // distinct sets of default arguments. That is, declarations in 255 // inner scopes do not acquire default arguments from 256 // declarations in outer scopes, and vice versa. In a given 257 // function declaration, all parameters subsequent to a 258 // parameter with a default argument shall have default 259 // arguments supplied in this or previous declarations. A 260 // default argument shall not be redefined by a later 261 // declaration (not even to the same value). 262 // 263 // C++ [dcl.fct.default]p6: 264 // Except for member functions of class templates, the default arguments 265 // in a member function definition that appears outside of the class 266 // definition are added to the set of default arguments provided by the 267 // member function declaration in the class definition. 268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 269 ParmVarDecl *OldParam = Old->getParamDecl(p); 270 ParmVarDecl *NewParam = New->getParamDecl(p); 271 272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 274 // hint here. Alternatively, we could walk the type-source information 275 // for NewParam to find the last source location in the type... but it 276 // isn't worth the effort right now. This is the kind of test case that 277 // is hard to get right: 278 279 // int f(int); 280 // void g(int (*fp)(int) = f); 281 // void g(int (*fp)(int) = &f); 282 Diag(NewParam->getLocation(), 283 diag::err_param_default_argument_redefinition) 284 << NewParam->getDefaultArgRange(); 285 286 // Look for the function declaration where the default argument was 287 // actually written, which may be a declaration prior to Old. 288 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 289 Older; Older = Older->getPreviousDeclaration()) { 290 if (!Older->getParamDecl(p)->hasDefaultArg()) 291 break; 292 293 OldParam = Older->getParamDecl(p); 294 } 295 296 Diag(OldParam->getLocation(), diag::note_previous_definition) 297 << OldParam->getDefaultArgRange(); 298 Invalid = true; 299 } else if (OldParam->hasDefaultArg()) { 300 // Merge the old default argument into the new parameter 301 if (OldParam->hasUninstantiatedDefaultArg()) 302 NewParam->setUninstantiatedDefaultArg( 303 OldParam->getUninstantiatedDefaultArg()); 304 else 305 NewParam->setDefaultArg(OldParam->getDefaultArg()); 306 } else if (NewParam->hasDefaultArg()) { 307 if (New->getDescribedFunctionTemplate()) { 308 // Paragraph 4, quoted above, only applies to non-template functions. 309 Diag(NewParam->getLocation(), 310 diag::err_param_default_argument_template_redecl) 311 << NewParam->getDefaultArgRange(); 312 Diag(Old->getLocation(), diag::note_template_prev_declaration) 313 << false; 314 } else if (New->getTemplateSpecializationKind() 315 != TSK_ImplicitInstantiation && 316 New->getTemplateSpecializationKind() != TSK_Undeclared) { 317 // C++ [temp.expr.spec]p21: 318 // Default function arguments shall not be specified in a declaration 319 // or a definition for one of the following explicit specializations: 320 // - the explicit specialization of a function template; 321 // - the explicit specialization of a member function template; 322 // - the explicit specialization of a member function of a class 323 // template where the class template specialization to which the 324 // member function specialization belongs is implicitly 325 // instantiated. 326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 328 << New->getDeclName() 329 << NewParam->getDefaultArgRange(); 330 } else if (New->getDeclContext()->isDependentContext()) { 331 // C++ [dcl.fct.default]p6 (DR217): 332 // Default arguments for a member function of a class template shall 333 // be specified on the initial declaration of the member function 334 // within the class template. 335 // 336 // Reading the tea leaves a bit in DR217 and its reference to DR205 337 // leads me to the conclusion that one cannot add default function 338 // arguments for an out-of-line definition of a member function of a 339 // dependent type. 340 int WhichKind = 2; 341 if (CXXRecordDecl *Record 342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 343 if (Record->getDescribedClassTemplate()) 344 WhichKind = 0; 345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 346 WhichKind = 1; 347 else 348 WhichKind = 2; 349 } 350 351 Diag(NewParam->getLocation(), 352 diag::err_param_default_argument_member_template_redecl) 353 << WhichKind 354 << NewParam->getDefaultArgRange(); 355 } 356 } 357 } 358 359 if (CheckEquivalentExceptionSpec( 360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(), 361 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) 362 Invalid = true; 363 364 return Invalid; 365} 366 367/// CheckCXXDefaultArguments - Verify that the default arguments for a 368/// function declaration are well-formed according to C++ 369/// [dcl.fct.default]. 370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 371 unsigned NumParams = FD->getNumParams(); 372 unsigned p; 373 374 // Find first parameter with a default argument 375 for (p = 0; p < NumParams; ++p) { 376 ParmVarDecl *Param = FD->getParamDecl(p); 377 if (Param->hasDefaultArg()) 378 break; 379 } 380 381 // C++ [dcl.fct.default]p4: 382 // In a given function declaration, all parameters 383 // subsequent to a parameter with a default argument shall 384 // have default arguments supplied in this or previous 385 // declarations. A default argument shall not be redefined 386 // by a later declaration (not even to the same value). 387 unsigned LastMissingDefaultArg = 0; 388 for (; p < NumParams; ++p) { 389 ParmVarDecl *Param = FD->getParamDecl(p); 390 if (!Param->hasDefaultArg()) { 391 if (Param->isInvalidDecl()) 392 /* We already complained about this parameter. */; 393 else if (Param->getIdentifier()) 394 Diag(Param->getLocation(), 395 diag::err_param_default_argument_missing_name) 396 << Param->getIdentifier(); 397 else 398 Diag(Param->getLocation(), 399 diag::err_param_default_argument_missing); 400 401 LastMissingDefaultArg = p; 402 } 403 } 404 405 if (LastMissingDefaultArg > 0) { 406 // Some default arguments were missing. Clear out all of the 407 // default arguments up to (and including) the last missing 408 // default argument, so that we leave the function parameters 409 // in a semantically valid state. 410 for (p = 0; p <= LastMissingDefaultArg; ++p) { 411 ParmVarDecl *Param = FD->getParamDecl(p); 412 if (Param->hasDefaultArg()) { 413 if (!Param->hasUnparsedDefaultArg()) 414 Param->getDefaultArg()->Destroy(Context); 415 Param->setDefaultArg(0); 416 } 417 } 418 } 419} 420 421/// isCurrentClassName - Determine whether the identifier II is the 422/// name of the class type currently being defined. In the case of 423/// nested classes, this will only return true if II is the name of 424/// the innermost class. 425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 426 const CXXScopeSpec *SS) { 427 assert(getLangOptions().CPlusPlus && "No class names in C!"); 428 429 CXXRecordDecl *CurDecl; 430 if (SS && SS->isSet() && !SS->isInvalid()) { 431 DeclContext *DC = computeDeclContext(*SS, true); 432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 433 } else 434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 435 436 if (CurDecl) 437 return &II == CurDecl->getIdentifier(); 438 else 439 return false; 440} 441 442/// \brief Check the validity of a C++ base class specifier. 443/// 444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 445/// and returns NULL otherwise. 446CXXBaseSpecifier * 447Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 448 SourceRange SpecifierRange, 449 bool Virtual, AccessSpecifier Access, 450 QualType BaseType, 451 SourceLocation BaseLoc) { 452 // C++ [class.union]p1: 453 // A union shall not have base classes. 454 if (Class->isUnion()) { 455 Diag(Class->getLocation(), diag::err_base_clause_on_union) 456 << SpecifierRange; 457 return 0; 458 } 459 460 if (BaseType->isDependentType()) 461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 462 Class->getTagKind() == RecordDecl::TK_class, 463 Access, BaseType); 464 465 // Base specifiers must be record types. 466 if (!BaseType->isRecordType()) { 467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 468 return 0; 469 } 470 471 // C++ [class.union]p1: 472 // A union shall not be used as a base class. 473 if (BaseType->isUnionType()) { 474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 475 return 0; 476 } 477 478 // C++ [class.derived]p2: 479 // The class-name in a base-specifier shall not be an incompletely 480 // defined class. 481 if (RequireCompleteType(BaseLoc, BaseType, 482 PDiag(diag::err_incomplete_base_class) 483 << SpecifierRange)) 484 return 0; 485 486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 488 assert(BaseDecl && "Record type has no declaration"); 489 BaseDecl = BaseDecl->getDefinition(Context); 490 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 492 assert(CXXBaseDecl && "Base type is not a C++ type"); 493 494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 495 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 498 << BaseType; 499 return 0; 500 } 501 502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 503 504 // Create the base specifier. 505 // FIXME: Allocate via ASTContext? 506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 507 Class->getTagKind() == RecordDecl::TK_class, 508 Access, BaseType); 509} 510 511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 512 const CXXRecordDecl *BaseClass, 513 bool BaseIsVirtual) { 514 // A class with a non-empty base class is not empty. 515 // FIXME: Standard ref? 516 if (!BaseClass->isEmpty()) 517 Class->setEmpty(false); 518 519 // C++ [class.virtual]p1: 520 // A class that [...] inherits a virtual function is called a polymorphic 521 // class. 522 if (BaseClass->isPolymorphic()) 523 Class->setPolymorphic(true); 524 525 // C++ [dcl.init.aggr]p1: 526 // An aggregate is [...] a class with [...] no base classes [...]. 527 Class->setAggregate(false); 528 529 // C++ [class]p4: 530 // A POD-struct is an aggregate class... 531 Class->setPOD(false); 532 533 if (BaseIsVirtual) { 534 // C++ [class.ctor]p5: 535 // A constructor is trivial if its class has no virtual base classes. 536 Class->setHasTrivialConstructor(false); 537 538 // C++ [class.copy]p6: 539 // A copy constructor is trivial if its class has no virtual base classes. 540 Class->setHasTrivialCopyConstructor(false); 541 542 // C++ [class.copy]p11: 543 // A copy assignment operator is trivial if its class has no virtual 544 // base classes. 545 Class->setHasTrivialCopyAssignment(false); 546 547 // C++0x [meta.unary.prop] is_empty: 548 // T is a class type, but not a union type, with ... no virtual base 549 // classes 550 Class->setEmpty(false); 551 } else { 552 // C++ [class.ctor]p5: 553 // A constructor is trivial if all the direct base classes of its 554 // class have trivial constructors. 555 if (!BaseClass->hasTrivialConstructor()) 556 Class->setHasTrivialConstructor(false); 557 558 // C++ [class.copy]p6: 559 // A copy constructor is trivial if all the direct base classes of its 560 // class have trivial copy constructors. 561 if (!BaseClass->hasTrivialCopyConstructor()) 562 Class->setHasTrivialCopyConstructor(false); 563 564 // C++ [class.copy]p11: 565 // A copy assignment operator is trivial if all the direct base classes 566 // of its class have trivial copy assignment operators. 567 if (!BaseClass->hasTrivialCopyAssignment()) 568 Class->setHasTrivialCopyAssignment(false); 569 } 570 571 // C++ [class.ctor]p3: 572 // A destructor is trivial if all the direct base classes of its class 573 // have trivial destructors. 574 if (!BaseClass->hasTrivialDestructor()) 575 Class->setHasTrivialDestructor(false); 576} 577 578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 579/// one entry in the base class list of a class specifier, for 580/// example: 581/// class foo : public bar, virtual private baz { 582/// 'public bar' and 'virtual private baz' are each base-specifiers. 583Sema::BaseResult 584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 585 bool Virtual, AccessSpecifier Access, 586 TypeTy *basetype, SourceLocation BaseLoc) { 587 if (!classdecl) 588 return true; 589 590 AdjustDeclIfTemplate(classdecl); 591 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 592 QualType BaseType = GetTypeFromParser(basetype); 593 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 594 Virtual, Access, 595 BaseType, BaseLoc)) 596 return BaseSpec; 597 598 return true; 599} 600 601/// \brief Performs the actual work of attaching the given base class 602/// specifiers to a C++ class. 603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 604 unsigned NumBases) { 605 if (NumBases == 0) 606 return false; 607 608 // Used to keep track of which base types we have already seen, so 609 // that we can properly diagnose redundant direct base types. Note 610 // that the key is always the unqualified canonical type of the base 611 // class. 612 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 613 614 // Copy non-redundant base specifiers into permanent storage. 615 unsigned NumGoodBases = 0; 616 bool Invalid = false; 617 for (unsigned idx = 0; idx < NumBases; ++idx) { 618 QualType NewBaseType 619 = Context.getCanonicalType(Bases[idx]->getType()); 620 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 621 622 if (KnownBaseTypes[NewBaseType]) { 623 // C++ [class.mi]p3: 624 // A class shall not be specified as a direct base class of a 625 // derived class more than once. 626 Diag(Bases[idx]->getSourceRange().getBegin(), 627 diag::err_duplicate_base_class) 628 << KnownBaseTypes[NewBaseType]->getType() 629 << Bases[idx]->getSourceRange(); 630 631 // Delete the duplicate base class specifier; we're going to 632 // overwrite its pointer later. 633 Context.Deallocate(Bases[idx]); 634 635 Invalid = true; 636 } else { 637 // Okay, add this new base class. 638 KnownBaseTypes[NewBaseType] = Bases[idx]; 639 Bases[NumGoodBases++] = Bases[idx]; 640 } 641 } 642 643 // Attach the remaining base class specifiers to the derived class. 644 Class->setBases(Context, Bases, NumGoodBases); 645 646 // Delete the remaining (good) base class specifiers, since their 647 // data has been copied into the CXXRecordDecl. 648 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 649 Context.Deallocate(Bases[idx]); 650 651 return Invalid; 652} 653 654/// ActOnBaseSpecifiers - Attach the given base specifiers to the 655/// class, after checking whether there are any duplicate base 656/// classes. 657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 658 unsigned NumBases) { 659 if (!ClassDecl || !Bases || !NumBases) 660 return; 661 662 AdjustDeclIfTemplate(ClassDecl); 663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 664 (CXXBaseSpecifier**)(Bases), NumBases); 665} 666 667/// \brief Determine whether the type \p Derived is a C++ class that is 668/// derived from the type \p Base. 669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 670 if (!getLangOptions().CPlusPlus) 671 return false; 672 673 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 674 if (!DerivedRT) 675 return false; 676 677 const RecordType *BaseRT = Base->getAs<RecordType>(); 678 if (!BaseRT) 679 return false; 680 681 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 682 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 683 return DerivedRD->isDerivedFrom(BaseRD); 684} 685 686/// \brief Determine whether the type \p Derived is a C++ class that is 687/// derived from the type \p Base. 688bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 689 if (!getLangOptions().CPlusPlus) 690 return false; 691 692 const RecordType *DerivedRT = Derived->getAs<RecordType>(); 693 if (!DerivedRT) 694 return false; 695 696 const RecordType *BaseRT = Base->getAs<RecordType>(); 697 if (!BaseRT) 698 return false; 699 700 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl()); 701 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 702 return DerivedRD->isDerivedFrom(BaseRD, Paths); 703} 704 705/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 706/// conversion (where Derived and Base are class types) is 707/// well-formed, meaning that the conversion is unambiguous (and 708/// that all of the base classes are accessible). Returns true 709/// and emits a diagnostic if the code is ill-formed, returns false 710/// otherwise. Loc is the location where this routine should point to 711/// if there is an error, and Range is the source range to highlight 712/// if there is an error. 713bool 714Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 715 unsigned InaccessibleBaseID, 716 unsigned AmbigiousBaseConvID, 717 SourceLocation Loc, SourceRange Range, 718 DeclarationName Name) { 719 // First, determine whether the path from Derived to Base is 720 // ambiguous. This is slightly more expensive than checking whether 721 // the Derived to Base conversion exists, because here we need to 722 // explore multiple paths to determine if there is an ambiguity. 723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 724 /*DetectVirtual=*/false); 725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 726 assert(DerivationOkay && 727 "Can only be used with a derived-to-base conversion"); 728 (void)DerivationOkay; 729 730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 731 if (InaccessibleBaseID == 0) 732 return false; 733 // Check that the base class can be accessed. 734 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc, 735 Name); 736 } 737 738 // We know that the derived-to-base conversion is ambiguous, and 739 // we're going to produce a diagnostic. Perform the derived-to-base 740 // search just one more time to compute all of the possible paths so 741 // that we can print them out. This is more expensive than any of 742 // the previous derived-to-base checks we've done, but at this point 743 // performance isn't as much of an issue. 744 Paths.clear(); 745 Paths.setRecordingPaths(true); 746 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 747 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 748 (void)StillOkay; 749 750 // Build up a textual representation of the ambiguous paths, e.g., 751 // D -> B -> A, that will be used to illustrate the ambiguous 752 // conversions in the diagnostic. We only print one of the paths 753 // to each base class subobject. 754 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 755 756 Diag(Loc, AmbigiousBaseConvID) 757 << Derived << Base << PathDisplayStr << Range << Name; 758 return true; 759} 760 761bool 762Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 763 SourceLocation Loc, SourceRange Range, 764 bool IgnoreAccess) { 765 return CheckDerivedToBaseConversion(Derived, Base, 766 IgnoreAccess ? 0 : 767 diag::err_conv_to_inaccessible_base, 768 diag::err_ambiguous_derived_to_base_conv, 769 Loc, Range, DeclarationName()); 770} 771 772 773/// @brief Builds a string representing ambiguous paths from a 774/// specific derived class to different subobjects of the same base 775/// class. 776/// 777/// This function builds a string that can be used in error messages 778/// to show the different paths that one can take through the 779/// inheritance hierarchy to go from the derived class to different 780/// subobjects of a base class. The result looks something like this: 781/// @code 782/// struct D -> struct B -> struct A 783/// struct D -> struct C -> struct A 784/// @endcode 785std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 786 std::string PathDisplayStr; 787 std::set<unsigned> DisplayedPaths; 788 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 789 Path != Paths.end(); ++Path) { 790 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 791 // We haven't displayed a path to this particular base 792 // class subobject yet. 793 PathDisplayStr += "\n "; 794 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 795 for (CXXBasePath::const_iterator Element = Path->begin(); 796 Element != Path->end(); ++Element) 797 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 798 } 799 } 800 801 return PathDisplayStr; 802} 803 804//===----------------------------------------------------------------------===// 805// C++ class member Handling 806//===----------------------------------------------------------------------===// 807 808/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 809/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 810/// bitfield width if there is one and 'InitExpr' specifies the initializer if 811/// any. 812Sema::DeclPtrTy 813Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 814 MultiTemplateParamsArg TemplateParameterLists, 815 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 816 bool Deleted) { 817 const DeclSpec &DS = D.getDeclSpec(); 818 DeclarationName Name = GetNameForDeclarator(D); 819 Expr *BitWidth = static_cast<Expr*>(BW); 820 Expr *Init = static_cast<Expr*>(InitExpr); 821 SourceLocation Loc = D.getIdentifierLoc(); 822 823 bool isFunc = D.isFunctionDeclarator(); 824 825 assert(!DS.isFriendSpecified()); 826 827 // C++ 9.2p6: A member shall not be declared to have automatic storage 828 // duration (auto, register) or with the extern storage-class-specifier. 829 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 830 // data members and cannot be applied to names declared const or static, 831 // and cannot be applied to reference members. 832 switch (DS.getStorageClassSpec()) { 833 case DeclSpec::SCS_unspecified: 834 case DeclSpec::SCS_typedef: 835 case DeclSpec::SCS_static: 836 // FALL THROUGH. 837 break; 838 case DeclSpec::SCS_mutable: 839 if (isFunc) { 840 if (DS.getStorageClassSpecLoc().isValid()) 841 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 842 else 843 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 844 845 // FIXME: It would be nicer if the keyword was ignored only for this 846 // declarator. Otherwise we could get follow-up errors. 847 D.getMutableDeclSpec().ClearStorageClassSpecs(); 848 } else { 849 QualType T = GetTypeForDeclarator(D, S); 850 diag::kind err = static_cast<diag::kind>(0); 851 if (T->isReferenceType()) 852 err = diag::err_mutable_reference; 853 else if (T.isConstQualified()) 854 err = diag::err_mutable_const; 855 if (err != 0) { 856 if (DS.getStorageClassSpecLoc().isValid()) 857 Diag(DS.getStorageClassSpecLoc(), err); 858 else 859 Diag(DS.getThreadSpecLoc(), err); 860 // FIXME: It would be nicer if the keyword was ignored only for this 861 // declarator. Otherwise we could get follow-up errors. 862 D.getMutableDeclSpec().ClearStorageClassSpecs(); 863 } 864 } 865 break; 866 default: 867 if (DS.getStorageClassSpecLoc().isValid()) 868 Diag(DS.getStorageClassSpecLoc(), 869 diag::err_storageclass_invalid_for_member); 870 else 871 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 872 D.getMutableDeclSpec().ClearStorageClassSpecs(); 873 } 874 875 if (!isFunc && 876 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 877 D.getNumTypeObjects() == 0) { 878 // Check also for this case: 879 // 880 // typedef int f(); 881 // f a; 882 // 883 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 884 isFunc = TDType->isFunctionType(); 885 } 886 887 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 888 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 889 !isFunc); 890 891 Decl *Member; 892 if (isInstField) { 893 // FIXME: Check for template parameters! 894 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 895 AS); 896 assert(Member && "HandleField never returns null"); 897 } else { 898 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 899 .getAs<Decl>(); 900 if (!Member) { 901 if (BitWidth) DeleteExpr(BitWidth); 902 return DeclPtrTy(); 903 } 904 905 // Non-instance-fields can't have a bitfield. 906 if (BitWidth) { 907 if (Member->isInvalidDecl()) { 908 // don't emit another diagnostic. 909 } else if (isa<VarDecl>(Member)) { 910 // C++ 9.6p3: A bit-field shall not be a static member. 911 // "static member 'A' cannot be a bit-field" 912 Diag(Loc, diag::err_static_not_bitfield) 913 << Name << BitWidth->getSourceRange(); 914 } else if (isa<TypedefDecl>(Member)) { 915 // "typedef member 'x' cannot be a bit-field" 916 Diag(Loc, diag::err_typedef_not_bitfield) 917 << Name << BitWidth->getSourceRange(); 918 } else { 919 // A function typedef ("typedef int f(); f a;"). 920 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 921 Diag(Loc, diag::err_not_integral_type_bitfield) 922 << Name << cast<ValueDecl>(Member)->getType() 923 << BitWidth->getSourceRange(); 924 } 925 926 DeleteExpr(BitWidth); 927 BitWidth = 0; 928 Member->setInvalidDecl(); 929 } 930 931 Member->setAccess(AS); 932 933 // If we have declared a member function template, set the access of the 934 // templated declaration as well. 935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 936 FunTmpl->getTemplatedDecl()->setAccess(AS); 937 } 938 939 assert((Name || isInstField) && "No identifier for non-field ?"); 940 941 if (Init) 942 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 943 if (Deleted) // FIXME: Source location is not very good. 944 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 945 946 if (isInstField) { 947 FieldCollector->Add(cast<FieldDecl>(Member)); 948 return DeclPtrTy(); 949 } 950 return DeclPtrTy::make(Member); 951} 952 953/// \brief Find the direct and/or virtual base specifiers that 954/// correspond to the given base type, for use in base initialization 955/// within a constructor. 956static bool FindBaseInitializer(Sema &SemaRef, 957 CXXRecordDecl *ClassDecl, 958 QualType BaseType, 959 const CXXBaseSpecifier *&DirectBaseSpec, 960 const CXXBaseSpecifier *&VirtualBaseSpec) { 961 // First, check for a direct base class. 962 DirectBaseSpec = 0; 963 for (CXXRecordDecl::base_class_const_iterator Base 964 = ClassDecl->bases_begin(); 965 Base != ClassDecl->bases_end(); ++Base) { 966 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 967 // We found a direct base of this type. That's what we're 968 // initializing. 969 DirectBaseSpec = &*Base; 970 break; 971 } 972 } 973 974 // Check for a virtual base class. 975 // FIXME: We might be able to short-circuit this if we know in advance that 976 // there are no virtual bases. 977 VirtualBaseSpec = 0; 978 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 979 // We haven't found a base yet; search the class hierarchy for a 980 // virtual base class. 981 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 982 /*DetectVirtual=*/false); 983 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 984 BaseType, Paths)) { 985 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 986 Path != Paths.end(); ++Path) { 987 if (Path->back().Base->isVirtual()) { 988 VirtualBaseSpec = Path->back().Base; 989 break; 990 } 991 } 992 } 993 } 994 995 return DirectBaseSpec || VirtualBaseSpec; 996} 997 998/// ActOnMemInitializer - Handle a C++ member initializer. 999Sema::MemInitResult 1000Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 1001 Scope *S, 1002 const CXXScopeSpec &SS, 1003 IdentifierInfo *MemberOrBase, 1004 TypeTy *TemplateTypeTy, 1005 SourceLocation IdLoc, 1006 SourceLocation LParenLoc, 1007 ExprTy **Args, unsigned NumArgs, 1008 SourceLocation *CommaLocs, 1009 SourceLocation RParenLoc) { 1010 if (!ConstructorD) 1011 return true; 1012 1013 AdjustDeclIfTemplate(ConstructorD); 1014 1015 CXXConstructorDecl *Constructor 1016 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 1017 if (!Constructor) { 1018 // The user wrote a constructor initializer on a function that is 1019 // not a C++ constructor. Ignore the error for now, because we may 1020 // have more member initializers coming; we'll diagnose it just 1021 // once in ActOnMemInitializers. 1022 return true; 1023 } 1024 1025 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1026 1027 // C++ [class.base.init]p2: 1028 // Names in a mem-initializer-id are looked up in the scope of the 1029 // constructor’s class and, if not found in that scope, are looked 1030 // up in the scope containing the constructor’s 1031 // definition. [Note: if the constructor’s class contains a member 1032 // with the same name as a direct or virtual base class of the 1033 // class, a mem-initializer-id naming the member or base class and 1034 // composed of a single identifier refers to the class member. A 1035 // mem-initializer-id for the hidden base class may be specified 1036 // using a qualified name. ] 1037 if (!SS.getScopeRep() && !TemplateTypeTy) { 1038 // Look for a member, first. 1039 FieldDecl *Member = 0; 1040 DeclContext::lookup_result Result 1041 = ClassDecl->lookup(MemberOrBase); 1042 if (Result.first != Result.second) 1043 Member = dyn_cast<FieldDecl>(*Result.first); 1044 1045 // FIXME: Handle members of an anonymous union. 1046 1047 if (Member) 1048 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1049 LParenLoc, RParenLoc); 1050 } 1051 // It didn't name a member, so see if it names a class. 1052 QualType BaseType; 1053 TypeSourceInfo *TInfo = 0; 1054 1055 if (TemplateTypeTy) { 1056 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1057 } else { 1058 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1059 LookupParsedName(R, S, &SS); 1060 1061 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1062 if (!TyD) { 1063 if (R.isAmbiguous()) return true; 1064 1065 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1066 bool NotUnknownSpecialization = false; 1067 DeclContext *DC = computeDeclContext(SS, false); 1068 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1069 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1070 1071 if (!NotUnknownSpecialization) { 1072 // When the scope specifier can refer to a member of an unknown 1073 // specialization, we take it as a type name. 1074 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(), 1075 *MemberOrBase, SS.getRange()); 1076 R.clear(); 1077 } 1078 } 1079 1080 // If no results were found, try to correct typos. 1081 if (R.empty() && BaseType.isNull() && 1082 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) { 1083 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1084 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 1085 // We have found a non-static data member with a similar 1086 // name to what was typed; complain and initialize that 1087 // member. 1088 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1089 << MemberOrBase << true << R.getLookupName() 1090 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 1091 R.getLookupName().getAsString()); 1092 Diag(Member->getLocation(), diag::note_previous_decl) 1093 << Member->getDeclName(); 1094 1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1096 LParenLoc, RParenLoc); 1097 } 1098 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1099 const CXXBaseSpecifier *DirectBaseSpec; 1100 const CXXBaseSpecifier *VirtualBaseSpec; 1101 if (FindBaseInitializer(*this, ClassDecl, 1102 Context.getTypeDeclType(Type), 1103 DirectBaseSpec, VirtualBaseSpec)) { 1104 // We have found a direct or virtual base class with a 1105 // similar name to what was typed; complain and initialize 1106 // that base class. 1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1108 << MemberOrBase << false << R.getLookupName() 1109 << CodeModificationHint::CreateReplacement(R.getNameLoc(), 1110 R.getLookupName().getAsString()); 1111 1112 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1113 : VirtualBaseSpec; 1114 Diag(BaseSpec->getSourceRange().getBegin(), 1115 diag::note_base_class_specified_here) 1116 << BaseSpec->getType() 1117 << BaseSpec->getSourceRange(); 1118 1119 TyD = Type; 1120 } 1121 } 1122 } 1123 1124 if (!TyD && BaseType.isNull()) { 1125 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1126 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1127 return true; 1128 } 1129 } 1130 1131 if (BaseType.isNull()) { 1132 BaseType = Context.getTypeDeclType(TyD); 1133 if (SS.isSet()) { 1134 NestedNameSpecifier *Qualifier = 1135 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1136 1137 // FIXME: preserve source range information 1138 BaseType = Context.getQualifiedNameType(Qualifier, BaseType); 1139 } 1140 } 1141 } 1142 1143 if (!TInfo) 1144 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1145 1146 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1147 LParenLoc, RParenLoc, ClassDecl); 1148} 1149 1150/// Checks an initializer expression for use of uninitialized fields, such as 1151/// containing the field that is being initialized. Returns true if there is an 1152/// uninitialized field was used an updates the SourceLocation parameter; false 1153/// otherwise. 1154static bool InitExprContainsUninitializedFields(const Stmt* S, 1155 const FieldDecl* LhsField, 1156 SourceLocation* L) { 1157 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 1158 if (ME) { 1159 const NamedDecl* RhsField = ME->getMemberDecl(); 1160 if (RhsField == LhsField) { 1161 // Initializing a field with itself. Throw a warning. 1162 // But wait; there are exceptions! 1163 // Exception #1: The field may not belong to this record. 1164 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1165 const Expr* base = ME->getBase(); 1166 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1167 // Even though the field matches, it does not belong to this record. 1168 return false; 1169 } 1170 // None of the exceptions triggered; return true to indicate an 1171 // uninitialized field was used. 1172 *L = ME->getMemberLoc(); 1173 return true; 1174 } 1175 } 1176 bool found = false; 1177 for (Stmt::const_child_iterator it = S->child_begin(); 1178 it != S->child_end() && found == false; 1179 ++it) { 1180 if (isa<CallExpr>(S)) { 1181 // Do not descend into function calls or constructors, as the use 1182 // of an uninitialized field may be valid. One would have to inspect 1183 // the contents of the function/ctor to determine if it is safe or not. 1184 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1185 // may be safe, depending on what the function/ctor does. 1186 continue; 1187 } 1188 found = InitExprContainsUninitializedFields(*it, LhsField, L); 1189 } 1190 return found; 1191} 1192 1193Sema::MemInitResult 1194Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1195 unsigned NumArgs, SourceLocation IdLoc, 1196 SourceLocation LParenLoc, 1197 SourceLocation RParenLoc) { 1198 // Diagnose value-uses of fields to initialize themselves, e.g. 1199 // foo(foo) 1200 // where foo is not also a parameter to the constructor. 1201 // TODO: implement -Wuninitialized and fold this into that framework. 1202 for (unsigned i = 0; i < NumArgs; ++i) { 1203 SourceLocation L; 1204 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1205 // FIXME: Return true in the case when other fields are used before being 1206 // uninitialized. For example, let this field be the i'th field. When 1207 // initializing the i'th field, throw a warning if any of the >= i'th 1208 // fields are used, as they are not yet initialized. 1209 // Right now we are only handling the case where the i'th field uses 1210 // itself in its initializer. 1211 Diag(L, diag::warn_field_is_uninit); 1212 } 1213 } 1214 1215 bool HasDependentArg = false; 1216 for (unsigned i = 0; i < NumArgs; i++) 1217 HasDependentArg |= Args[i]->isTypeDependent(); 1218 1219 QualType FieldType = Member->getType(); 1220 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1221 FieldType = Array->getElementType(); 1222 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1223 if (FieldType->isDependentType() || HasDependentArg) { 1224 // Can't check initialization for a member of dependent type or when 1225 // any of the arguments are type-dependent expressions. 1226 OwningExprResult Init 1227 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1228 RParenLoc)); 1229 1230 // Erase any temporaries within this evaluation context; we're not 1231 // going to track them in the AST, since we'll be rebuilding the 1232 // ASTs during template instantiation. 1233 ExprTemporaries.erase( 1234 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1235 ExprTemporaries.end()); 1236 1237 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1238 LParenLoc, 1239 Init.takeAs<Expr>(), 1240 RParenLoc); 1241 1242 } 1243 1244 if (Member->isInvalidDecl()) 1245 return true; 1246 1247 // Initialize the member. 1248 InitializedEntity MemberEntity = 1249 InitializedEntity::InitializeMember(Member, 0); 1250 InitializationKind Kind = 1251 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1252 1253 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1254 1255 OwningExprResult MemberInit = 1256 InitSeq.Perform(*this, MemberEntity, Kind, 1257 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1258 if (MemberInit.isInvalid()) 1259 return true; 1260 1261 // C++0x [class.base.init]p7: 1262 // The initialization of each base and member constitutes a 1263 // full-expression. 1264 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1265 if (MemberInit.isInvalid()) 1266 return true; 1267 1268 // If we are in a dependent context, template instantiation will 1269 // perform this type-checking again. Just save the arguments that we 1270 // received in a ParenListExpr. 1271 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1272 // of the information that we have about the member 1273 // initializer. However, deconstructing the ASTs is a dicey process, 1274 // and this approach is far more likely to get the corner cases right. 1275 if (CurContext->isDependentContext()) { 1276 // Bump the reference count of all of the arguments. 1277 for (unsigned I = 0; I != NumArgs; ++I) 1278 Args[I]->Retain(); 1279 1280 OwningExprResult Init 1281 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1282 RParenLoc)); 1283 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1284 LParenLoc, 1285 Init.takeAs<Expr>(), 1286 RParenLoc); 1287 } 1288 1289 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1290 LParenLoc, 1291 MemberInit.takeAs<Expr>(), 1292 RParenLoc); 1293} 1294 1295Sema::MemInitResult 1296Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1297 Expr **Args, unsigned NumArgs, 1298 SourceLocation LParenLoc, SourceLocation RParenLoc, 1299 CXXRecordDecl *ClassDecl) { 1300 bool HasDependentArg = false; 1301 for (unsigned i = 0; i < NumArgs; i++) 1302 HasDependentArg |= Args[i]->isTypeDependent(); 1303 1304 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin(); 1305 if (BaseType->isDependentType() || HasDependentArg) { 1306 // Can't check initialization for a base of dependent type or when 1307 // any of the arguments are type-dependent expressions. 1308 OwningExprResult BaseInit 1309 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1310 RParenLoc)); 1311 1312 // Erase any temporaries within this evaluation context; we're not 1313 // going to track them in the AST, since we'll be rebuilding the 1314 // ASTs during template instantiation. 1315 ExprTemporaries.erase( 1316 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1317 ExprTemporaries.end()); 1318 1319 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1320 LParenLoc, 1321 BaseInit.takeAs<Expr>(), 1322 RParenLoc); 1323 } 1324 1325 if (!BaseType->isRecordType()) 1326 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1327 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1328 1329 // C++ [class.base.init]p2: 1330 // [...] Unless the mem-initializer-id names a nonstatic data 1331 // member of the constructor’s class or a direct or virtual base 1332 // of that class, the mem-initializer is ill-formed. A 1333 // mem-initializer-list can initialize a base class using any 1334 // name that denotes that base class type. 1335 1336 // Check for direct and virtual base classes. 1337 const CXXBaseSpecifier *DirectBaseSpec = 0; 1338 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1339 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1340 VirtualBaseSpec); 1341 1342 // C++ [base.class.init]p2: 1343 // If a mem-initializer-id is ambiguous because it designates both 1344 // a direct non-virtual base class and an inherited virtual base 1345 // class, the mem-initializer is ill-formed. 1346 if (DirectBaseSpec && VirtualBaseSpec) 1347 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1348 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 1349 // C++ [base.class.init]p2: 1350 // Unless the mem-initializer-id names a nonstatic data membeer of the 1351 // constructor's class ot a direst or virtual base of that class, the 1352 // mem-initializer is ill-formed. 1353 if (!DirectBaseSpec && !VirtualBaseSpec) 1354 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1355 << BaseType << ClassDecl->getNameAsCString() 1356 << BaseTInfo->getTypeLoc().getSourceRange(); 1357 1358 CXXBaseSpecifier *BaseSpec 1359 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1360 if (!BaseSpec) 1361 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1362 1363 // Initialize the base. 1364 InitializedEntity BaseEntity = 1365 InitializedEntity::InitializeBase(Context, BaseSpec); 1366 InitializationKind Kind = 1367 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1368 1369 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1370 1371 OwningExprResult BaseInit = 1372 InitSeq.Perform(*this, BaseEntity, Kind, 1373 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1374 if (BaseInit.isInvalid()) 1375 return true; 1376 1377 // C++0x [class.base.init]p7: 1378 // The initialization of each base and member constitutes a 1379 // full-expression. 1380 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1381 if (BaseInit.isInvalid()) 1382 return true; 1383 1384 // If we are in a dependent context, template instantiation will 1385 // perform this type-checking again. Just save the arguments that we 1386 // received in a ParenListExpr. 1387 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1388 // of the information that we have about the base 1389 // initializer. However, deconstructing the ASTs is a dicey process, 1390 // and this approach is far more likely to get the corner cases right. 1391 if (CurContext->isDependentContext()) { 1392 // Bump the reference count of all of the arguments. 1393 for (unsigned I = 0; I != NumArgs; ++I) 1394 Args[I]->Retain(); 1395 1396 OwningExprResult Init 1397 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1398 RParenLoc)); 1399 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1400 LParenLoc, 1401 Init.takeAs<Expr>(), 1402 RParenLoc); 1403 } 1404 1405 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1406 LParenLoc, 1407 BaseInit.takeAs<Expr>(), 1408 RParenLoc); 1409} 1410 1411bool 1412Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1413 CXXBaseOrMemberInitializer **Initializers, 1414 unsigned NumInitializers, 1415 bool IsImplicitConstructor, 1416 bool AnyErrors) { 1417 // We need to build the initializer AST according to order of construction 1418 // and not what user specified in the Initializers list. 1419 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1420 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 1421 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1422 bool HasDependentBaseInit = false; 1423 bool HadError = false; 1424 1425 for (unsigned i = 0; i < NumInitializers; i++) { 1426 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1427 if (Member->isBaseInitializer()) { 1428 if (Member->getBaseClass()->isDependentType()) 1429 HasDependentBaseInit = true; 1430 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1431 } else { 1432 AllBaseFields[Member->getMember()] = Member; 1433 } 1434 } 1435 1436 if (HasDependentBaseInit) { 1437 // FIXME. This does not preserve the ordering of the initializers. 1438 // Try (with -Wreorder) 1439 // template<class X> struct A {}; 1440 // template<class X> struct B : A<X> { 1441 // B() : x1(10), A<X>() {} 1442 // int x1; 1443 // }; 1444 // B<int> x; 1445 // On seeing one dependent type, we should essentially exit this routine 1446 // while preserving user-declared initializer list. When this routine is 1447 // called during instantiatiation process, this routine will rebuild the 1448 // ordered initializer list correctly. 1449 1450 // If we have a dependent base initialization, we can't determine the 1451 // association between initializers and bases; just dump the known 1452 // initializers into the list, and don't try to deal with other bases. 1453 for (unsigned i = 0; i < NumInitializers; i++) { 1454 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1455 if (Member->isBaseInitializer()) 1456 AllToInit.push_back(Member); 1457 } 1458 } else { 1459 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit; 1460 1461 // Push virtual bases before others. 1462 for (CXXRecordDecl::base_class_iterator VBase = 1463 ClassDecl->vbases_begin(), 1464 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1465 if (VBase->getType()->isDependentType()) 1466 continue; 1467 if (CXXBaseOrMemberInitializer *Value 1468 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1469 AllToInit.push_back(Value); 1470 } else if (!AnyErrors) { 1471 InitializedEntity InitEntity 1472 = InitializedEntity::InitializeBase(Context, VBase); 1473 InitializationKind InitKind 1474 = InitializationKind::CreateDefault(Constructor->getLocation()); 1475 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1476 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 1477 MultiExprArg(*this, 0, 0)); 1478 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1479 if (BaseInit.isInvalid()) { 1480 HadError = true; 1481 continue; 1482 } 1483 1484 // Don't attach synthesized base initializers in a dependent 1485 // context; they'll be checked again at template instantiation 1486 // time. 1487 if (CurContext->isDependentContext()) 1488 continue; 1489 1490 CXXBaseOrMemberInitializer *CXXBaseInit = 1491 new (Context) CXXBaseOrMemberInitializer(Context, 1492 Context.getTrivialTypeSourceInfo(VBase->getType(), 1493 SourceLocation()), 1494 SourceLocation(), 1495 BaseInit.takeAs<Expr>(), 1496 SourceLocation()); 1497 AllToInit.push_back(CXXBaseInit); 1498 } 1499 } 1500 1501 for (CXXRecordDecl::base_class_iterator Base = 1502 ClassDecl->bases_begin(), 1503 E = ClassDecl->bases_end(); Base != E; ++Base) { 1504 // Virtuals are in the virtual base list and already constructed. 1505 if (Base->isVirtual()) 1506 continue; 1507 // Skip dependent types. 1508 if (Base->getType()->isDependentType()) 1509 continue; 1510 if (CXXBaseOrMemberInitializer *Value 1511 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1512 AllToInit.push_back(Value); 1513 } 1514 else if (!AnyErrors) { 1515 InitializedEntity InitEntity 1516 = InitializedEntity::InitializeBase(Context, Base); 1517 InitializationKind InitKind 1518 = InitializationKind::CreateDefault(Constructor->getLocation()); 1519 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1520 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind, 1521 MultiExprArg(*this, 0, 0)); 1522 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1523 if (BaseInit.isInvalid()) { 1524 HadError = true; 1525 continue; 1526 } 1527 1528 // Don't attach synthesized base initializers in a dependent 1529 // context; they'll be regenerated at template instantiation 1530 // time. 1531 if (CurContext->isDependentContext()) 1532 continue; 1533 1534 CXXBaseOrMemberInitializer *CXXBaseInit = 1535 new (Context) CXXBaseOrMemberInitializer(Context, 1536 Context.getTrivialTypeSourceInfo(Base->getType(), 1537 SourceLocation()), 1538 SourceLocation(), 1539 BaseInit.takeAs<Expr>(), 1540 SourceLocation()); 1541 AllToInit.push_back(CXXBaseInit); 1542 } 1543 } 1544 } 1545 1546 // non-static data members. 1547 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1548 E = ClassDecl->field_end(); Field != E; ++Field) { 1549 if ((*Field)->isAnonymousStructOrUnion()) { 1550 if (const RecordType *FieldClassType = 1551 Field->getType()->getAs<RecordType>()) { 1552 CXXRecordDecl *FieldClassDecl 1553 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1554 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1555 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1556 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1557 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1558 // set to the anonymous union data member used in the initializer 1559 // list. 1560 Value->setMember(*Field); 1561 Value->setAnonUnionMember(*FA); 1562 AllToInit.push_back(Value); 1563 break; 1564 } 1565 } 1566 } 1567 continue; 1568 } 1569 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1570 AllToInit.push_back(Value); 1571 continue; 1572 } 1573 1574 if ((*Field)->getType()->isDependentType() || AnyErrors) 1575 continue; 1576 1577 QualType FT = Context.getBaseElementType((*Field)->getType()); 1578 if (FT->getAs<RecordType>()) { 1579 InitializedEntity InitEntity 1580 = InitializedEntity::InitializeMember(*Field); 1581 InitializationKind InitKind 1582 = InitializationKind::CreateDefault(Constructor->getLocation()); 1583 1584 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 1585 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind, 1586 MultiExprArg(*this, 0, 0)); 1587 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1588 if (MemberInit.isInvalid()) { 1589 HadError = true; 1590 continue; 1591 } 1592 1593 // Don't attach synthesized member initializers in a dependent 1594 // context; they'll be regenerated a template instantiation 1595 // time. 1596 if (CurContext->isDependentContext()) 1597 continue; 1598 1599 CXXBaseOrMemberInitializer *Member = 1600 new (Context) CXXBaseOrMemberInitializer(Context, 1601 *Field, SourceLocation(), 1602 SourceLocation(), 1603 MemberInit.takeAs<Expr>(), 1604 SourceLocation()); 1605 1606 AllToInit.push_back(Member); 1607 } 1608 else if (FT->isReferenceType()) { 1609 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 1610 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1611 << 0 << (*Field)->getDeclName(); 1612 Diag((*Field)->getLocation(), diag::note_declared_at); 1613 HadError = true; 1614 } 1615 else if (FT.isConstQualified()) { 1616 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) 1617 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl) 1618 << 1 << (*Field)->getDeclName(); 1619 Diag((*Field)->getLocation(), diag::note_declared_at); 1620 HadError = true; 1621 } 1622 } 1623 1624 NumInitializers = AllToInit.size(); 1625 if (NumInitializers > 0) { 1626 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1627 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1628 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1629 1630 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1631 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) 1632 baseOrMemberInitializers[Idx] = AllToInit[Idx]; 1633 } 1634 1635 return HadError; 1636} 1637 1638static void *GetKeyForTopLevelField(FieldDecl *Field) { 1639 // For anonymous unions, use the class declaration as the key. 1640 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1641 if (RT->getDecl()->isAnonymousStructOrUnion()) 1642 return static_cast<void *>(RT->getDecl()); 1643 } 1644 return static_cast<void *>(Field); 1645} 1646 1647static void *GetKeyForBase(QualType BaseType) { 1648 if (const RecordType *RT = BaseType->getAs<RecordType>()) 1649 return (void *)RT; 1650 1651 assert(0 && "Unexpected base type!"); 1652 return 0; 1653} 1654 1655static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 1656 bool MemberMaybeAnon = false) { 1657 // For fields injected into the class via declaration of an anonymous union, 1658 // use its anonymous union class declaration as the unique key. 1659 if (Member->isMemberInitializer()) { 1660 FieldDecl *Field = Member->getMember(); 1661 1662 // After SetBaseOrMemberInitializers call, Field is the anonymous union 1663 // data member of the class. Data member used in the initializer list is 1664 // in AnonUnionMember field. 1665 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1666 Field = Member->getAnonUnionMember(); 1667 if (Field->getDeclContext()->isRecord()) { 1668 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 1669 if (RD->isAnonymousStructOrUnion()) 1670 return static_cast<void *>(RD); 1671 } 1672 return static_cast<void *>(Field); 1673 } 1674 1675 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 1676} 1677 1678/// ActOnMemInitializers - Handle the member initializers for a constructor. 1679void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1680 SourceLocation ColonLoc, 1681 MemInitTy **MemInits, unsigned NumMemInits, 1682 bool AnyErrors) { 1683 if (!ConstructorDecl) 1684 return; 1685 1686 AdjustDeclIfTemplate(ConstructorDecl); 1687 1688 CXXConstructorDecl *Constructor 1689 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1690 1691 if (!Constructor) { 1692 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1693 return; 1694 } 1695 1696 if (!Constructor->isDependentContext()) { 1697 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 1698 bool err = false; 1699 for (unsigned i = 0; i < NumMemInits; i++) { 1700 CXXBaseOrMemberInitializer *Member = 1701 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1702 void *KeyToMember = GetKeyForMember(Member); 1703 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1704 if (!PrevMember) { 1705 PrevMember = Member; 1706 continue; 1707 } 1708 if (FieldDecl *Field = Member->getMember()) 1709 Diag(Member->getSourceLocation(), 1710 diag::error_multiple_mem_initialization) 1711 << Field->getNameAsString() 1712 << Member->getSourceRange(); 1713 else { 1714 Type *BaseClass = Member->getBaseClass(); 1715 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1716 Diag(Member->getSourceLocation(), 1717 diag::error_multiple_base_initialization) 1718 << QualType(BaseClass, 0) 1719 << Member->getSourceRange(); 1720 } 1721 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1722 << 0; 1723 err = true; 1724 } 1725 1726 if (err) 1727 return; 1728 } 1729 1730 SetBaseOrMemberInitializers(Constructor, 1731 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 1732 NumMemInits, false, AnyErrors); 1733 1734 if (Constructor->isDependentContext()) 1735 return; 1736 1737 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1738 Diagnostic::Ignored && 1739 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1740 Diagnostic::Ignored) 1741 return; 1742 1743 // Also issue warning if order of ctor-initializer list does not match order 1744 // of 1) base class declarations and 2) order of non-static data members. 1745 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1746 1747 CXXRecordDecl *ClassDecl 1748 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1749 // Push virtual bases before others. 1750 for (CXXRecordDecl::base_class_iterator VBase = 1751 ClassDecl->vbases_begin(), 1752 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1753 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 1754 1755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1756 E = ClassDecl->bases_end(); Base != E; ++Base) { 1757 // Virtuals are alread in the virtual base list and are constructed 1758 // first. 1759 if (Base->isVirtual()) 1760 continue; 1761 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 1762 } 1763 1764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1765 E = ClassDecl->field_end(); Field != E; ++Field) 1766 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1767 1768 int Last = AllBaseOrMembers.size(); 1769 int curIndex = 0; 1770 CXXBaseOrMemberInitializer *PrevMember = 0; 1771 for (unsigned i = 0; i < NumMemInits; i++) { 1772 CXXBaseOrMemberInitializer *Member = 1773 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1774 void *MemberInCtorList = GetKeyForMember(Member, true); 1775 1776 for (; curIndex < Last; curIndex++) 1777 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1778 break; 1779 if (curIndex == Last) { 1780 assert(PrevMember && "Member not in member list?!"); 1781 // Initializer as specified in ctor-initializer list is out of order. 1782 // Issue a warning diagnostic. 1783 if (PrevMember->isBaseInitializer()) { 1784 // Diagnostics is for an initialized base class. 1785 Type *BaseClass = PrevMember->getBaseClass(); 1786 Diag(PrevMember->getSourceLocation(), 1787 diag::warn_base_initialized) 1788 << QualType(BaseClass, 0); 1789 } else { 1790 FieldDecl *Field = PrevMember->getMember(); 1791 Diag(PrevMember->getSourceLocation(), 1792 diag::warn_field_initialized) 1793 << Field->getNameAsString(); 1794 } 1795 // Also the note! 1796 if (FieldDecl *Field = Member->getMember()) 1797 Diag(Member->getSourceLocation(), 1798 diag::note_fieldorbase_initialized_here) << 0 1799 << Field->getNameAsString(); 1800 else { 1801 Type *BaseClass = Member->getBaseClass(); 1802 Diag(Member->getSourceLocation(), 1803 diag::note_fieldorbase_initialized_here) << 1 1804 << QualType(BaseClass, 0); 1805 } 1806 for (curIndex = 0; curIndex < Last; curIndex++) 1807 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1808 break; 1809 } 1810 PrevMember = Member; 1811 } 1812} 1813 1814void 1815Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) { 1816 // Ignore dependent destructors. 1817 if (Destructor->isDependentContext()) 1818 return; 1819 1820 CXXRecordDecl *ClassDecl = Destructor->getParent(); 1821 1822 // Non-static data members. 1823 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1824 E = ClassDecl->field_end(); I != E; ++I) { 1825 FieldDecl *Field = *I; 1826 1827 QualType FieldType = Context.getBaseElementType(Field->getType()); 1828 1829 const RecordType* RT = FieldType->getAs<RecordType>(); 1830 if (!RT) 1831 continue; 1832 1833 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1834 if (FieldClassDecl->hasTrivialDestructor()) 1835 continue; 1836 1837 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 1838 MarkDeclarationReferenced(Destructor->getLocation(), 1839 const_cast<CXXDestructorDecl*>(Dtor)); 1840 } 1841 1842 // Bases. 1843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1844 E = ClassDecl->bases_end(); Base != E; ++Base) { 1845 // Ignore virtual bases. 1846 if (Base->isVirtual()) 1847 continue; 1848 1849 // Ignore trivial destructors. 1850 CXXRecordDecl *BaseClassDecl 1851 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1852 if (BaseClassDecl->hasTrivialDestructor()) 1853 continue; 1854 1855 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1856 MarkDeclarationReferenced(Destructor->getLocation(), 1857 const_cast<CXXDestructorDecl*>(Dtor)); 1858 } 1859 1860 // Virtual bases. 1861 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1862 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1863 // Ignore trivial destructors. 1864 CXXRecordDecl *BaseClassDecl 1865 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1866 if (BaseClassDecl->hasTrivialDestructor()) 1867 continue; 1868 1869 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 1870 MarkDeclarationReferenced(Destructor->getLocation(), 1871 const_cast<CXXDestructorDecl*>(Dtor)); 1872 } 1873} 1874 1875void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1876 if (!CDtorDecl) 1877 return; 1878 1879 AdjustDeclIfTemplate(CDtorDecl); 1880 1881 if (CXXConstructorDecl *Constructor 1882 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1883 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false); 1884} 1885 1886namespace { 1887 /// PureVirtualMethodCollector - traverses a class and its superclasses 1888 /// and determines if it has any pure virtual methods. 1889 class PureVirtualMethodCollector { 1890 ASTContext &Context; 1891 1892 public: 1893 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1894 1895 private: 1896 MethodList Methods; 1897 1898 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1899 1900 public: 1901 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1902 : Context(Ctx) { 1903 1904 MethodList List; 1905 Collect(RD, List); 1906 1907 // Copy the temporary list to methods, and make sure to ignore any 1908 // null entries. 1909 for (size_t i = 0, e = List.size(); i != e; ++i) { 1910 if (List[i]) 1911 Methods.push_back(List[i]); 1912 } 1913 } 1914 1915 bool empty() const { return Methods.empty(); } 1916 1917 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1918 MethodList::const_iterator methods_end() { return Methods.end(); } 1919 }; 1920 1921 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1922 MethodList& Methods) { 1923 // First, collect the pure virtual methods for the base classes. 1924 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1925 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1926 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1927 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1928 if (BaseDecl && BaseDecl->isAbstract()) 1929 Collect(BaseDecl, Methods); 1930 } 1931 } 1932 1933 // Next, zero out any pure virtual methods that this class overrides. 1934 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1935 1936 MethodSetTy OverriddenMethods; 1937 size_t MethodsSize = Methods.size(); 1938 1939 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1940 i != e; ++i) { 1941 // Traverse the record, looking for methods. 1942 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1943 // If the method is pure virtual, add it to the methods vector. 1944 if (MD->isPure()) 1945 Methods.push_back(MD); 1946 1947 // Record all the overridden methods in our set. 1948 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1949 E = MD->end_overridden_methods(); I != E; ++I) { 1950 // Keep track of the overridden methods. 1951 OverriddenMethods.insert(*I); 1952 } 1953 } 1954 } 1955 1956 // Now go through the methods and zero out all the ones we know are 1957 // overridden. 1958 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1959 if (OverriddenMethods.count(Methods[i])) 1960 Methods[i] = 0; 1961 } 1962 1963 } 1964} 1965 1966 1967bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1968 unsigned DiagID, AbstractDiagSelID SelID, 1969 const CXXRecordDecl *CurrentRD) { 1970 if (SelID == -1) 1971 return RequireNonAbstractType(Loc, T, 1972 PDiag(DiagID), CurrentRD); 1973 else 1974 return RequireNonAbstractType(Loc, T, 1975 PDiag(DiagID) << SelID, CurrentRD); 1976} 1977 1978bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1979 const PartialDiagnostic &PD, 1980 const CXXRecordDecl *CurrentRD) { 1981 if (!getLangOptions().CPlusPlus) 1982 return false; 1983 1984 if (const ArrayType *AT = Context.getAsArrayType(T)) 1985 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1986 CurrentRD); 1987 1988 if (const PointerType *PT = T->getAs<PointerType>()) { 1989 // Find the innermost pointer type. 1990 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1991 PT = T; 1992 1993 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1994 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1995 } 1996 1997 const RecordType *RT = T->getAs<RecordType>(); 1998 if (!RT) 1999 return false; 2000 2001 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2002 if (!RD) 2003 return false; 2004 2005 if (CurrentRD && CurrentRD != RD) 2006 return false; 2007 2008 if (!RD->isAbstract()) 2009 return false; 2010 2011 Diag(Loc, PD) << RD->getDeclName(); 2012 2013 // Check if we've already emitted the list of pure virtual functions for this 2014 // class. 2015 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2016 return true; 2017 2018 PureVirtualMethodCollector Collector(Context, RD); 2019 2020 for (PureVirtualMethodCollector::MethodList::const_iterator I = 2021 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 2022 const CXXMethodDecl *MD = *I; 2023 2024 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 2025 MD->getDeclName(); 2026 } 2027 2028 if (!PureVirtualClassDiagSet) 2029 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2030 PureVirtualClassDiagSet->insert(RD); 2031 2032 return true; 2033} 2034 2035namespace { 2036 class AbstractClassUsageDiagnoser 2037 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 2038 Sema &SemaRef; 2039 CXXRecordDecl *AbstractClass; 2040 2041 bool VisitDeclContext(const DeclContext *DC) { 2042 bool Invalid = false; 2043 2044 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 2045 E = DC->decls_end(); I != E; ++I) 2046 Invalid |= Visit(*I); 2047 2048 return Invalid; 2049 } 2050 2051 public: 2052 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 2053 : SemaRef(SemaRef), AbstractClass(ac) { 2054 Visit(SemaRef.Context.getTranslationUnitDecl()); 2055 } 2056 2057 bool VisitFunctionDecl(const FunctionDecl *FD) { 2058 if (FD->isThisDeclarationADefinition()) { 2059 // No need to do the check if we're in a definition, because it requires 2060 // that the return/param types are complete. 2061 // because that requires 2062 return VisitDeclContext(FD); 2063 } 2064 2065 // Check the return type. 2066 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 2067 bool Invalid = 2068 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 2069 diag::err_abstract_type_in_decl, 2070 Sema::AbstractReturnType, 2071 AbstractClass); 2072 2073 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 2074 E = FD->param_end(); I != E; ++I) { 2075 const ParmVarDecl *VD = *I; 2076 Invalid |= 2077 SemaRef.RequireNonAbstractType(VD->getLocation(), 2078 VD->getOriginalType(), 2079 diag::err_abstract_type_in_decl, 2080 Sema::AbstractParamType, 2081 AbstractClass); 2082 } 2083 2084 return Invalid; 2085 } 2086 2087 bool VisitDecl(const Decl* D) { 2088 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 2089 return VisitDeclContext(DC); 2090 2091 return false; 2092 } 2093 }; 2094} 2095 2096/// \brief Perform semantic checks on a class definition that has been 2097/// completing, introducing implicitly-declared members, checking for 2098/// abstract types, etc. 2099void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2100 if (!Record || Record->isInvalidDecl()) 2101 return; 2102 2103 if (!Record->isDependentType()) 2104 AddImplicitlyDeclaredMembersToClass(Record); 2105 2106 if (Record->isInvalidDecl()) 2107 return; 2108 2109 // Set access bits correctly on the directly-declared conversions. 2110 UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 2111 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 2112 Convs->setAccess(I, (*I)->getAccess()); 2113 2114 if (!Record->isAbstract()) { 2115 // Collect all the pure virtual methods and see if this is an abstract 2116 // class after all. 2117 PureVirtualMethodCollector Collector(Context, Record); 2118 if (!Collector.empty()) 2119 Record->setAbstract(true); 2120 } 2121 2122 if (Record->isAbstract()) 2123 (void)AbstractClassUsageDiagnoser(*this, Record); 2124} 2125 2126void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2127 DeclPtrTy TagDecl, 2128 SourceLocation LBrac, 2129 SourceLocation RBrac) { 2130 if (!TagDecl) 2131 return; 2132 2133 AdjustDeclIfTemplate(TagDecl); 2134 2135 ActOnFields(S, RLoc, TagDecl, 2136 (DeclPtrTy*)FieldCollector->getCurFields(), 2137 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 2138 2139 CheckCompletedCXXClass( 2140 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 2141} 2142 2143/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2144/// special functions, such as the default constructor, copy 2145/// constructor, or destructor, to the given C++ class (C++ 2146/// [special]p1). This routine can only be executed just before the 2147/// definition of the class is complete. 2148void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 2149 CanQualType ClassType 2150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2151 2152 // FIXME: Implicit declarations have exception specifications, which are 2153 // the union of the specifications of the implicitly called functions. 2154 2155 if (!ClassDecl->hasUserDeclaredConstructor()) { 2156 // C++ [class.ctor]p5: 2157 // A default constructor for a class X is a constructor of class X 2158 // that can be called without an argument. If there is no 2159 // user-declared constructor for class X, a default constructor is 2160 // implicitly declared. An implicitly-declared default constructor 2161 // is an inline public member of its class. 2162 DeclarationName Name 2163 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2164 CXXConstructorDecl *DefaultCon = 2165 CXXConstructorDecl::Create(Context, ClassDecl, 2166 ClassDecl->getLocation(), Name, 2167 Context.getFunctionType(Context.VoidTy, 2168 0, 0, false, 0), 2169 /*TInfo=*/0, 2170 /*isExplicit=*/false, 2171 /*isInline=*/true, 2172 /*isImplicitlyDeclared=*/true); 2173 DefaultCon->setAccess(AS_public); 2174 DefaultCon->setImplicit(); 2175 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 2176 ClassDecl->addDecl(DefaultCon); 2177 } 2178 2179 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 2180 // C++ [class.copy]p4: 2181 // If the class definition does not explicitly declare a copy 2182 // constructor, one is declared implicitly. 2183 2184 // C++ [class.copy]p5: 2185 // The implicitly-declared copy constructor for a class X will 2186 // have the form 2187 // 2188 // X::X(const X&) 2189 // 2190 // if 2191 bool HasConstCopyConstructor = true; 2192 2193 // -- each direct or virtual base class B of X has a copy 2194 // constructor whose first parameter is of type const B& or 2195 // const volatile B&, and 2196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2197 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 2198 const CXXRecordDecl *BaseClassDecl 2199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2200 HasConstCopyConstructor 2201 = BaseClassDecl->hasConstCopyConstructor(Context); 2202 } 2203 2204 // -- for all the nonstatic data members of X that are of a 2205 // class type M (or array thereof), each such class type 2206 // has a copy constructor whose first parameter is of type 2207 // const M& or const volatile M&. 2208 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2209 HasConstCopyConstructor && Field != ClassDecl->field_end(); 2210 ++Field) { 2211 QualType FieldType = (*Field)->getType(); 2212 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2213 FieldType = Array->getElementType(); 2214 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2215 const CXXRecordDecl *FieldClassDecl 2216 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2217 HasConstCopyConstructor 2218 = FieldClassDecl->hasConstCopyConstructor(Context); 2219 } 2220 } 2221 2222 // Otherwise, the implicitly declared copy constructor will have 2223 // the form 2224 // 2225 // X::X(X&) 2226 QualType ArgType = ClassType; 2227 if (HasConstCopyConstructor) 2228 ArgType = ArgType.withConst(); 2229 ArgType = Context.getLValueReferenceType(ArgType); 2230 2231 // An implicitly-declared copy constructor is an inline public 2232 // member of its class. 2233 DeclarationName Name 2234 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2235 CXXConstructorDecl *CopyConstructor 2236 = CXXConstructorDecl::Create(Context, ClassDecl, 2237 ClassDecl->getLocation(), Name, 2238 Context.getFunctionType(Context.VoidTy, 2239 &ArgType, 1, 2240 false, 0), 2241 /*TInfo=*/0, 2242 /*isExplicit=*/false, 2243 /*isInline=*/true, 2244 /*isImplicitlyDeclared=*/true); 2245 CopyConstructor->setAccess(AS_public); 2246 CopyConstructor->setImplicit(); 2247 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 2248 2249 // Add the parameter to the constructor. 2250 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 2251 ClassDecl->getLocation(), 2252 /*IdentifierInfo=*/0, 2253 ArgType, /*TInfo=*/0, 2254 VarDecl::None, 0); 2255 CopyConstructor->setParams(Context, &FromParam, 1); 2256 ClassDecl->addDecl(CopyConstructor); 2257 } 2258 2259 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2260 // Note: The following rules are largely analoguous to the copy 2261 // constructor rules. Note that virtual bases are not taken into account 2262 // for determining the argument type of the operator. Note also that 2263 // operators taking an object instead of a reference are allowed. 2264 // 2265 // C++ [class.copy]p10: 2266 // If the class definition does not explicitly declare a copy 2267 // assignment operator, one is declared implicitly. 2268 // The implicitly-defined copy assignment operator for a class X 2269 // will have the form 2270 // 2271 // X& X::operator=(const X&) 2272 // 2273 // if 2274 bool HasConstCopyAssignment = true; 2275 2276 // -- each direct base class B of X has a copy assignment operator 2277 // whose parameter is of type const B&, const volatile B& or B, 2278 // and 2279 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2280 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 2281 assert(!Base->getType()->isDependentType() && 2282 "Cannot generate implicit members for class with dependent bases."); 2283 const CXXRecordDecl *BaseClassDecl 2284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2285 const CXXMethodDecl *MD = 0; 2286 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 2287 MD); 2288 } 2289 2290 // -- for all the nonstatic data members of X that are of a class 2291 // type M (or array thereof), each such class type has a copy 2292 // assignment operator whose parameter is of type const M&, 2293 // const volatile M& or M. 2294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2295 HasConstCopyAssignment && Field != ClassDecl->field_end(); 2296 ++Field) { 2297 QualType FieldType = (*Field)->getType(); 2298 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2299 FieldType = Array->getElementType(); 2300 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2301 const CXXRecordDecl *FieldClassDecl 2302 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2303 const CXXMethodDecl *MD = 0; 2304 HasConstCopyAssignment 2305 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 2306 } 2307 } 2308 2309 // Otherwise, the implicitly declared copy assignment operator will 2310 // have the form 2311 // 2312 // X& X::operator=(X&) 2313 QualType ArgType = ClassType; 2314 QualType RetType = Context.getLValueReferenceType(ArgType); 2315 if (HasConstCopyAssignment) 2316 ArgType = ArgType.withConst(); 2317 ArgType = Context.getLValueReferenceType(ArgType); 2318 2319 // An implicitly-declared copy assignment operator is an inline public 2320 // member of its class. 2321 DeclarationName Name = 2322 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2323 CXXMethodDecl *CopyAssignment = 2324 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2325 Context.getFunctionType(RetType, &ArgType, 1, 2326 false, 0), 2327 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 2328 CopyAssignment->setAccess(AS_public); 2329 CopyAssignment->setImplicit(); 2330 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2331 CopyAssignment->setCopyAssignment(true); 2332 2333 // Add the parameter to the operator. 2334 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2335 ClassDecl->getLocation(), 2336 /*IdentifierInfo=*/0, 2337 ArgType, /*TInfo=*/0, 2338 VarDecl::None, 0); 2339 CopyAssignment->setParams(Context, &FromParam, 1); 2340 2341 // Don't call addedAssignmentOperator. There is no way to distinguish an 2342 // implicit from an explicit assignment operator. 2343 ClassDecl->addDecl(CopyAssignment); 2344 AddOverriddenMethods(ClassDecl, CopyAssignment); 2345 } 2346 2347 if (!ClassDecl->hasUserDeclaredDestructor()) { 2348 // C++ [class.dtor]p2: 2349 // If a class has no user-declared destructor, a destructor is 2350 // declared implicitly. An implicitly-declared destructor is an 2351 // inline public member of its class. 2352 DeclarationName Name 2353 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2354 CXXDestructorDecl *Destructor 2355 = CXXDestructorDecl::Create(Context, ClassDecl, 2356 ClassDecl->getLocation(), Name, 2357 Context.getFunctionType(Context.VoidTy, 2358 0, 0, false, 0), 2359 /*isInline=*/true, 2360 /*isImplicitlyDeclared=*/true); 2361 Destructor->setAccess(AS_public); 2362 Destructor->setImplicit(); 2363 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2364 ClassDecl->addDecl(Destructor); 2365 2366 AddOverriddenMethods(ClassDecl, Destructor); 2367 } 2368} 2369 2370void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2371 Decl *D = TemplateD.getAs<Decl>(); 2372 if (!D) 2373 return; 2374 2375 TemplateParameterList *Params = 0; 2376 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2377 Params = Template->getTemplateParameters(); 2378 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2379 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2380 Params = PartialSpec->getTemplateParameters(); 2381 else 2382 return; 2383 2384 for (TemplateParameterList::iterator Param = Params->begin(), 2385 ParamEnd = Params->end(); 2386 Param != ParamEnd; ++Param) { 2387 NamedDecl *Named = cast<NamedDecl>(*Param); 2388 if (Named->getDeclName()) { 2389 S->AddDecl(DeclPtrTy::make(Named)); 2390 IdResolver.AddDecl(Named); 2391 } 2392 } 2393} 2394 2395void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2396 if (!RecordD) return; 2397 AdjustDeclIfTemplate(RecordD); 2398 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 2399 PushDeclContext(S, Record); 2400} 2401 2402void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2403 if (!RecordD) return; 2404 PopDeclContext(); 2405} 2406 2407/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2408/// parsing a top-level (non-nested) C++ class, and we are now 2409/// parsing those parts of the given Method declaration that could 2410/// not be parsed earlier (C++ [class.mem]p2), such as default 2411/// arguments. This action should enter the scope of the given 2412/// Method declaration as if we had just parsed the qualified method 2413/// name. However, it should not bring the parameters into scope; 2414/// that will be performed by ActOnDelayedCXXMethodParameter. 2415void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2416} 2417 2418/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2419/// C++ method declaration. We're (re-)introducing the given 2420/// function parameter into scope for use in parsing later parts of 2421/// the method declaration. For example, we could see an 2422/// ActOnParamDefaultArgument event for this parameter. 2423void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2424 if (!ParamD) 2425 return; 2426 2427 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2428 2429 // If this parameter has an unparsed default argument, clear it out 2430 // to make way for the parsed default argument. 2431 if (Param->hasUnparsedDefaultArg()) 2432 Param->setDefaultArg(0); 2433 2434 S->AddDecl(DeclPtrTy::make(Param)); 2435 if (Param->getDeclName()) 2436 IdResolver.AddDecl(Param); 2437} 2438 2439/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2440/// processing the delayed method declaration for Method. The method 2441/// declaration is now considered finished. There may be a separate 2442/// ActOnStartOfFunctionDef action later (not necessarily 2443/// immediately!) for this method, if it was also defined inside the 2444/// class body. 2445void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2446 if (!MethodD) 2447 return; 2448 2449 AdjustDeclIfTemplate(MethodD); 2450 2451 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2452 2453 // Now that we have our default arguments, check the constructor 2454 // again. It could produce additional diagnostics or affect whether 2455 // the class has implicitly-declared destructors, among other 2456 // things. 2457 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2458 CheckConstructor(Constructor); 2459 2460 // Check the default arguments, which we may have added. 2461 if (!Method->isInvalidDecl()) 2462 CheckCXXDefaultArguments(Method); 2463} 2464 2465/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2466/// the well-formedness of the constructor declarator @p D with type @p 2467/// R. If there are any errors in the declarator, this routine will 2468/// emit diagnostics and set the invalid bit to true. In any case, the type 2469/// will be updated to reflect a well-formed type for the constructor and 2470/// returned. 2471QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2472 FunctionDecl::StorageClass &SC) { 2473 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2474 2475 // C++ [class.ctor]p3: 2476 // A constructor shall not be virtual (10.3) or static (9.4). A 2477 // constructor can be invoked for a const, volatile or const 2478 // volatile object. A constructor shall not be declared const, 2479 // volatile, or const volatile (9.3.2). 2480 if (isVirtual) { 2481 if (!D.isInvalidType()) 2482 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2483 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2484 << SourceRange(D.getIdentifierLoc()); 2485 D.setInvalidType(); 2486 } 2487 if (SC == FunctionDecl::Static) { 2488 if (!D.isInvalidType()) 2489 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2490 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2491 << SourceRange(D.getIdentifierLoc()); 2492 D.setInvalidType(); 2493 SC = FunctionDecl::None; 2494 } 2495 2496 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2497 if (FTI.TypeQuals != 0) { 2498 if (FTI.TypeQuals & Qualifiers::Const) 2499 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2500 << "const" << SourceRange(D.getIdentifierLoc()); 2501 if (FTI.TypeQuals & Qualifiers::Volatile) 2502 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2503 << "volatile" << SourceRange(D.getIdentifierLoc()); 2504 if (FTI.TypeQuals & Qualifiers::Restrict) 2505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2506 << "restrict" << SourceRange(D.getIdentifierLoc()); 2507 } 2508 2509 // Rebuild the function type "R" without any type qualifiers (in 2510 // case any of the errors above fired) and with "void" as the 2511 // return type, since constructors don't have return types. We 2512 // *always* have to do this, because GetTypeForDeclarator will 2513 // put in a result type of "int" when none was specified. 2514 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2515 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2516 Proto->getNumArgs(), 2517 Proto->isVariadic(), 0); 2518} 2519 2520/// CheckConstructor - Checks a fully-formed constructor for 2521/// well-formedness, issuing any diagnostics required. Returns true if 2522/// the constructor declarator is invalid. 2523void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2524 CXXRecordDecl *ClassDecl 2525 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2526 if (!ClassDecl) 2527 return Constructor->setInvalidDecl(); 2528 2529 // C++ [class.copy]p3: 2530 // A declaration of a constructor for a class X is ill-formed if 2531 // its first parameter is of type (optionally cv-qualified) X and 2532 // either there are no other parameters or else all other 2533 // parameters have default arguments. 2534 if (!Constructor->isInvalidDecl() && 2535 ((Constructor->getNumParams() == 1) || 2536 (Constructor->getNumParams() > 1 && 2537 Constructor->getParamDecl(1)->hasDefaultArg())) && 2538 Constructor->getTemplateSpecializationKind() 2539 != TSK_ImplicitInstantiation) { 2540 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2541 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2542 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2543 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2544 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2545 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 2546 2547 // FIXME: Rather that making the constructor invalid, we should endeavor 2548 // to fix the type. 2549 Constructor->setInvalidDecl(); 2550 } 2551 } 2552 2553 // Notify the class that we've added a constructor. 2554 ClassDecl->addedConstructor(Context, Constructor); 2555} 2556 2557/// CheckDestructor - Checks a fully-formed destructor for well-formedness, 2558/// issuing any diagnostics required. Returns true on error. 2559bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 2560 CXXRecordDecl *RD = Destructor->getParent(); 2561 2562 if (Destructor->isVirtual()) { 2563 SourceLocation Loc; 2564 2565 if (!Destructor->isImplicit()) 2566 Loc = Destructor->getLocation(); 2567 else 2568 Loc = RD->getLocation(); 2569 2570 // If we have a virtual destructor, look up the deallocation function 2571 FunctionDecl *OperatorDelete = 0; 2572 DeclarationName Name = 2573 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2574 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2575 return true; 2576 2577 Destructor->setOperatorDelete(OperatorDelete); 2578 } 2579 2580 return false; 2581} 2582 2583static inline bool 2584FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2585 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2586 FTI.ArgInfo[0].Param && 2587 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2588} 2589 2590/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2591/// the well-formednes of the destructor declarator @p D with type @p 2592/// R. If there are any errors in the declarator, this routine will 2593/// emit diagnostics and set the declarator to invalid. Even if this happens, 2594/// will be updated to reflect a well-formed type for the destructor and 2595/// returned. 2596QualType Sema::CheckDestructorDeclarator(Declarator &D, 2597 FunctionDecl::StorageClass& SC) { 2598 // C++ [class.dtor]p1: 2599 // [...] A typedef-name that names a class is a class-name 2600 // (7.1.3); however, a typedef-name that names a class shall not 2601 // be used as the identifier in the declarator for a destructor 2602 // declaration. 2603 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2604 if (isa<TypedefType>(DeclaratorType)) { 2605 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2606 << DeclaratorType; 2607 D.setInvalidType(); 2608 } 2609 2610 // C++ [class.dtor]p2: 2611 // A destructor is used to destroy objects of its class type. A 2612 // destructor takes no parameters, and no return type can be 2613 // specified for it (not even void). The address of a destructor 2614 // shall not be taken. A destructor shall not be static. A 2615 // destructor can be invoked for a const, volatile or const 2616 // volatile object. A destructor shall not be declared const, 2617 // volatile or const volatile (9.3.2). 2618 if (SC == FunctionDecl::Static) { 2619 if (!D.isInvalidType()) 2620 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2621 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2622 << SourceRange(D.getIdentifierLoc()); 2623 SC = FunctionDecl::None; 2624 D.setInvalidType(); 2625 } 2626 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2627 // Destructors don't have return types, but the parser will 2628 // happily parse something like: 2629 // 2630 // class X { 2631 // float ~X(); 2632 // }; 2633 // 2634 // The return type will be eliminated later. 2635 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2636 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2637 << SourceRange(D.getIdentifierLoc()); 2638 } 2639 2640 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2641 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2642 if (FTI.TypeQuals & Qualifiers::Const) 2643 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2644 << "const" << SourceRange(D.getIdentifierLoc()); 2645 if (FTI.TypeQuals & Qualifiers::Volatile) 2646 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2647 << "volatile" << SourceRange(D.getIdentifierLoc()); 2648 if (FTI.TypeQuals & Qualifiers::Restrict) 2649 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2650 << "restrict" << SourceRange(D.getIdentifierLoc()); 2651 D.setInvalidType(); 2652 } 2653 2654 // Make sure we don't have any parameters. 2655 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2656 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2657 2658 // Delete the parameters. 2659 FTI.freeArgs(); 2660 D.setInvalidType(); 2661 } 2662 2663 // Make sure the destructor isn't variadic. 2664 if (FTI.isVariadic) { 2665 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2666 D.setInvalidType(); 2667 } 2668 2669 // Rebuild the function type "R" without any type qualifiers or 2670 // parameters (in case any of the errors above fired) and with 2671 // "void" as the return type, since destructors don't have return 2672 // types. We *always* have to do this, because GetTypeForDeclarator 2673 // will put in a result type of "int" when none was specified. 2674 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 2675} 2676 2677/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2678/// well-formednes of the conversion function declarator @p D with 2679/// type @p R. If there are any errors in the declarator, this routine 2680/// will emit diagnostics and return true. Otherwise, it will return 2681/// false. Either way, the type @p R will be updated to reflect a 2682/// well-formed type for the conversion operator. 2683void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2684 FunctionDecl::StorageClass& SC) { 2685 // C++ [class.conv.fct]p1: 2686 // Neither parameter types nor return type can be specified. The 2687 // type of a conversion function (8.3.5) is "function taking no 2688 // parameter returning conversion-type-id." 2689 if (SC == FunctionDecl::Static) { 2690 if (!D.isInvalidType()) 2691 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2692 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2693 << SourceRange(D.getIdentifierLoc()); 2694 D.setInvalidType(); 2695 SC = FunctionDecl::None; 2696 } 2697 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2698 // Conversion functions don't have return types, but the parser will 2699 // happily parse something like: 2700 // 2701 // class X { 2702 // float operator bool(); 2703 // }; 2704 // 2705 // The return type will be changed later anyway. 2706 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2707 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2708 << SourceRange(D.getIdentifierLoc()); 2709 } 2710 2711 // Make sure we don't have any parameters. 2712 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 2713 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2714 2715 // Delete the parameters. 2716 D.getTypeObject(0).Fun.freeArgs(); 2717 D.setInvalidType(); 2718 } 2719 2720 // Make sure the conversion function isn't variadic. 2721 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 2722 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2723 D.setInvalidType(); 2724 } 2725 2726 // C++ [class.conv.fct]p4: 2727 // The conversion-type-id shall not represent a function type nor 2728 // an array type. 2729 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 2730 if (ConvType->isArrayType()) { 2731 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2732 ConvType = Context.getPointerType(ConvType); 2733 D.setInvalidType(); 2734 } else if (ConvType->isFunctionType()) { 2735 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2736 ConvType = Context.getPointerType(ConvType); 2737 D.setInvalidType(); 2738 } 2739 2740 // Rebuild the function type "R" without any parameters (in case any 2741 // of the errors above fired) and with the conversion type as the 2742 // return type. 2743 R = Context.getFunctionType(ConvType, 0, 0, false, 2744 R->getAs<FunctionProtoType>()->getTypeQuals()); 2745 2746 // C++0x explicit conversion operators. 2747 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2748 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2749 diag::warn_explicit_conversion_functions) 2750 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2751} 2752 2753/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2754/// the declaration of the given C++ conversion function. This routine 2755/// is responsible for recording the conversion function in the C++ 2756/// class, if possible. 2757Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2758 assert(Conversion && "Expected to receive a conversion function declaration"); 2759 2760 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2761 2762 // Make sure we aren't redeclaring the conversion function. 2763 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2764 2765 // C++ [class.conv.fct]p1: 2766 // [...] A conversion function is never used to convert a 2767 // (possibly cv-qualified) object to the (possibly cv-qualified) 2768 // same object type (or a reference to it), to a (possibly 2769 // cv-qualified) base class of that type (or a reference to it), 2770 // or to (possibly cv-qualified) void. 2771 // FIXME: Suppress this warning if the conversion function ends up being a 2772 // virtual function that overrides a virtual function in a base class. 2773 QualType ClassType 2774 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2775 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2776 ConvType = ConvTypeRef->getPointeeType(); 2777 if (ConvType->isRecordType()) { 2778 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2779 if (ConvType == ClassType) 2780 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2781 << ClassType; 2782 else if (IsDerivedFrom(ClassType, ConvType)) 2783 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2784 << ClassType << ConvType; 2785 } else if (ConvType->isVoidType()) { 2786 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2787 << ClassType << ConvType; 2788 } 2789 2790 if (Conversion->getPrimaryTemplate()) { 2791 // ignore specializations 2792 } else if (Conversion->getPreviousDeclaration()) { 2793 if (FunctionTemplateDecl *ConversionTemplate 2794 = Conversion->getDescribedFunctionTemplate()) { 2795 if (ClassDecl->replaceConversion( 2796 ConversionTemplate->getPreviousDeclaration(), 2797 ConversionTemplate)) 2798 return DeclPtrTy::make(ConversionTemplate); 2799 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 2800 Conversion)) 2801 return DeclPtrTy::make(Conversion); 2802 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2803 } else if (FunctionTemplateDecl *ConversionTemplate 2804 = Conversion->getDescribedFunctionTemplate()) 2805 ClassDecl->addConversionFunction(ConversionTemplate); 2806 else 2807 ClassDecl->addConversionFunction(Conversion); 2808 2809 return DeclPtrTy::make(Conversion); 2810} 2811 2812//===----------------------------------------------------------------------===// 2813// Namespace Handling 2814//===----------------------------------------------------------------------===// 2815 2816/// ActOnStartNamespaceDef - This is called at the start of a namespace 2817/// definition. 2818Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2819 SourceLocation IdentLoc, 2820 IdentifierInfo *II, 2821 SourceLocation LBrace) { 2822 NamespaceDecl *Namespc = 2823 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2824 Namespc->setLBracLoc(LBrace); 2825 2826 Scope *DeclRegionScope = NamespcScope->getParent(); 2827 2828 if (II) { 2829 // C++ [namespace.def]p2: 2830 // The identifier in an original-namespace-definition shall not have been 2831 // previously defined in the declarative region in which the 2832 // original-namespace-definition appears. The identifier in an 2833 // original-namespace-definition is the name of the namespace. Subsequently 2834 // in that declarative region, it is treated as an original-namespace-name. 2835 2836 NamedDecl *PrevDecl 2837 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, 2838 ForRedeclaration); 2839 2840 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2841 // This is an extended namespace definition. 2842 // Attach this namespace decl to the chain of extended namespace 2843 // definitions. 2844 OrigNS->setNextNamespace(Namespc); 2845 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2846 2847 // Remove the previous declaration from the scope. 2848 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2849 IdResolver.RemoveDecl(OrigNS); 2850 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2851 } 2852 } else if (PrevDecl) { 2853 // This is an invalid name redefinition. 2854 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2855 << Namespc->getDeclName(); 2856 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2857 Namespc->setInvalidDecl(); 2858 // Continue on to push Namespc as current DeclContext and return it. 2859 } else if (II->isStr("std") && 2860 CurContext->getLookupContext()->isTranslationUnit()) { 2861 // This is the first "real" definition of the namespace "std", so update 2862 // our cache of the "std" namespace to point at this definition. 2863 if (StdNamespace) { 2864 // We had already defined a dummy namespace "std". Link this new 2865 // namespace definition to the dummy namespace "std". 2866 StdNamespace->setNextNamespace(Namespc); 2867 StdNamespace->setLocation(IdentLoc); 2868 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 2869 } 2870 2871 // Make our StdNamespace cache point at the first real definition of the 2872 // "std" namespace. 2873 StdNamespace = Namespc; 2874 } 2875 2876 PushOnScopeChains(Namespc, DeclRegionScope); 2877 } else { 2878 // Anonymous namespaces. 2879 assert(Namespc->isAnonymousNamespace()); 2880 CurContext->addDecl(Namespc); 2881 2882 // Link the anonymous namespace into its parent. 2883 NamespaceDecl *PrevDecl; 2884 DeclContext *Parent = CurContext->getLookupContext(); 2885 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 2886 PrevDecl = TU->getAnonymousNamespace(); 2887 TU->setAnonymousNamespace(Namespc); 2888 } else { 2889 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 2890 PrevDecl = ND->getAnonymousNamespace(); 2891 ND->setAnonymousNamespace(Namespc); 2892 } 2893 2894 // Link the anonymous namespace with its previous declaration. 2895 if (PrevDecl) { 2896 assert(PrevDecl->isAnonymousNamespace()); 2897 assert(!PrevDecl->getNextNamespace()); 2898 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 2899 PrevDecl->setNextNamespace(Namespc); 2900 } 2901 2902 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 2903 // behaves as if it were replaced by 2904 // namespace unique { /* empty body */ } 2905 // using namespace unique; 2906 // namespace unique { namespace-body } 2907 // where all occurrences of 'unique' in a translation unit are 2908 // replaced by the same identifier and this identifier differs 2909 // from all other identifiers in the entire program. 2910 2911 // We just create the namespace with an empty name and then add an 2912 // implicit using declaration, just like the standard suggests. 2913 // 2914 // CodeGen enforces the "universally unique" aspect by giving all 2915 // declarations semantically contained within an anonymous 2916 // namespace internal linkage. 2917 2918 if (!PrevDecl) { 2919 UsingDirectiveDecl* UD 2920 = UsingDirectiveDecl::Create(Context, CurContext, 2921 /* 'using' */ LBrace, 2922 /* 'namespace' */ SourceLocation(), 2923 /* qualifier */ SourceRange(), 2924 /* NNS */ NULL, 2925 /* identifier */ SourceLocation(), 2926 Namespc, 2927 /* Ancestor */ CurContext); 2928 UD->setImplicit(); 2929 CurContext->addDecl(UD); 2930 } 2931 } 2932 2933 // Although we could have an invalid decl (i.e. the namespace name is a 2934 // redefinition), push it as current DeclContext and try to continue parsing. 2935 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2936 // for the namespace has the declarations that showed up in that particular 2937 // namespace definition. 2938 PushDeclContext(NamespcScope, Namespc); 2939 return DeclPtrTy::make(Namespc); 2940} 2941 2942/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2943/// is a namespace alias, returns the namespace it points to. 2944static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2945 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2946 return AD->getNamespace(); 2947 return dyn_cast_or_null<NamespaceDecl>(D); 2948} 2949 2950/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2951/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2952void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2953 Decl *Dcl = D.getAs<Decl>(); 2954 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2955 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2956 Namespc->setRBracLoc(RBrace); 2957 PopDeclContext(); 2958} 2959 2960Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2961 SourceLocation UsingLoc, 2962 SourceLocation NamespcLoc, 2963 const CXXScopeSpec &SS, 2964 SourceLocation IdentLoc, 2965 IdentifierInfo *NamespcName, 2966 AttributeList *AttrList) { 2967 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2968 assert(NamespcName && "Invalid NamespcName."); 2969 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2970 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2971 2972 UsingDirectiveDecl *UDir = 0; 2973 2974 // Lookup namespace name. 2975 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 2976 LookupParsedName(R, S, &SS); 2977 if (R.isAmbiguous()) 2978 return DeclPtrTy(); 2979 2980 if (!R.empty()) { 2981 NamedDecl *Named = R.getFoundDecl(); 2982 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 2983 && "expected namespace decl"); 2984 // C++ [namespace.udir]p1: 2985 // A using-directive specifies that the names in the nominated 2986 // namespace can be used in the scope in which the 2987 // using-directive appears after the using-directive. During 2988 // unqualified name lookup (3.4.1), the names appear as if they 2989 // were declared in the nearest enclosing namespace which 2990 // contains both the using-directive and the nominated 2991 // namespace. [Note: in this context, "contains" means "contains 2992 // directly or indirectly". ] 2993 2994 // Find enclosing context containing both using-directive and 2995 // nominated namespace. 2996 NamespaceDecl *NS = getNamespaceDecl(Named); 2997 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2998 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2999 CommonAncestor = CommonAncestor->getParent(); 3000 3001 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3002 SS.getRange(), 3003 (NestedNameSpecifier *)SS.getScopeRep(), 3004 IdentLoc, Named, CommonAncestor); 3005 PushUsingDirective(S, UDir); 3006 } else { 3007 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3008 } 3009 3010 // FIXME: We ignore attributes for now. 3011 delete AttrList; 3012 return DeclPtrTy::make(UDir); 3013} 3014 3015void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3016 // If scope has associated entity, then using directive is at namespace 3017 // or translation unit scope. We add UsingDirectiveDecls, into 3018 // it's lookup structure. 3019 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3020 Ctx->addDecl(UDir); 3021 else 3022 // Otherwise it is block-sope. using-directives will affect lookup 3023 // only to the end of scope. 3024 S->PushUsingDirective(DeclPtrTy::make(UDir)); 3025} 3026 3027 3028Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 3029 AccessSpecifier AS, 3030 bool HasUsingKeyword, 3031 SourceLocation UsingLoc, 3032 const CXXScopeSpec &SS, 3033 UnqualifiedId &Name, 3034 AttributeList *AttrList, 3035 bool IsTypeName, 3036 SourceLocation TypenameLoc) { 3037 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3038 3039 switch (Name.getKind()) { 3040 case UnqualifiedId::IK_Identifier: 3041 case UnqualifiedId::IK_OperatorFunctionId: 3042 case UnqualifiedId::IK_LiteralOperatorId: 3043 case UnqualifiedId::IK_ConversionFunctionId: 3044 break; 3045 3046 case UnqualifiedId::IK_ConstructorName: 3047 case UnqualifiedId::IK_ConstructorTemplateId: 3048 // C++0x inherited constructors. 3049 if (getLangOptions().CPlusPlus0x) break; 3050 3051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3052 << SS.getRange(); 3053 return DeclPtrTy(); 3054 3055 case UnqualifiedId::IK_DestructorName: 3056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3057 << SS.getRange(); 3058 return DeclPtrTy(); 3059 3060 case UnqualifiedId::IK_TemplateId: 3061 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3062 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3063 return DeclPtrTy(); 3064 } 3065 3066 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 3067 if (!TargetName) 3068 return DeclPtrTy(); 3069 3070 // Warn about using declarations. 3071 // TODO: store that the declaration was written without 'using' and 3072 // talk about access decls instead of using decls in the 3073 // diagnostics. 3074 if (!HasUsingKeyword) { 3075 UsingLoc = Name.getSourceRange().getBegin(); 3076 3077 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3078 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(), 3079 "using "); 3080 } 3081 3082 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3083 Name.getSourceRange().getBegin(), 3084 TargetName, AttrList, 3085 /* IsInstantiation */ false, 3086 IsTypeName, TypenameLoc); 3087 if (UD) 3088 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3089 3090 return DeclPtrTy::make(UD); 3091} 3092 3093/// Determines whether to create a using shadow decl for a particular 3094/// decl, given the set of decls existing prior to this using lookup. 3095bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3096 const LookupResult &Previous) { 3097 // Diagnose finding a decl which is not from a base class of the 3098 // current class. We do this now because there are cases where this 3099 // function will silently decide not to build a shadow decl, which 3100 // will pre-empt further diagnostics. 3101 // 3102 // We don't need to do this in C++0x because we do the check once on 3103 // the qualifier. 3104 // 3105 // FIXME: diagnose the following if we care enough: 3106 // struct A { int foo; }; 3107 // struct B : A { using A::foo; }; 3108 // template <class T> struct C : A {}; 3109 // template <class T> struct D : C<T> { using B::foo; } // <--- 3110 // This is invalid (during instantiation) in C++03 because B::foo 3111 // resolves to the using decl in B, which is not a base class of D<T>. 3112 // We can't diagnose it immediately because C<T> is an unknown 3113 // specialization. The UsingShadowDecl in D<T> then points directly 3114 // to A::foo, which will look well-formed when we instantiate. 3115 // The right solution is to not collapse the shadow-decl chain. 3116 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3117 DeclContext *OrigDC = Orig->getDeclContext(); 3118 3119 // Handle enums and anonymous structs. 3120 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3121 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3122 while (OrigRec->isAnonymousStructOrUnion()) 3123 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3124 3125 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3126 if (OrigDC == CurContext) { 3127 Diag(Using->getLocation(), 3128 diag::err_using_decl_nested_name_specifier_is_current_class) 3129 << Using->getNestedNameRange(); 3130 Diag(Orig->getLocation(), diag::note_using_decl_target); 3131 return true; 3132 } 3133 3134 Diag(Using->getNestedNameRange().getBegin(), 3135 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3136 << Using->getTargetNestedNameDecl() 3137 << cast<CXXRecordDecl>(CurContext) 3138 << Using->getNestedNameRange(); 3139 Diag(Orig->getLocation(), diag::note_using_decl_target); 3140 return true; 3141 } 3142 } 3143 3144 if (Previous.empty()) return false; 3145 3146 NamedDecl *Target = Orig; 3147 if (isa<UsingShadowDecl>(Target)) 3148 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3149 3150 // If the target happens to be one of the previous declarations, we 3151 // don't have a conflict. 3152 // 3153 // FIXME: but we might be increasing its access, in which case we 3154 // should redeclare it. 3155 NamedDecl *NonTag = 0, *Tag = 0; 3156 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3157 I != E; ++I) { 3158 NamedDecl *D = (*I)->getUnderlyingDecl(); 3159 if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 3160 return false; 3161 3162 (isa<TagDecl>(D) ? Tag : NonTag) = D; 3163 } 3164 3165 if (Target->isFunctionOrFunctionTemplate()) { 3166 FunctionDecl *FD; 3167 if (isa<FunctionTemplateDecl>(Target)) 3168 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3169 else 3170 FD = cast<FunctionDecl>(Target); 3171 3172 NamedDecl *OldDecl = 0; 3173 switch (CheckOverload(FD, Previous, OldDecl)) { 3174 case Ovl_Overload: 3175 return false; 3176 3177 case Ovl_NonFunction: 3178 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3179 break; 3180 3181 // We found a decl with the exact signature. 3182 case Ovl_Match: 3183 if (isa<UsingShadowDecl>(OldDecl)) { 3184 // Silently ignore the possible conflict. 3185 return false; 3186 } 3187 3188 // If we're in a record, we want to hide the target, so we 3189 // return true (without a diagnostic) to tell the caller not to 3190 // build a shadow decl. 3191 if (CurContext->isRecord()) 3192 return true; 3193 3194 // If we're not in a record, this is an error. 3195 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3196 break; 3197 } 3198 3199 Diag(Target->getLocation(), diag::note_using_decl_target); 3200 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3201 return true; 3202 } 3203 3204 // Target is not a function. 3205 3206 if (isa<TagDecl>(Target)) { 3207 // No conflict between a tag and a non-tag. 3208 if (!Tag) return false; 3209 3210 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3211 Diag(Target->getLocation(), diag::note_using_decl_target); 3212 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3213 return true; 3214 } 3215 3216 // No conflict between a tag and a non-tag. 3217 if (!NonTag) return false; 3218 3219 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3220 Diag(Target->getLocation(), diag::note_using_decl_target); 3221 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3222 return true; 3223} 3224 3225/// Builds a shadow declaration corresponding to a 'using' declaration. 3226UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3227 UsingDecl *UD, 3228 NamedDecl *Orig) { 3229 3230 // If we resolved to another shadow declaration, just coalesce them. 3231 NamedDecl *Target = Orig; 3232 if (isa<UsingShadowDecl>(Target)) { 3233 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3234 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3235 } 3236 3237 UsingShadowDecl *Shadow 3238 = UsingShadowDecl::Create(Context, CurContext, 3239 UD->getLocation(), UD, Target); 3240 UD->addShadowDecl(Shadow); 3241 3242 if (S) 3243 PushOnScopeChains(Shadow, S); 3244 else 3245 CurContext->addDecl(Shadow); 3246 Shadow->setAccess(UD->getAccess()); 3247 3248 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3249 Shadow->setInvalidDecl(); 3250 3251 return Shadow; 3252} 3253 3254/// Hides a using shadow declaration. This is required by the current 3255/// using-decl implementation when a resolvable using declaration in a 3256/// class is followed by a declaration which would hide or override 3257/// one or more of the using decl's targets; for example: 3258/// 3259/// struct Base { void foo(int); }; 3260/// struct Derived : Base { 3261/// using Base::foo; 3262/// void foo(int); 3263/// }; 3264/// 3265/// The governing language is C++03 [namespace.udecl]p12: 3266/// 3267/// When a using-declaration brings names from a base class into a 3268/// derived class scope, member functions in the derived class 3269/// override and/or hide member functions with the same name and 3270/// parameter types in a base class (rather than conflicting). 3271/// 3272/// There are two ways to implement this: 3273/// (1) optimistically create shadow decls when they're not hidden 3274/// by existing declarations, or 3275/// (2) don't create any shadow decls (or at least don't make them 3276/// visible) until we've fully parsed/instantiated the class. 3277/// The problem with (1) is that we might have to retroactively remove 3278/// a shadow decl, which requires several O(n) operations because the 3279/// decl structures are (very reasonably) not designed for removal. 3280/// (2) avoids this but is very fiddly and phase-dependent. 3281void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3282 // Remove it from the DeclContext... 3283 Shadow->getDeclContext()->removeDecl(Shadow); 3284 3285 // ...and the scope, if applicable... 3286 if (S) { 3287 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 3288 IdResolver.RemoveDecl(Shadow); 3289 } 3290 3291 // ...and the using decl. 3292 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3293 3294 // TODO: complain somehow if Shadow was used. It shouldn't 3295 // be possible for this to happen, because 3296} 3297 3298/// Builds a using declaration. 3299/// 3300/// \param IsInstantiation - Whether this call arises from an 3301/// instantiation of an unresolved using declaration. We treat 3302/// the lookup differently for these declarations. 3303NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3304 SourceLocation UsingLoc, 3305 const CXXScopeSpec &SS, 3306 SourceLocation IdentLoc, 3307 DeclarationName Name, 3308 AttributeList *AttrList, 3309 bool IsInstantiation, 3310 bool IsTypeName, 3311 SourceLocation TypenameLoc) { 3312 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3313 assert(IdentLoc.isValid() && "Invalid TargetName location."); 3314 3315 // FIXME: We ignore attributes for now. 3316 delete AttrList; 3317 3318 if (SS.isEmpty()) { 3319 Diag(IdentLoc, diag::err_using_requires_qualname); 3320 return 0; 3321 } 3322 3323 // Do the redeclaration lookup in the current scope. 3324 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 3325 ForRedeclaration); 3326 Previous.setHideTags(false); 3327 if (S) { 3328 LookupName(Previous, S); 3329 3330 // It is really dumb that we have to do this. 3331 LookupResult::Filter F = Previous.makeFilter(); 3332 while (F.hasNext()) { 3333 NamedDecl *D = F.next(); 3334 if (!isDeclInScope(D, CurContext, S)) 3335 F.erase(); 3336 } 3337 F.done(); 3338 } else { 3339 assert(IsInstantiation && "no scope in non-instantiation"); 3340 assert(CurContext->isRecord() && "scope not record in instantiation"); 3341 LookupQualifiedName(Previous, CurContext); 3342 } 3343 3344 NestedNameSpecifier *NNS = 3345 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3346 3347 // Check for invalid redeclarations. 3348 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3349 return 0; 3350 3351 // Check for bad qualifiers. 3352 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3353 return 0; 3354 3355 DeclContext *LookupContext = computeDeclContext(SS); 3356 NamedDecl *D; 3357 if (!LookupContext) { 3358 if (IsTypeName) { 3359 // FIXME: not all declaration name kinds are legal here 3360 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3361 UsingLoc, TypenameLoc, 3362 SS.getRange(), NNS, 3363 IdentLoc, Name); 3364 } else { 3365 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3366 UsingLoc, SS.getRange(), NNS, 3367 IdentLoc, Name); 3368 } 3369 } else { 3370 D = UsingDecl::Create(Context, CurContext, IdentLoc, 3371 SS.getRange(), UsingLoc, NNS, Name, 3372 IsTypeName); 3373 } 3374 D->setAccess(AS); 3375 CurContext->addDecl(D); 3376 3377 if (!LookupContext) return D; 3378 UsingDecl *UD = cast<UsingDecl>(D); 3379 3380 if (RequireCompleteDeclContext(SS)) { 3381 UD->setInvalidDecl(); 3382 return UD; 3383 } 3384 3385 // Look up the target name. 3386 3387 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 3388 3389 // Unlike most lookups, we don't always want to hide tag 3390 // declarations: tag names are visible through the using declaration 3391 // even if hidden by ordinary names, *except* in a dependent context 3392 // where it's important for the sanity of two-phase lookup. 3393 if (!IsInstantiation) 3394 R.setHideTags(false); 3395 3396 LookupQualifiedName(R, LookupContext); 3397 3398 if (R.empty()) { 3399 Diag(IdentLoc, diag::err_no_member) 3400 << Name << LookupContext << SS.getRange(); 3401 UD->setInvalidDecl(); 3402 return UD; 3403 } 3404 3405 if (R.isAmbiguous()) { 3406 UD->setInvalidDecl(); 3407 return UD; 3408 } 3409 3410 if (IsTypeName) { 3411 // If we asked for a typename and got a non-type decl, error out. 3412 if (!R.getAsSingle<TypeDecl>()) { 3413 Diag(IdentLoc, diag::err_using_typename_non_type); 3414 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3415 Diag((*I)->getUnderlyingDecl()->getLocation(), 3416 diag::note_using_decl_target); 3417 UD->setInvalidDecl(); 3418 return UD; 3419 } 3420 } else { 3421 // If we asked for a non-typename and we got a type, error out, 3422 // but only if this is an instantiation of an unresolved using 3423 // decl. Otherwise just silently find the type name. 3424 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3425 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3426 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3427 UD->setInvalidDecl(); 3428 return UD; 3429 } 3430 } 3431 3432 // C++0x N2914 [namespace.udecl]p6: 3433 // A using-declaration shall not name a namespace. 3434 if (R.getAsSingle<NamespaceDecl>()) { 3435 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3436 << SS.getRange(); 3437 UD->setInvalidDecl(); 3438 return UD; 3439 } 3440 3441 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3442 if (!CheckUsingShadowDecl(UD, *I, Previous)) 3443 BuildUsingShadowDecl(S, UD, *I); 3444 } 3445 3446 return UD; 3447} 3448 3449/// Checks that the given using declaration is not an invalid 3450/// redeclaration. Note that this is checking only for the using decl 3451/// itself, not for any ill-formedness among the UsingShadowDecls. 3452bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3453 bool isTypeName, 3454 const CXXScopeSpec &SS, 3455 SourceLocation NameLoc, 3456 const LookupResult &Prev) { 3457 // C++03 [namespace.udecl]p8: 3458 // C++0x [namespace.udecl]p10: 3459 // A using-declaration is a declaration and can therefore be used 3460 // repeatedly where (and only where) multiple declarations are 3461 // allowed. 3462 // That's only in file contexts. 3463 if (CurContext->getLookupContext()->isFileContext()) 3464 return false; 3465 3466 NestedNameSpecifier *Qual 3467 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3468 3469 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3470 NamedDecl *D = *I; 3471 3472 bool DTypename; 3473 NestedNameSpecifier *DQual; 3474 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3475 DTypename = UD->isTypeName(); 3476 DQual = UD->getTargetNestedNameDecl(); 3477 } else if (UnresolvedUsingValueDecl *UD 3478 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3479 DTypename = false; 3480 DQual = UD->getTargetNestedNameSpecifier(); 3481 } else if (UnresolvedUsingTypenameDecl *UD 3482 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3483 DTypename = true; 3484 DQual = UD->getTargetNestedNameSpecifier(); 3485 } else continue; 3486 3487 // using decls differ if one says 'typename' and the other doesn't. 3488 // FIXME: non-dependent using decls? 3489 if (isTypeName != DTypename) continue; 3490 3491 // using decls differ if they name different scopes (but note that 3492 // template instantiation can cause this check to trigger when it 3493 // didn't before instantiation). 3494 if (Context.getCanonicalNestedNameSpecifier(Qual) != 3495 Context.getCanonicalNestedNameSpecifier(DQual)) 3496 continue; 3497 3498 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 3499 Diag(D->getLocation(), diag::note_using_decl) << 1; 3500 return true; 3501 } 3502 3503 return false; 3504} 3505 3506 3507/// Checks that the given nested-name qualifier used in a using decl 3508/// in the current context is appropriately related to the current 3509/// scope. If an error is found, diagnoses it and returns true. 3510bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 3511 const CXXScopeSpec &SS, 3512 SourceLocation NameLoc) { 3513 DeclContext *NamedContext = computeDeclContext(SS); 3514 3515 if (!CurContext->isRecord()) { 3516 // C++03 [namespace.udecl]p3: 3517 // C++0x [namespace.udecl]p8: 3518 // A using-declaration for a class member shall be a member-declaration. 3519 3520 // If we weren't able to compute a valid scope, it must be a 3521 // dependent class scope. 3522 if (!NamedContext || NamedContext->isRecord()) { 3523 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 3524 << SS.getRange(); 3525 return true; 3526 } 3527 3528 // Otherwise, everything is known to be fine. 3529 return false; 3530 } 3531 3532 // The current scope is a record. 3533 3534 // If the named context is dependent, we can't decide much. 3535 if (!NamedContext) { 3536 // FIXME: in C++0x, we can diagnose if we can prove that the 3537 // nested-name-specifier does not refer to a base class, which is 3538 // still possible in some cases. 3539 3540 // Otherwise we have to conservatively report that things might be 3541 // okay. 3542 return false; 3543 } 3544 3545 if (!NamedContext->isRecord()) { 3546 // Ideally this would point at the last name in the specifier, 3547 // but we don't have that level of source info. 3548 Diag(SS.getRange().getBegin(), 3549 diag::err_using_decl_nested_name_specifier_is_not_class) 3550 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 3551 return true; 3552 } 3553 3554 if (getLangOptions().CPlusPlus0x) { 3555 // C++0x [namespace.udecl]p3: 3556 // In a using-declaration used as a member-declaration, the 3557 // nested-name-specifier shall name a base class of the class 3558 // being defined. 3559 3560 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 3561 cast<CXXRecordDecl>(NamedContext))) { 3562 if (CurContext == NamedContext) { 3563 Diag(NameLoc, 3564 diag::err_using_decl_nested_name_specifier_is_current_class) 3565 << SS.getRange(); 3566 return true; 3567 } 3568 3569 Diag(SS.getRange().getBegin(), 3570 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3571 << (NestedNameSpecifier*) SS.getScopeRep() 3572 << cast<CXXRecordDecl>(CurContext) 3573 << SS.getRange(); 3574 return true; 3575 } 3576 3577 return false; 3578 } 3579 3580 // C++03 [namespace.udecl]p4: 3581 // A using-declaration used as a member-declaration shall refer 3582 // to a member of a base class of the class being defined [etc.]. 3583 3584 // Salient point: SS doesn't have to name a base class as long as 3585 // lookup only finds members from base classes. Therefore we can 3586 // diagnose here only if we can prove that that can't happen, 3587 // i.e. if the class hierarchies provably don't intersect. 3588 3589 // TODO: it would be nice if "definitely valid" results were cached 3590 // in the UsingDecl and UsingShadowDecl so that these checks didn't 3591 // need to be repeated. 3592 3593 struct UserData { 3594 llvm::DenseSet<const CXXRecordDecl*> Bases; 3595 3596 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 3597 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3598 Data->Bases.insert(Base); 3599 return true; 3600 } 3601 3602 bool hasDependentBases(const CXXRecordDecl *Class) { 3603 return !Class->forallBases(collect, this); 3604 } 3605 3606 /// Returns true if the base is dependent or is one of the 3607 /// accumulated base classes. 3608 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 3609 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 3610 return !Data->Bases.count(Base); 3611 } 3612 3613 bool mightShareBases(const CXXRecordDecl *Class) { 3614 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 3615 } 3616 }; 3617 3618 UserData Data; 3619 3620 // Returns false if we find a dependent base. 3621 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 3622 return false; 3623 3624 // Returns false if the class has a dependent base or if it or one 3625 // of its bases is present in the base set of the current context. 3626 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 3627 return false; 3628 3629 Diag(SS.getRange().getBegin(), 3630 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3631 << (NestedNameSpecifier*) SS.getScopeRep() 3632 << cast<CXXRecordDecl>(CurContext) 3633 << SS.getRange(); 3634 3635 return true; 3636} 3637 3638Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 3639 SourceLocation NamespaceLoc, 3640 SourceLocation AliasLoc, 3641 IdentifierInfo *Alias, 3642 const CXXScopeSpec &SS, 3643 SourceLocation IdentLoc, 3644 IdentifierInfo *Ident) { 3645 3646 // Lookup the namespace name. 3647 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 3648 LookupParsedName(R, S, &SS); 3649 3650 // Check if we have a previous declaration with the same name. 3651 if (NamedDecl *PrevDecl 3652 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) { 3653 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 3654 // We already have an alias with the same name that points to the same 3655 // namespace, so don't create a new one. 3656 if (!R.isAmbiguous() && !R.empty() && 3657 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl())) 3658 return DeclPtrTy(); 3659 } 3660 3661 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 3662 diag::err_redefinition_different_kind; 3663 Diag(AliasLoc, DiagID) << Alias; 3664 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3665 return DeclPtrTy(); 3666 } 3667 3668 if (R.isAmbiguous()) 3669 return DeclPtrTy(); 3670 3671 if (R.empty()) { 3672 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 3673 return DeclPtrTy(); 3674 } 3675 3676 NamespaceAliasDecl *AliasDecl = 3677 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 3678 Alias, SS.getRange(), 3679 (NestedNameSpecifier *)SS.getScopeRep(), 3680 IdentLoc, R.getFoundDecl()); 3681 3682 CurContext->addDecl(AliasDecl); 3683 return DeclPtrTy::make(AliasDecl); 3684} 3685 3686void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3687 CXXConstructorDecl *Constructor) { 3688 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 3689 !Constructor->isUsed()) && 3690 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 3691 3692 CXXRecordDecl *ClassDecl 3693 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 3694 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 3695 3696 DeclContext *PreviousContext = CurContext; 3697 CurContext = Constructor; 3698 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) { 3699 Diag(CurrentLocation, diag::note_member_synthesized_at) 3700 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 3701 Constructor->setInvalidDecl(); 3702 } else { 3703 Constructor->setUsed(); 3704 } 3705 CurContext = PreviousContext; 3706} 3707 3708void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 3709 CXXDestructorDecl *Destructor) { 3710 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 3711 "DefineImplicitDestructor - call it for implicit default dtor"); 3712 CXXRecordDecl *ClassDecl = Destructor->getParent(); 3713 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 3714 3715 DeclContext *PreviousContext = CurContext; 3716 CurContext = Destructor; 3717 3718 // C++ [class.dtor] p5 3719 // Before the implicitly-declared default destructor for a class is 3720 // implicitly defined, all the implicitly-declared default destructors 3721 // for its base class and its non-static data members shall have been 3722 // implicitly defined. 3723 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3724 E = ClassDecl->bases_end(); Base != E; ++Base) { 3725 CXXRecordDecl *BaseClassDecl 3726 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3727 if (!BaseClassDecl->hasTrivialDestructor()) { 3728 if (CXXDestructorDecl *BaseDtor = 3729 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 3730 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 3731 else 3732 assert(false && 3733 "DefineImplicitDestructor - missing dtor in a base class"); 3734 } 3735 } 3736 3737 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3738 E = ClassDecl->field_end(); Field != E; ++Field) { 3739 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3740 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3741 FieldType = Array->getElementType(); 3742 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3743 CXXRecordDecl *FieldClassDecl 3744 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3745 if (!FieldClassDecl->hasTrivialDestructor()) { 3746 if (CXXDestructorDecl *FieldDtor = 3747 const_cast<CXXDestructorDecl*>( 3748 FieldClassDecl->getDestructor(Context))) 3749 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 3750 else 3751 assert(false && 3752 "DefineImplicitDestructor - missing dtor in class of a data member"); 3753 } 3754 } 3755 } 3756 3757 // FIXME: If CheckDestructor fails, we should emit a note about where the 3758 // implicit destructor was needed. 3759 if (CheckDestructor(Destructor)) { 3760 Diag(CurrentLocation, diag::note_member_synthesized_at) 3761 << CXXDestructor << Context.getTagDeclType(ClassDecl); 3762 3763 Destructor->setInvalidDecl(); 3764 CurContext = PreviousContext; 3765 3766 return; 3767 } 3768 CurContext = PreviousContext; 3769 3770 Destructor->setUsed(); 3771} 3772 3773void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 3774 CXXMethodDecl *MethodDecl) { 3775 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 3776 MethodDecl->getOverloadedOperator() == OO_Equal && 3777 !MethodDecl->isUsed()) && 3778 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 3779 3780 CXXRecordDecl *ClassDecl 3781 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 3782 3783 DeclContext *PreviousContext = CurContext; 3784 CurContext = MethodDecl; 3785 3786 // C++[class.copy] p12 3787 // Before the implicitly-declared copy assignment operator for a class is 3788 // implicitly defined, all implicitly-declared copy assignment operators 3789 // for its direct base classes and its nonstatic data members shall have 3790 // been implicitly defined. 3791 bool err = false; 3792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3793 E = ClassDecl->bases_end(); Base != E; ++Base) { 3794 CXXRecordDecl *BaseClassDecl 3795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3796 if (CXXMethodDecl *BaseAssignOpMethod = 3797 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 3798 BaseClassDecl)) 3799 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 3800 } 3801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3802 E = ClassDecl->field_end(); Field != E; ++Field) { 3803 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3804 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3805 FieldType = Array->getElementType(); 3806 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3807 CXXRecordDecl *FieldClassDecl 3808 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3809 if (CXXMethodDecl *FieldAssignOpMethod = 3810 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0), 3811 FieldClassDecl)) 3812 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 3813 } else if (FieldType->isReferenceType()) { 3814 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3815 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 3816 Diag(Field->getLocation(), diag::note_declared_at); 3817 Diag(CurrentLocation, diag::note_first_required_here); 3818 err = true; 3819 } else if (FieldType.isConstQualified()) { 3820 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 3821 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 3822 Diag(Field->getLocation(), diag::note_declared_at); 3823 Diag(CurrentLocation, diag::note_first_required_here); 3824 err = true; 3825 } 3826 } 3827 if (!err) 3828 MethodDecl->setUsed(); 3829 3830 CurContext = PreviousContext; 3831} 3832 3833CXXMethodDecl * 3834Sema::getAssignOperatorMethod(SourceLocation CurrentLocation, 3835 ParmVarDecl *ParmDecl, 3836 CXXRecordDecl *ClassDecl) { 3837 QualType LHSType = Context.getTypeDeclType(ClassDecl); 3838 QualType RHSType(LHSType); 3839 // If class's assignment operator argument is const/volatile qualified, 3840 // look for operator = (const/volatile B&). Otherwise, look for 3841 // operator = (B&). 3842 RHSType = Context.getCVRQualifiedType(RHSType, 3843 ParmDecl->getType().getCVRQualifiers()); 3844 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 3845 LHSType, 3846 SourceLocation())); 3847 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 3848 RHSType, 3849 CurrentLocation)); 3850 Expr *Args[2] = { &*LHS, &*RHS }; 3851 OverloadCandidateSet CandidateSet; 3852 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 3853 CandidateSet); 3854 OverloadCandidateSet::iterator Best; 3855 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success) 3856 return cast<CXXMethodDecl>(Best->Function); 3857 assert(false && 3858 "getAssignOperatorMethod - copy assignment operator method not found"); 3859 return 0; 3860} 3861 3862void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3863 CXXConstructorDecl *CopyConstructor, 3864 unsigned TypeQuals) { 3865 assert((CopyConstructor->isImplicit() && 3866 CopyConstructor->isCopyConstructor(TypeQuals) && 3867 !CopyConstructor->isUsed()) && 3868 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 3869 3870 CXXRecordDecl *ClassDecl 3871 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 3872 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 3873 3874 DeclContext *PreviousContext = CurContext; 3875 CurContext = CopyConstructor; 3876 3877 // C++ [class.copy] p209 3878 // Before the implicitly-declared copy constructor for a class is 3879 // implicitly defined, all the implicitly-declared copy constructors 3880 // for its base class and its non-static data members shall have been 3881 // implicitly defined. 3882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 3883 Base != ClassDecl->bases_end(); ++Base) { 3884 CXXRecordDecl *BaseClassDecl 3885 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3886 if (CXXConstructorDecl *BaseCopyCtor = 3887 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 3888 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 3889 } 3890 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3891 FieldEnd = ClassDecl->field_end(); 3892 Field != FieldEnd; ++Field) { 3893 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 3894 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 3895 FieldType = Array->getElementType(); 3896 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 3897 CXXRecordDecl *FieldClassDecl 3898 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 3899 if (CXXConstructorDecl *FieldCopyCtor = 3900 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 3901 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 3902 } 3903 } 3904 CopyConstructor->setUsed(); 3905 3906 CurContext = PreviousContext; 3907} 3908 3909Sema::OwningExprResult 3910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3911 CXXConstructorDecl *Constructor, 3912 MultiExprArg ExprArgs, 3913 bool RequiresZeroInit, 3914 bool BaseInitialization) { 3915 bool Elidable = false; 3916 3917 // C++ [class.copy]p15: 3918 // Whenever a temporary class object is copied using a copy constructor, and 3919 // this object and the copy have the same cv-unqualified type, an 3920 // implementation is permitted to treat the original and the copy as two 3921 // different ways of referring to the same object and not perform a copy at 3922 // all, even if the class copy constructor or destructor have side effects. 3923 3924 // FIXME: Is this enough? 3925 if (Constructor->isCopyConstructor()) { 3926 Expr *E = ((Expr **)ExprArgs.get())[0]; 3927 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 3928 if (ICE->getCastKind() == CastExpr::CK_NoOp) 3929 E = ICE->getSubExpr(); 3930 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E)) 3931 E = FCE->getSubExpr(); 3932 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 3933 E = BE->getSubExpr(); 3934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 3935 if (ICE->getCastKind() == CastExpr::CK_NoOp) 3936 E = ICE->getSubExpr(); 3937 3938 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 3939 Elidable = !CE->getCallReturnType()->isReferenceType(); 3940 else if (isa<CXXTemporaryObjectExpr>(E)) 3941 Elidable = true; 3942 else if (isa<CXXConstructExpr>(E)) 3943 Elidable = true; 3944 } 3945 3946 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 3947 Elidable, move(ExprArgs), RequiresZeroInit, 3948 BaseInitialization); 3949} 3950 3951/// BuildCXXConstructExpr - Creates a complete call to a constructor, 3952/// including handling of its default argument expressions. 3953Sema::OwningExprResult 3954Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3955 CXXConstructorDecl *Constructor, bool Elidable, 3956 MultiExprArg ExprArgs, 3957 bool RequiresZeroInit, 3958 bool BaseInitialization) { 3959 unsigned NumExprs = ExprArgs.size(); 3960 Expr **Exprs = (Expr **)ExprArgs.release(); 3961 3962 MarkDeclarationReferenced(ConstructLoc, Constructor); 3963 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 3964 Constructor, Elidable, Exprs, NumExprs, 3965 RequiresZeroInit, BaseInitialization)); 3966} 3967 3968Sema::OwningExprResult 3969Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 3970 QualType Ty, 3971 SourceLocation TyBeginLoc, 3972 MultiExprArg Args, 3973 SourceLocation RParenLoc) { 3974 unsigned NumExprs = Args.size(); 3975 Expr **Exprs = (Expr **)Args.release(); 3976 3977 MarkDeclarationReferenced(TyBeginLoc, Constructor); 3978 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, 3979 TyBeginLoc, Exprs, 3980 NumExprs, RParenLoc)); 3981} 3982 3983 3984bool Sema::InitializeVarWithConstructor(VarDecl *VD, 3985 CXXConstructorDecl *Constructor, 3986 MultiExprArg Exprs) { 3987 OwningExprResult TempResult = 3988 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 3989 move(Exprs)); 3990 if (TempResult.isInvalid()) 3991 return true; 3992 3993 Expr *Temp = TempResult.takeAs<Expr>(); 3994 MarkDeclarationReferenced(VD->getLocation(), Constructor); 3995 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 3996 VD->setInit(Context, Temp); 3997 3998 return false; 3999} 4000 4001void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) { 4002 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 4003 DeclInitType->getAs<RecordType>()->getDecl()); 4004 if (!ClassDecl->hasTrivialDestructor()) 4005 if (CXXDestructorDecl *Destructor = 4006 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 4007 MarkDeclarationReferenced(VD->getLocation(), Destructor); 4008} 4009 4010/// AddCXXDirectInitializerToDecl - This action is called immediately after 4011/// ActOnDeclarator, when a C++ direct initializer is present. 4012/// e.g: "int x(1);" 4013void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 4014 SourceLocation LParenLoc, 4015 MultiExprArg Exprs, 4016 SourceLocation *CommaLocs, 4017 SourceLocation RParenLoc) { 4018 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 4019 Decl *RealDecl = Dcl.getAs<Decl>(); 4020 4021 // If there is no declaration, there was an error parsing it. Just ignore 4022 // the initializer. 4023 if (RealDecl == 0) 4024 return; 4025 4026 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4027 if (!VDecl) { 4028 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4029 RealDecl->setInvalidDecl(); 4030 return; 4031 } 4032 4033 // We will represent direct-initialization similarly to copy-initialization: 4034 // int x(1); -as-> int x = 1; 4035 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 4036 // 4037 // Clients that want to distinguish between the two forms, can check for 4038 // direct initializer using VarDecl::hasCXXDirectInitializer(). 4039 // A major benefit is that clients that don't particularly care about which 4040 // exactly form was it (like the CodeGen) can handle both cases without 4041 // special case code. 4042 4043 // If either the declaration has a dependent type or if any of the expressions 4044 // is type-dependent, we represent the initialization via a ParenListExpr for 4045 // later use during template instantiation. 4046 if (VDecl->getType()->isDependentType() || 4047 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 4048 // Let clients know that initialization was done with a direct initializer. 4049 VDecl->setCXXDirectInitializer(true); 4050 4051 // Store the initialization expressions as a ParenListExpr. 4052 unsigned NumExprs = Exprs.size(); 4053 VDecl->setInit(Context, 4054 new (Context) ParenListExpr(Context, LParenLoc, 4055 (Expr **)Exprs.release(), 4056 NumExprs, RParenLoc)); 4057 return; 4058 } 4059 4060 4061 // C++ 8.5p11: 4062 // The form of initialization (using parentheses or '=') is generally 4063 // insignificant, but does matter when the entity being initialized has a 4064 // class type. 4065 QualType DeclInitType = VDecl->getType(); 4066 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 4067 DeclInitType = Context.getBaseElementType(Array); 4068 4069 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 4070 diag::err_typecheck_decl_incomplete_type)) { 4071 VDecl->setInvalidDecl(); 4072 return; 4073 } 4074 4075 // The variable can not have an abstract class type. 4076 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4077 diag::err_abstract_type_in_decl, 4078 AbstractVariableType)) 4079 VDecl->setInvalidDecl(); 4080 4081 const VarDecl *Def = 0; 4082 if (VDecl->getDefinition(Def)) { 4083 Diag(VDecl->getLocation(), diag::err_redefinition) 4084 << VDecl->getDeclName(); 4085 Diag(Def->getLocation(), diag::note_previous_definition); 4086 VDecl->setInvalidDecl(); 4087 return; 4088 } 4089 4090 // Capture the variable that is being initialized and the style of 4091 // initialization. 4092 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4093 4094 // FIXME: Poor source location information. 4095 InitializationKind Kind 4096 = InitializationKind::CreateDirect(VDecl->getLocation(), 4097 LParenLoc, RParenLoc); 4098 4099 InitializationSequence InitSeq(*this, Entity, Kind, 4100 (Expr**)Exprs.get(), Exprs.size()); 4101 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 4102 if (Result.isInvalid()) { 4103 VDecl->setInvalidDecl(); 4104 return; 4105 } 4106 4107 Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 4108 VDecl->setInit(Context, Result.takeAs<Expr>()); 4109 VDecl->setCXXDirectInitializer(true); 4110 4111 if (VDecl->getType()->getAs<RecordType>()) 4112 FinalizeVarWithDestructor(VDecl, DeclInitType); 4113} 4114 4115/// \brief Add the applicable constructor candidates for an initialization 4116/// by constructor. 4117static void AddConstructorInitializationCandidates(Sema &SemaRef, 4118 QualType ClassType, 4119 Expr **Args, 4120 unsigned NumArgs, 4121 InitializationKind Kind, 4122 OverloadCandidateSet &CandidateSet) { 4123 // C++ [dcl.init]p14: 4124 // If the initialization is direct-initialization, or if it is 4125 // copy-initialization where the cv-unqualified version of the 4126 // source type is the same class as, or a derived class of, the 4127 // class of the destination, constructors are considered. The 4128 // applicable constructors are enumerated (13.3.1.3), and the 4129 // best one is chosen through overload resolution (13.3). The 4130 // constructor so selected is called to initialize the object, 4131 // with the initializer expression(s) as its argument(s). If no 4132 // constructor applies, or the overload resolution is ambiguous, 4133 // the initialization is ill-formed. 4134 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 4135 assert(ClassRec && "Can only initialize a class type here"); 4136 4137 // FIXME: When we decide not to synthesize the implicitly-declared 4138 // constructors, we'll need to make them appear here. 4139 4140 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 4141 DeclarationName ConstructorName 4142 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 4143 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType()); 4144 DeclContext::lookup_const_iterator Con, ConEnd; 4145 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 4146 Con != ConEnd; ++Con) { 4147 // Find the constructor (which may be a template). 4148 CXXConstructorDecl *Constructor = 0; 4149 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 4150 if (ConstructorTmpl) 4151 Constructor 4152 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 4153 else 4154 Constructor = cast<CXXConstructorDecl>(*Con); 4155 4156 if ((Kind.getKind() == InitializationKind::IK_Direct) || 4157 (Kind.getKind() == InitializationKind::IK_Value) || 4158 (Kind.getKind() == InitializationKind::IK_Copy && 4159 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 4160 ((Kind.getKind() == InitializationKind::IK_Default) && 4161 Constructor->isDefaultConstructor())) { 4162 if (ConstructorTmpl) 4163 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, 4164 ConstructorTmpl->getAccess(), 4165 /*ExplicitArgs*/ 0, 4166 Args, NumArgs, CandidateSet); 4167 else 4168 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(), 4169 Args, NumArgs, CandidateSet); 4170 } 4171 } 4172} 4173 4174/// \brief Attempt to perform initialization by constructor 4175/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or 4176/// copy-initialization. 4177/// 4178/// This routine determines whether initialization by constructor is possible, 4179/// but it does not emit any diagnostics in the case where the initialization 4180/// is ill-formed. 4181/// 4182/// \param ClassType the type of the object being initialized, which must have 4183/// class type. 4184/// 4185/// \param Args the arguments provided to initialize the object 4186/// 4187/// \param NumArgs the number of arguments provided to initialize the object 4188/// 4189/// \param Kind the type of initialization being performed 4190/// 4191/// \returns the constructor used to initialize the object, if successful. 4192/// Otherwise, emits a diagnostic and returns NULL. 4193CXXConstructorDecl * 4194Sema::TryInitializationByConstructor(QualType ClassType, 4195 Expr **Args, unsigned NumArgs, 4196 SourceLocation Loc, 4197 InitializationKind Kind) { 4198 // Build the overload candidate set 4199 OverloadCandidateSet CandidateSet; 4200 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 4201 CandidateSet); 4202 4203 // Determine whether we found a constructor we can use. 4204 OverloadCandidateSet::iterator Best; 4205 switch (BestViableFunction(CandidateSet, Loc, Best)) { 4206 case OR_Success: 4207 case OR_Deleted: 4208 // We found a constructor. Return it. 4209 return cast<CXXConstructorDecl>(Best->Function); 4210 4211 case OR_No_Viable_Function: 4212 case OR_Ambiguous: 4213 // Overload resolution failed. Return nothing. 4214 return 0; 4215 } 4216 4217 // Silence GCC warning 4218 return 0; 4219} 4220 4221/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which 4222/// may occur as part of direct-initialization or copy-initialization. 4223/// 4224/// \param ClassType the type of the object being initialized, which must have 4225/// class type. 4226/// 4227/// \param ArgsPtr the arguments provided to initialize the object 4228/// 4229/// \param Loc the source location where the initialization occurs 4230/// 4231/// \param Range the source range that covers the entire initialization 4232/// 4233/// \param InitEntity the name of the entity being initialized, if known 4234/// 4235/// \param Kind the type of initialization being performed 4236/// 4237/// \param ConvertedArgs a vector that will be filled in with the 4238/// appropriately-converted arguments to the constructor (if initialization 4239/// succeeded). 4240/// 4241/// \returns the constructor used to initialize the object, if successful. 4242/// Otherwise, emits a diagnostic and returns NULL. 4243CXXConstructorDecl * 4244Sema::PerformInitializationByConstructor(QualType ClassType, 4245 MultiExprArg ArgsPtr, 4246 SourceLocation Loc, SourceRange Range, 4247 DeclarationName InitEntity, 4248 InitializationKind Kind, 4249 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 4250 4251 // Build the overload candidate set 4252 Expr **Args = (Expr **)ArgsPtr.get(); 4253 unsigned NumArgs = ArgsPtr.size(); 4254 OverloadCandidateSet CandidateSet; 4255 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind, 4256 CandidateSet); 4257 4258 OverloadCandidateSet::iterator Best; 4259 switch (BestViableFunction(CandidateSet, Loc, Best)) { 4260 case OR_Success: 4261 // We found a constructor. Break out so that we can convert the arguments 4262 // appropriately. 4263 break; 4264 4265 case OR_No_Viable_Function: 4266 if (InitEntity) 4267 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 4268 << InitEntity << Range; 4269 else 4270 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 4271 << ClassType << Range; 4272 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 4273 return 0; 4274 4275 case OR_Ambiguous: 4276 if (InitEntity) 4277 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 4278 else 4279 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 4280 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 4281 return 0; 4282 4283 case OR_Deleted: 4284 if (InitEntity) 4285 Diag(Loc, diag::err_ovl_deleted_init) 4286 << Best->Function->isDeleted() 4287 << InitEntity << Range; 4288 else { 4289 const CXXRecordDecl *RD = 4290 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl()); 4291 Diag(Loc, diag::err_ovl_deleted_init) 4292 << Best->Function->isDeleted() 4293 << RD->getDeclName() << Range; 4294 } 4295 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 4296 return 0; 4297 } 4298 4299 // Convert the arguments, fill in default arguments, etc. 4300 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 4301 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs)) 4302 return 0; 4303 4304 return Constructor; 4305} 4306 4307/// \brief Given a constructor and the set of arguments provided for the 4308/// constructor, convert the arguments and add any required default arguments 4309/// to form a proper call to this constructor. 4310/// 4311/// \returns true if an error occurred, false otherwise. 4312bool 4313Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 4314 MultiExprArg ArgsPtr, 4315 SourceLocation Loc, 4316 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 4317 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 4318 unsigned NumArgs = ArgsPtr.size(); 4319 Expr **Args = (Expr **)ArgsPtr.get(); 4320 4321 const FunctionProtoType *Proto 4322 = Constructor->getType()->getAs<FunctionProtoType>(); 4323 assert(Proto && "Constructor without a prototype?"); 4324 unsigned NumArgsInProto = Proto->getNumArgs(); 4325 4326 // If too few arguments are available, we'll fill in the rest with defaults. 4327 if (NumArgs < NumArgsInProto) 4328 ConvertedArgs.reserve(NumArgsInProto); 4329 else 4330 ConvertedArgs.reserve(NumArgs); 4331 4332 VariadicCallType CallType = 4333 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4334 llvm::SmallVector<Expr *, 8> AllArgs; 4335 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 4336 Proto, 0, Args, NumArgs, AllArgs, 4337 CallType); 4338 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 4339 ConvertedArgs.push_back(AllArgs[i]); 4340 return Invalid; 4341} 4342 4343/// CompareReferenceRelationship - Compare the two types T1 and T2 to 4344/// determine whether they are reference-related, 4345/// reference-compatible, reference-compatible with added 4346/// qualification, or incompatible, for use in C++ initialization by 4347/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4348/// type, and the first type (T1) is the pointee type of the reference 4349/// type being initialized. 4350Sema::ReferenceCompareResult 4351Sema::CompareReferenceRelationship(SourceLocation Loc, 4352 QualType OrigT1, QualType OrigT2, 4353 bool& DerivedToBase) { 4354 assert(!OrigT1->isReferenceType() && 4355 "T1 must be the pointee type of the reference type"); 4356 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4357 4358 QualType T1 = Context.getCanonicalType(OrigT1); 4359 QualType T2 = Context.getCanonicalType(OrigT2); 4360 Qualifiers T1Quals, T2Quals; 4361 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4362 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4363 4364 // C++ [dcl.init.ref]p4: 4365 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4366 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4367 // T1 is a base class of T2. 4368 if (UnqualT1 == UnqualT2) 4369 DerivedToBase = false; 4370 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) && 4371 !RequireCompleteType(Loc, OrigT2, PDiag()) && 4372 IsDerivedFrom(UnqualT2, UnqualT1)) 4373 DerivedToBase = true; 4374 else 4375 return Ref_Incompatible; 4376 4377 // At this point, we know that T1 and T2 are reference-related (at 4378 // least). 4379 4380 // If the type is an array type, promote the element qualifiers to the type 4381 // for comparison. 4382 if (isa<ArrayType>(T1) && T1Quals) 4383 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4384 if (isa<ArrayType>(T2) && T2Quals) 4385 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4386 4387 // C++ [dcl.init.ref]p4: 4388 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4389 // reference-related to T2 and cv1 is the same cv-qualification 4390 // as, or greater cv-qualification than, cv2. For purposes of 4391 // overload resolution, cases for which cv1 is greater 4392 // cv-qualification than cv2 are identified as 4393 // reference-compatible with added qualification (see 13.3.3.2). 4394 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers()) 4395 return Ref_Compatible; 4396 else if (T1.isMoreQualifiedThan(T2)) 4397 return Ref_Compatible_With_Added_Qualification; 4398 else 4399 return Ref_Related; 4400} 4401 4402/// CheckReferenceInit - Check the initialization of a reference 4403/// variable with the given initializer (C++ [dcl.init.ref]). Init is 4404/// the initializer (either a simple initializer or an initializer 4405/// list), and DeclType is the type of the declaration. When ICS is 4406/// non-null, this routine will compute the implicit conversion 4407/// sequence according to C++ [over.ics.ref] and will not produce any 4408/// diagnostics; when ICS is null, it will emit diagnostics when any 4409/// errors are found. Either way, a return value of true indicates 4410/// that there was a failure, a return value of false indicates that 4411/// the reference initialization succeeded. 4412/// 4413/// When @p SuppressUserConversions, user-defined conversions are 4414/// suppressed. 4415/// When @p AllowExplicit, we also permit explicit user-defined 4416/// conversion functions. 4417/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 4418/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion. 4419/// This is used when this is called from a C-style cast. 4420bool 4421Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 4422 SourceLocation DeclLoc, 4423 bool SuppressUserConversions, 4424 bool AllowExplicit, bool ForceRValue, 4425 ImplicitConversionSequence *ICS, 4426 bool IgnoreBaseAccess) { 4427 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4428 4429 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4430 QualType T2 = Init->getType(); 4431 4432 // If the initializer is the address of an overloaded function, try 4433 // to resolve the overloaded function. If all goes well, T2 is the 4434 // type of the resulting function. 4435 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 4436 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 4437 ICS != 0); 4438 if (Fn) { 4439 // Since we're performing this reference-initialization for 4440 // real, update the initializer with the resulting function. 4441 if (!ICS) { 4442 if (DiagnoseUseOfDecl(Fn, DeclLoc)) 4443 return true; 4444 4445 Init = FixOverloadedFunctionReference(Init, Fn); 4446 } 4447 4448 T2 = Fn->getType(); 4449 } 4450 } 4451 4452 // Compute some basic properties of the types and the initializer. 4453 bool isRValRef = DeclType->isRValueReferenceType(); 4454 bool DerivedToBase = false; 4455 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 4456 Init->isLvalue(Context); 4457 ReferenceCompareResult RefRelationship 4458 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase); 4459 4460 // Most paths end in a failed conversion. 4461 if (ICS) { 4462 ICS->setBad(); 4463 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType); 4464 } 4465 4466 // C++ [dcl.init.ref]p5: 4467 // A reference to type "cv1 T1" is initialized by an expression 4468 // of type "cv2 T2" as follows: 4469 4470 // -- If the initializer expression 4471 4472 // Rvalue references cannot bind to lvalues (N2812). 4473 // There is absolutely no situation where they can. In particular, note that 4474 // this is ill-formed, even if B has a user-defined conversion to A&&: 4475 // B b; 4476 // A&& r = b; 4477 if (isRValRef && InitLvalue == Expr::LV_Valid) { 4478 if (!ICS) 4479 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 4480 << Init->getSourceRange(); 4481 return true; 4482 } 4483 4484 bool BindsDirectly = false; 4485 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4486 // reference-compatible with "cv2 T2," or 4487 // 4488 // Note that the bit-field check is skipped if we are just computing 4489 // the implicit conversion sequence (C++ [over.best.ics]p2). 4490 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 4491 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 4492 BindsDirectly = true; 4493 4494 if (ICS) { 4495 // C++ [over.ics.ref]p1: 4496 // When a parameter of reference type binds directly (8.5.3) 4497 // to an argument expression, the implicit conversion sequence 4498 // is the identity conversion, unless the argument expression 4499 // has a type that is a derived class of the parameter type, 4500 // in which case the implicit conversion sequence is a 4501 // derived-to-base Conversion (13.3.3.1). 4502 ICS->setStandard(); 4503 ICS->Standard.First = ICK_Identity; 4504 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 4505 ICS->Standard.Third = ICK_Identity; 4506 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 4507 ICS->Standard.setToType(0, T2); 4508 ICS->Standard.setToType(1, T1); 4509 ICS->Standard.setToType(2, T1); 4510 ICS->Standard.ReferenceBinding = true; 4511 ICS->Standard.DirectBinding = true; 4512 ICS->Standard.RRefBinding = false; 4513 ICS->Standard.CopyConstructor = 0; 4514 4515 // Nothing more to do: the inaccessibility/ambiguity check for 4516 // derived-to-base conversions is suppressed when we're 4517 // computing the implicit conversion sequence (C++ 4518 // [over.best.ics]p2). 4519 return false; 4520 } else { 4521 // Perform the conversion. 4522 CastExpr::CastKind CK = CastExpr::CK_NoOp; 4523 if (DerivedToBase) 4524 CK = CastExpr::CK_DerivedToBase; 4525 else if(CheckExceptionSpecCompatibility(Init, T1)) 4526 return true; 4527 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 4528 } 4529 } 4530 4531 // -- has a class type (i.e., T2 is a class type) and can be 4532 // implicitly converted to an lvalue of type "cv3 T3," 4533 // where "cv1 T1" is reference-compatible with "cv3 T3" 4534 // 92) (this conversion is selected by enumerating the 4535 // applicable conversion functions (13.3.1.6) and choosing 4536 // the best one through overload resolution (13.3)), 4537 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 4538 !RequireCompleteType(DeclLoc, T2, 0)) { 4539 CXXRecordDecl *T2RecordDecl 4540 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4541 4542 OverloadCandidateSet CandidateSet; 4543 const UnresolvedSetImpl *Conversions 4544 = T2RecordDecl->getVisibleConversionFunctions(); 4545 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4546 E = Conversions->end(); I != E; ++I) { 4547 NamedDecl *D = *I; 4548 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4549 if (isa<UsingShadowDecl>(D)) 4550 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4551 4552 FunctionTemplateDecl *ConvTemplate 4553 = dyn_cast<FunctionTemplateDecl>(D); 4554 CXXConversionDecl *Conv; 4555 if (ConvTemplate) 4556 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4557 else 4558 Conv = cast<CXXConversionDecl>(D); 4559 4560 // If the conversion function doesn't return a reference type, 4561 // it can't be considered for this conversion. 4562 if (Conv->getConversionType()->isLValueReferenceType() && 4563 (AllowExplicit || !Conv->isExplicit())) { 4564 if (ConvTemplate) 4565 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC, 4566 Init, DeclType, CandidateSet); 4567 else 4568 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init, 4569 DeclType, CandidateSet); 4570 } 4571 } 4572 4573 OverloadCandidateSet::iterator Best; 4574 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) { 4575 case OR_Success: 4576 // This is a direct binding. 4577 BindsDirectly = true; 4578 4579 if (ICS) { 4580 // C++ [over.ics.ref]p1: 4581 // 4582 // [...] If the parameter binds directly to the result of 4583 // applying a conversion function to the argument 4584 // expression, the implicit conversion sequence is a 4585 // user-defined conversion sequence (13.3.3.1.2), with the 4586 // second standard conversion sequence either an identity 4587 // conversion or, if the conversion function returns an 4588 // entity of a type that is a derived class of the parameter 4589 // type, a derived-to-base Conversion. 4590 ICS->setUserDefined(); 4591 ICS->UserDefined.Before = Best->Conversions[0].Standard; 4592 ICS->UserDefined.After = Best->FinalConversion; 4593 ICS->UserDefined.ConversionFunction = Best->Function; 4594 ICS->UserDefined.EllipsisConversion = false; 4595 assert(ICS->UserDefined.After.ReferenceBinding && 4596 ICS->UserDefined.After.DirectBinding && 4597 "Expected a direct reference binding!"); 4598 return false; 4599 } else { 4600 OwningExprResult InitConversion = 4601 BuildCXXCastArgument(DeclLoc, QualType(), 4602 CastExpr::CK_UserDefinedConversion, 4603 cast<CXXMethodDecl>(Best->Function), 4604 Owned(Init)); 4605 Init = InitConversion.takeAs<Expr>(); 4606 4607 if (CheckExceptionSpecCompatibility(Init, T1)) 4608 return true; 4609 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion, 4610 /*isLvalue=*/true); 4611 } 4612 break; 4613 4614 case OR_Ambiguous: 4615 if (ICS) { 4616 ICS->setAmbiguous(); 4617 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4618 Cand != CandidateSet.end(); ++Cand) 4619 if (Cand->Viable) 4620 ICS->Ambiguous.addConversion(Cand->Function); 4621 break; 4622 } 4623 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType() 4624 << Init->getSourceRange(); 4625 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1); 4626 return true; 4627 4628 case OR_No_Viable_Function: 4629 case OR_Deleted: 4630 // There was no suitable conversion, or we found a deleted 4631 // conversion; continue with other checks. 4632 break; 4633 } 4634 } 4635 4636 if (BindsDirectly) { 4637 // C++ [dcl.init.ref]p4: 4638 // [...] In all cases where the reference-related or 4639 // reference-compatible relationship of two types is used to 4640 // establish the validity of a reference binding, and T1 is a 4641 // base class of T2, a program that necessitates such a binding 4642 // is ill-formed if T1 is an inaccessible (clause 11) or 4643 // ambiguous (10.2) base class of T2. 4644 // 4645 // Note that we only check this condition when we're allowed to 4646 // complain about errors, because we should not be checking for 4647 // ambiguity (or inaccessibility) unless the reference binding 4648 // actually happens. 4649 if (DerivedToBase) 4650 return CheckDerivedToBaseConversion(T2, T1, DeclLoc, 4651 Init->getSourceRange(), 4652 IgnoreBaseAccess); 4653 else 4654 return false; 4655 } 4656 4657 // -- Otherwise, the reference shall be to a non-volatile const 4658 // type (i.e., cv1 shall be const), or the reference shall be an 4659 // rvalue reference and the initializer expression shall be an rvalue. 4660 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) { 4661 if (!ICS) 4662 Diag(DeclLoc, diag::err_not_reference_to_const_init) 4663 << T1.isVolatileQualified() 4664 << T1 << int(InitLvalue != Expr::LV_Valid) 4665 << T2 << Init->getSourceRange(); 4666 return true; 4667 } 4668 4669 // -- If the initializer expression is an rvalue, with T2 a 4670 // class type, and "cv1 T1" is reference-compatible with 4671 // "cv2 T2," the reference is bound in one of the 4672 // following ways (the choice is implementation-defined): 4673 // 4674 // -- The reference is bound to the object represented by 4675 // the rvalue (see 3.10) or to a sub-object within that 4676 // object. 4677 // 4678 // -- A temporary of type "cv1 T2" [sic] is created, and 4679 // a constructor is called to copy the entire rvalue 4680 // object into the temporary. The reference is bound to 4681 // the temporary or to a sub-object within the 4682 // temporary. 4683 // 4684 // The constructor that would be used to make the copy 4685 // shall be callable whether or not the copy is actually 4686 // done. 4687 // 4688 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 4689 // freedom, so we will always take the first option and never build 4690 // a temporary in this case. FIXME: We will, however, have to check 4691 // for the presence of a copy constructor in C++98/03 mode. 4692 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 4693 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 4694 if (ICS) { 4695 ICS->setStandard(); 4696 ICS->Standard.First = ICK_Identity; 4697 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 4698 ICS->Standard.Third = ICK_Identity; 4699 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 4700 ICS->Standard.setToType(0, T2); 4701 ICS->Standard.setToType(1, T1); 4702 ICS->Standard.setToType(2, T1); 4703 ICS->Standard.ReferenceBinding = true; 4704 ICS->Standard.DirectBinding = false; 4705 ICS->Standard.RRefBinding = isRValRef; 4706 ICS->Standard.CopyConstructor = 0; 4707 } else { 4708 CastExpr::CastKind CK = CastExpr::CK_NoOp; 4709 if (DerivedToBase) 4710 CK = CastExpr::CK_DerivedToBase; 4711 else if(CheckExceptionSpecCompatibility(Init, T1)) 4712 return true; 4713 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 4714 } 4715 return false; 4716 } 4717 4718 // -- Otherwise, a temporary of type "cv1 T1" is created and 4719 // initialized from the initializer expression using the 4720 // rules for a non-reference copy initialization (8.5). The 4721 // reference is then bound to the temporary. If T1 is 4722 // reference-related to T2, cv1 must be the same 4723 // cv-qualification as, or greater cv-qualification than, 4724 // cv2; otherwise, the program is ill-formed. 4725 if (RefRelationship == Ref_Related) { 4726 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4727 // we would be reference-compatible or reference-compatible with 4728 // added qualification. But that wasn't the case, so the reference 4729 // initialization fails. 4730 if (!ICS) 4731 Diag(DeclLoc, diag::err_reference_init_drops_quals) 4732 << T1 << int(InitLvalue != Expr::LV_Valid) 4733 << T2 << Init->getSourceRange(); 4734 return true; 4735 } 4736 4737 // If at least one of the types is a class type, the types are not 4738 // related, and we aren't allowed any user conversions, the 4739 // reference binding fails. This case is important for breaking 4740 // recursion, since TryImplicitConversion below will attempt to 4741 // create a temporary through the use of a copy constructor. 4742 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 4743 (T1->isRecordType() || T2->isRecordType())) { 4744 if (!ICS) 4745 Diag(DeclLoc, diag::err_typecheck_convert_incompatible) 4746 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange(); 4747 return true; 4748 } 4749 4750 // Actually try to convert the initializer to T1. 4751 if (ICS) { 4752 // C++ [over.ics.ref]p2: 4753 // 4754 // When a parameter of reference type is not bound directly to 4755 // an argument expression, the conversion sequence is the one 4756 // required to convert the argument expression to the 4757 // underlying type of the reference according to 4758 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4759 // to copy-initializing a temporary of the underlying type with 4760 // the argument expression. Any difference in top-level 4761 // cv-qualification is subsumed by the initialization itself 4762 // and does not constitute a conversion. 4763 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 4764 /*AllowExplicit=*/false, 4765 /*ForceRValue=*/false, 4766 /*InOverloadResolution=*/false); 4767 4768 // Of course, that's still a reference binding. 4769 if (ICS->isStandard()) { 4770 ICS->Standard.ReferenceBinding = true; 4771 ICS->Standard.RRefBinding = isRValRef; 4772 } else if (ICS->isUserDefined()) { 4773 ICS->UserDefined.After.ReferenceBinding = true; 4774 ICS->UserDefined.After.RRefBinding = isRValRef; 4775 } 4776 return ICS->isBad(); 4777 } else { 4778 ImplicitConversionSequence Conversions; 4779 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing, 4780 false, false, 4781 Conversions); 4782 if (badConversion) { 4783 if (Conversions.isAmbiguous()) { 4784 Diag(DeclLoc, 4785 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 4786 for (int j = Conversions.Ambiguous.conversions().size()-1; 4787 j >= 0; j--) { 4788 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j]; 4789 NoteOverloadCandidate(Func); 4790 } 4791 } 4792 else { 4793 if (isRValRef) 4794 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref) 4795 << Init->getSourceRange(); 4796 else 4797 Diag(DeclLoc, diag::err_invalid_initialization) 4798 << DeclType << Init->getType() << Init->getSourceRange(); 4799 } 4800 } 4801 return badConversion; 4802 } 4803} 4804 4805static inline bool 4806CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 4807 const FunctionDecl *FnDecl) { 4808 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 4809 if (isa<NamespaceDecl>(DC)) { 4810 return SemaRef.Diag(FnDecl->getLocation(), 4811 diag::err_operator_new_delete_declared_in_namespace) 4812 << FnDecl->getDeclName(); 4813 } 4814 4815 if (isa<TranslationUnitDecl>(DC) && 4816 FnDecl->getStorageClass() == FunctionDecl::Static) { 4817 return SemaRef.Diag(FnDecl->getLocation(), 4818 diag::err_operator_new_delete_declared_static) 4819 << FnDecl->getDeclName(); 4820 } 4821 4822 return false; 4823} 4824 4825static inline bool 4826CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 4827 CanQualType ExpectedResultType, 4828 CanQualType ExpectedFirstParamType, 4829 unsigned DependentParamTypeDiag, 4830 unsigned InvalidParamTypeDiag) { 4831 QualType ResultType = 4832 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 4833 4834 // Check that the result type is not dependent. 4835 if (ResultType->isDependentType()) 4836 return SemaRef.Diag(FnDecl->getLocation(), 4837 diag::err_operator_new_delete_dependent_result_type) 4838 << FnDecl->getDeclName() << ExpectedResultType; 4839 4840 // Check that the result type is what we expect. 4841 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 4842 return SemaRef.Diag(FnDecl->getLocation(), 4843 diag::err_operator_new_delete_invalid_result_type) 4844 << FnDecl->getDeclName() << ExpectedResultType; 4845 4846 // A function template must have at least 2 parameters. 4847 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 4848 return SemaRef.Diag(FnDecl->getLocation(), 4849 diag::err_operator_new_delete_template_too_few_parameters) 4850 << FnDecl->getDeclName(); 4851 4852 // The function decl must have at least 1 parameter. 4853 if (FnDecl->getNumParams() == 0) 4854 return SemaRef.Diag(FnDecl->getLocation(), 4855 diag::err_operator_new_delete_too_few_parameters) 4856 << FnDecl->getDeclName(); 4857 4858 // Check the the first parameter type is not dependent. 4859 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4860 if (FirstParamType->isDependentType()) 4861 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 4862 << FnDecl->getDeclName() << ExpectedFirstParamType; 4863 4864 // Check that the first parameter type is what we expect. 4865 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 4866 ExpectedFirstParamType) 4867 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 4868 << FnDecl->getDeclName() << ExpectedFirstParamType; 4869 4870 return false; 4871} 4872 4873static bool 4874CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4875 // C++ [basic.stc.dynamic.allocation]p1: 4876 // A program is ill-formed if an allocation function is declared in a 4877 // namespace scope other than global scope or declared static in global 4878 // scope. 4879 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4880 return true; 4881 4882 CanQualType SizeTy = 4883 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 4884 4885 // C++ [basic.stc.dynamic.allocation]p1: 4886 // The return type shall be void*. The first parameter shall have type 4887 // std::size_t. 4888 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 4889 SizeTy, 4890 diag::err_operator_new_dependent_param_type, 4891 diag::err_operator_new_param_type)) 4892 return true; 4893 4894 // C++ [basic.stc.dynamic.allocation]p1: 4895 // The first parameter shall not have an associated default argument. 4896 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 4897 return SemaRef.Diag(FnDecl->getLocation(), 4898 diag::err_operator_new_default_arg) 4899 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 4900 4901 return false; 4902} 4903 4904static bool 4905CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 4906 // C++ [basic.stc.dynamic.deallocation]p1: 4907 // A program is ill-formed if deallocation functions are declared in a 4908 // namespace scope other than global scope or declared static in global 4909 // scope. 4910 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 4911 return true; 4912 4913 // C++ [basic.stc.dynamic.deallocation]p2: 4914 // Each deallocation function shall return void and its first parameter 4915 // shall be void*. 4916 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 4917 SemaRef.Context.VoidPtrTy, 4918 diag::err_operator_delete_dependent_param_type, 4919 diag::err_operator_delete_param_type)) 4920 return true; 4921 4922 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 4923 if (FirstParamType->isDependentType()) 4924 return SemaRef.Diag(FnDecl->getLocation(), 4925 diag::err_operator_delete_dependent_param_type) 4926 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4927 4928 if (SemaRef.Context.getCanonicalType(FirstParamType) != 4929 SemaRef.Context.VoidPtrTy) 4930 return SemaRef.Diag(FnDecl->getLocation(), 4931 diag::err_operator_delete_param_type) 4932 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 4933 4934 return false; 4935} 4936 4937/// CheckOverloadedOperatorDeclaration - Check whether the declaration 4938/// of this overloaded operator is well-formed. If so, returns false; 4939/// otherwise, emits appropriate diagnostics and returns true. 4940bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 4941 assert(FnDecl && FnDecl->isOverloadedOperator() && 4942 "Expected an overloaded operator declaration"); 4943 4944 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 4945 4946 // C++ [over.oper]p5: 4947 // The allocation and deallocation functions, operator new, 4948 // operator new[], operator delete and operator delete[], are 4949 // described completely in 3.7.3. The attributes and restrictions 4950 // found in the rest of this subclause do not apply to them unless 4951 // explicitly stated in 3.7.3. 4952 if (Op == OO_Delete || Op == OO_Array_Delete) 4953 return CheckOperatorDeleteDeclaration(*this, FnDecl); 4954 4955 if (Op == OO_New || Op == OO_Array_New) 4956 return CheckOperatorNewDeclaration(*this, FnDecl); 4957 4958 // C++ [over.oper]p6: 4959 // An operator function shall either be a non-static member 4960 // function or be a non-member function and have at least one 4961 // parameter whose type is a class, a reference to a class, an 4962 // enumeration, or a reference to an enumeration. 4963 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 4964 if (MethodDecl->isStatic()) 4965 return Diag(FnDecl->getLocation(), 4966 diag::err_operator_overload_static) << FnDecl->getDeclName(); 4967 } else { 4968 bool ClassOrEnumParam = false; 4969 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 4970 ParamEnd = FnDecl->param_end(); 4971 Param != ParamEnd; ++Param) { 4972 QualType ParamType = (*Param)->getType().getNonReferenceType(); 4973 if (ParamType->isDependentType() || ParamType->isRecordType() || 4974 ParamType->isEnumeralType()) { 4975 ClassOrEnumParam = true; 4976 break; 4977 } 4978 } 4979 4980 if (!ClassOrEnumParam) 4981 return Diag(FnDecl->getLocation(), 4982 diag::err_operator_overload_needs_class_or_enum) 4983 << FnDecl->getDeclName(); 4984 } 4985 4986 // C++ [over.oper]p8: 4987 // An operator function cannot have default arguments (8.3.6), 4988 // except where explicitly stated below. 4989 // 4990 // Only the function-call operator allows default arguments 4991 // (C++ [over.call]p1). 4992 if (Op != OO_Call) { 4993 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 4994 Param != FnDecl->param_end(); ++Param) { 4995 if ((*Param)->hasDefaultArg()) 4996 return Diag((*Param)->getLocation(), 4997 diag::err_operator_overload_default_arg) 4998 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 4999 } 5000 } 5001 5002 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 5003 { false, false, false } 5004#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5005 , { Unary, Binary, MemberOnly } 5006#include "clang/Basic/OperatorKinds.def" 5007 }; 5008 5009 bool CanBeUnaryOperator = OperatorUses[Op][0]; 5010 bool CanBeBinaryOperator = OperatorUses[Op][1]; 5011 bool MustBeMemberOperator = OperatorUses[Op][2]; 5012 5013 // C++ [over.oper]p8: 5014 // [...] Operator functions cannot have more or fewer parameters 5015 // than the number required for the corresponding operator, as 5016 // described in the rest of this subclause. 5017 unsigned NumParams = FnDecl->getNumParams() 5018 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 5019 if (Op != OO_Call && 5020 ((NumParams == 1 && !CanBeUnaryOperator) || 5021 (NumParams == 2 && !CanBeBinaryOperator) || 5022 (NumParams < 1) || (NumParams > 2))) { 5023 // We have the wrong number of parameters. 5024 unsigned ErrorKind; 5025 if (CanBeUnaryOperator && CanBeBinaryOperator) { 5026 ErrorKind = 2; // 2 -> unary or binary. 5027 } else if (CanBeUnaryOperator) { 5028 ErrorKind = 0; // 0 -> unary 5029 } else { 5030 assert(CanBeBinaryOperator && 5031 "All non-call overloaded operators are unary or binary!"); 5032 ErrorKind = 1; // 1 -> binary 5033 } 5034 5035 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 5036 << FnDecl->getDeclName() << NumParams << ErrorKind; 5037 } 5038 5039 // Overloaded operators other than operator() cannot be variadic. 5040 if (Op != OO_Call && 5041 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 5042 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 5043 << FnDecl->getDeclName(); 5044 } 5045 5046 // Some operators must be non-static member functions. 5047 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 5048 return Diag(FnDecl->getLocation(), 5049 diag::err_operator_overload_must_be_member) 5050 << FnDecl->getDeclName(); 5051 } 5052 5053 // C++ [over.inc]p1: 5054 // The user-defined function called operator++ implements the 5055 // prefix and postfix ++ operator. If this function is a member 5056 // function with no parameters, or a non-member function with one 5057 // parameter of class or enumeration type, it defines the prefix 5058 // increment operator ++ for objects of that type. If the function 5059 // is a member function with one parameter (which shall be of type 5060 // int) or a non-member function with two parameters (the second 5061 // of which shall be of type int), it defines the postfix 5062 // increment operator ++ for objects of that type. 5063 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 5064 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 5065 bool ParamIsInt = false; 5066 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 5067 ParamIsInt = BT->getKind() == BuiltinType::Int; 5068 5069 if (!ParamIsInt) 5070 return Diag(LastParam->getLocation(), 5071 diag::err_operator_overload_post_incdec_must_be_int) 5072 << LastParam->getType() << (Op == OO_MinusMinus); 5073 } 5074 5075 // Notify the class if it got an assignment operator. 5076 if (Op == OO_Equal) { 5077 // Would have returned earlier otherwise. 5078 assert(isa<CXXMethodDecl>(FnDecl) && 5079 "Overloaded = not member, but not filtered."); 5080 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 5081 Method->getParent()->addedAssignmentOperator(Context, Method); 5082 } 5083 5084 return false; 5085} 5086 5087/// CheckLiteralOperatorDeclaration - Check whether the declaration 5088/// of this literal operator function is well-formed. If so, returns 5089/// false; otherwise, emits appropriate diagnostics and returns true. 5090bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 5091 DeclContext *DC = FnDecl->getDeclContext(); 5092 Decl::Kind Kind = DC->getDeclKind(); 5093 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 5094 Kind != Decl::LinkageSpec) { 5095 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 5096 << FnDecl->getDeclName(); 5097 return true; 5098 } 5099 5100 bool Valid = false; 5101 5102 // FIXME: Check for the one valid template signature 5103 // template <char...> type operator "" name(); 5104 5105 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) { 5106 // Check the first parameter 5107 QualType T = (*Param)->getType(); 5108 5109 // unsigned long long int and long double are allowed, but only 5110 // alone. 5111 // We also allow any character type; their omission seems to be a bug 5112 // in n3000 5113 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 5114 Context.hasSameType(T, Context.LongDoubleTy) || 5115 Context.hasSameType(T, Context.CharTy) || 5116 Context.hasSameType(T, Context.WCharTy) || 5117 Context.hasSameType(T, Context.Char16Ty) || 5118 Context.hasSameType(T, Context.Char32Ty)) { 5119 if (++Param == FnDecl->param_end()) 5120 Valid = true; 5121 goto FinishedParams; 5122 } 5123 5124 // Otherwise it must be a pointer to const; let's strip those. 5125 const PointerType *PT = T->getAs<PointerType>(); 5126 if (!PT) 5127 goto FinishedParams; 5128 T = PT->getPointeeType(); 5129 if (!T.isConstQualified()) 5130 goto FinishedParams; 5131 T = T.getUnqualifiedType(); 5132 5133 // Move on to the second parameter; 5134 ++Param; 5135 5136 // If there is no second parameter, the first must be a const char * 5137 if (Param == FnDecl->param_end()) { 5138 if (Context.hasSameType(T, Context.CharTy)) 5139 Valid = true; 5140 goto FinishedParams; 5141 } 5142 5143 // const char *, const wchar_t*, const char16_t*, and const char32_t* 5144 // are allowed as the first parameter to a two-parameter function 5145 if (!(Context.hasSameType(T, Context.CharTy) || 5146 Context.hasSameType(T, Context.WCharTy) || 5147 Context.hasSameType(T, Context.Char16Ty) || 5148 Context.hasSameType(T, Context.Char32Ty))) 5149 goto FinishedParams; 5150 5151 // The second and final parameter must be an std::size_t 5152 T = (*Param)->getType().getUnqualifiedType(); 5153 if (Context.hasSameType(T, Context.getSizeType()) && 5154 ++Param == FnDecl->param_end()) 5155 Valid = true; 5156 } 5157 5158 // FIXME: This diagnostic is absolutely terrible. 5159FinishedParams: 5160 if (!Valid) { 5161 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 5162 << FnDecl->getDeclName(); 5163 return true; 5164 } 5165 5166 return false; 5167} 5168 5169/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5170/// linkage specification, including the language and (if present) 5171/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 5172/// the location of the language string literal, which is provided 5173/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 5174/// the '{' brace. Otherwise, this linkage specification does not 5175/// have any braces. 5176Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 5177 SourceLocation ExternLoc, 5178 SourceLocation LangLoc, 5179 const char *Lang, 5180 unsigned StrSize, 5181 SourceLocation LBraceLoc) { 5182 LinkageSpecDecl::LanguageIDs Language; 5183 if (strncmp(Lang, "\"C\"", StrSize) == 0) 5184 Language = LinkageSpecDecl::lang_c; 5185 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 5186 Language = LinkageSpecDecl::lang_cxx; 5187 else { 5188 Diag(LangLoc, diag::err_bad_language); 5189 return DeclPtrTy(); 5190 } 5191 5192 // FIXME: Add all the various semantics of linkage specifications 5193 5194 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 5195 LangLoc, Language, 5196 LBraceLoc.isValid()); 5197 CurContext->addDecl(D); 5198 PushDeclContext(S, D); 5199 return DeclPtrTy::make(D); 5200} 5201 5202/// ActOnFinishLinkageSpecification - Completely the definition of 5203/// the C++ linkage specification LinkageSpec. If RBraceLoc is 5204/// valid, it's the position of the closing '}' brace in a linkage 5205/// specification that uses braces. 5206Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 5207 DeclPtrTy LinkageSpec, 5208 SourceLocation RBraceLoc) { 5209 if (LinkageSpec) 5210 PopDeclContext(); 5211 return LinkageSpec; 5212} 5213 5214/// \brief Perform semantic analysis for the variable declaration that 5215/// occurs within a C++ catch clause, returning the newly-created 5216/// variable. 5217VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 5218 TypeSourceInfo *TInfo, 5219 IdentifierInfo *Name, 5220 SourceLocation Loc, 5221 SourceRange Range) { 5222 bool Invalid = false; 5223 5224 // Arrays and functions decay. 5225 if (ExDeclType->isArrayType()) 5226 ExDeclType = Context.getArrayDecayedType(ExDeclType); 5227 else if (ExDeclType->isFunctionType()) 5228 ExDeclType = Context.getPointerType(ExDeclType); 5229 5230 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 5231 // The exception-declaration shall not denote a pointer or reference to an 5232 // incomplete type, other than [cv] void*. 5233 // N2844 forbids rvalue references. 5234 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 5235 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 5236 Invalid = true; 5237 } 5238 5239 QualType BaseType = ExDeclType; 5240 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 5241 unsigned DK = diag::err_catch_incomplete; 5242 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 5243 BaseType = Ptr->getPointeeType(); 5244 Mode = 1; 5245 DK = diag::err_catch_incomplete_ptr; 5246 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 5247 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 5248 BaseType = Ref->getPointeeType(); 5249 Mode = 2; 5250 DK = diag::err_catch_incomplete_ref; 5251 } 5252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 5253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 5254 Invalid = true; 5255 5256 if (!Invalid && !ExDeclType->isDependentType() && 5257 RequireNonAbstractType(Loc, ExDeclType, 5258 diag::err_abstract_type_in_decl, 5259 AbstractVariableType)) 5260 Invalid = true; 5261 5262 // FIXME: Need to test for ability to copy-construct and destroy the 5263 // exception variable. 5264 5265 // FIXME: Need to check for abstract classes. 5266 5267 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 5268 Name, ExDeclType, TInfo, VarDecl::None); 5269 5270 if (Invalid) 5271 ExDecl->setInvalidDecl(); 5272 5273 return ExDecl; 5274} 5275 5276/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 5277/// handler. 5278Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 5279 TypeSourceInfo *TInfo = 0; 5280 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 5281 5282 bool Invalid = D.isInvalidType(); 5283 IdentifierInfo *II = D.getIdentifier(); 5284 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) { 5285 // The scope should be freshly made just for us. There is just no way 5286 // it contains any previous declaration. 5287 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 5288 if (PrevDecl->isTemplateParameter()) { 5289 // Maybe we will complain about the shadowed template parameter. 5290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5291 } 5292 } 5293 5294 if (D.getCXXScopeSpec().isSet() && !Invalid) { 5295 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 5296 << D.getCXXScopeSpec().getRange(); 5297 Invalid = true; 5298 } 5299 5300 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 5301 D.getIdentifier(), 5302 D.getIdentifierLoc(), 5303 D.getDeclSpec().getSourceRange()); 5304 5305 if (Invalid) 5306 ExDecl->setInvalidDecl(); 5307 5308 // Add the exception declaration into this scope. 5309 if (II) 5310 PushOnScopeChains(ExDecl, S); 5311 else 5312 CurContext->addDecl(ExDecl); 5313 5314 ProcessDeclAttributes(S, ExDecl, D); 5315 return DeclPtrTy::make(ExDecl); 5316} 5317 5318Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 5319 ExprArg assertexpr, 5320 ExprArg assertmessageexpr) { 5321 Expr *AssertExpr = (Expr *)assertexpr.get(); 5322 StringLiteral *AssertMessage = 5323 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 5324 5325 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 5326 llvm::APSInt Value(32); 5327 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 5328 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 5329 AssertExpr->getSourceRange(); 5330 return DeclPtrTy(); 5331 } 5332 5333 if (Value == 0) { 5334 Diag(AssertLoc, diag::err_static_assert_failed) 5335 << AssertMessage->getString() << AssertExpr->getSourceRange(); 5336 } 5337 } 5338 5339 assertexpr.release(); 5340 assertmessageexpr.release(); 5341 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 5342 AssertExpr, AssertMessage); 5343 5344 CurContext->addDecl(Decl); 5345 return DeclPtrTy::make(Decl); 5346} 5347 5348/// Handle a friend type declaration. This works in tandem with 5349/// ActOnTag. 5350/// 5351/// Notes on friend class templates: 5352/// 5353/// We generally treat friend class declarations as if they were 5354/// declaring a class. So, for example, the elaborated type specifier 5355/// in a friend declaration is required to obey the restrictions of a 5356/// class-head (i.e. no typedefs in the scope chain), template 5357/// parameters are required to match up with simple template-ids, &c. 5358/// However, unlike when declaring a template specialization, it's 5359/// okay to refer to a template specialization without an empty 5360/// template parameter declaration, e.g. 5361/// friend class A<T>::B<unsigned>; 5362/// We permit this as a special case; if there are any template 5363/// parameters present at all, require proper matching, i.e. 5364/// template <> template <class T> friend class A<int>::B; 5365Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5366 MultiTemplateParamsArg TempParams) { 5367 SourceLocation Loc = DS.getSourceRange().getBegin(); 5368 5369 assert(DS.isFriendSpecified()); 5370 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5371 5372 // Try to convert the decl specifier to a type. This works for 5373 // friend templates because ActOnTag never produces a ClassTemplateDecl 5374 // for a TUK_Friend. 5375 Declarator TheDeclarator(DS, Declarator::MemberContext); 5376 QualType T = GetTypeForDeclarator(TheDeclarator, S); 5377 if (TheDeclarator.isInvalidType()) 5378 return DeclPtrTy(); 5379 5380 // This is definitely an error in C++98. It's probably meant to 5381 // be forbidden in C++0x, too, but the specification is just 5382 // poorly written. 5383 // 5384 // The problem is with declarations like the following: 5385 // template <T> friend A<T>::foo; 5386 // where deciding whether a class C is a friend or not now hinges 5387 // on whether there exists an instantiation of A that causes 5388 // 'foo' to equal C. There are restrictions on class-heads 5389 // (which we declare (by fiat) elaborated friend declarations to 5390 // be) that makes this tractable. 5391 // 5392 // FIXME: handle "template <> friend class A<T>;", which 5393 // is possibly well-formed? Who even knows? 5394 if (TempParams.size() && !isa<ElaboratedType>(T)) { 5395 Diag(Loc, diag::err_tagless_friend_type_template) 5396 << DS.getSourceRange(); 5397 return DeclPtrTy(); 5398 } 5399 5400 // C++ [class.friend]p2: 5401 // An elaborated-type-specifier shall be used in a friend declaration 5402 // for a class.* 5403 // * The class-key of the elaborated-type-specifier is required. 5404 // This is one of the rare places in Clang where it's legitimate to 5405 // ask about the "spelling" of the type. 5406 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 5407 // If we evaluated the type to a record type, suggest putting 5408 // a tag in front. 5409 if (const RecordType *RT = T->getAs<RecordType>()) { 5410 RecordDecl *RD = RT->getDecl(); 5411 5412 std::string InsertionText = std::string(" ") + RD->getKindName(); 5413 5414 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type) 5415 << (unsigned) RD->getTagKind() 5416 << T 5417 << SourceRange(DS.getFriendSpecLoc()) 5418 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 5419 InsertionText); 5420 return DeclPtrTy(); 5421 }else { 5422 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 5423 << DS.getSourceRange(); 5424 return DeclPtrTy(); 5425 } 5426 } 5427 5428 // Enum types cannot be friends. 5429 if (T->getAs<EnumType>()) { 5430 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend) 5431 << SourceRange(DS.getFriendSpecLoc()); 5432 return DeclPtrTy(); 5433 } 5434 5435 // C++98 [class.friend]p1: A friend of a class is a function 5436 // or class that is not a member of the class . . . 5437 // This is fixed in DR77, which just barely didn't make the C++03 5438 // deadline. It's also a very silly restriction that seriously 5439 // affects inner classes and which nobody else seems to implement; 5440 // thus we never diagnose it, not even in -pedantic. 5441 5442 Decl *D; 5443 if (TempParams.size()) 5444 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 5445 TempParams.size(), 5446 (TemplateParameterList**) TempParams.release(), 5447 T.getTypePtr(), 5448 DS.getFriendSpecLoc()); 5449 else 5450 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(), 5451 DS.getFriendSpecLoc()); 5452 D->setAccess(AS_public); 5453 CurContext->addDecl(D); 5454 5455 return DeclPtrTy::make(D); 5456} 5457 5458Sema::DeclPtrTy 5459Sema::ActOnFriendFunctionDecl(Scope *S, 5460 Declarator &D, 5461 bool IsDefinition, 5462 MultiTemplateParamsArg TemplateParams) { 5463 const DeclSpec &DS = D.getDeclSpec(); 5464 5465 assert(DS.isFriendSpecified()); 5466 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5467 5468 SourceLocation Loc = D.getIdentifierLoc(); 5469 TypeSourceInfo *TInfo = 0; 5470 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5471 5472 // C++ [class.friend]p1 5473 // A friend of a class is a function or class.... 5474 // Note that this sees through typedefs, which is intended. 5475 // It *doesn't* see through dependent types, which is correct 5476 // according to [temp.arg.type]p3: 5477 // If a declaration acquires a function type through a 5478 // type dependent on a template-parameter and this causes 5479 // a declaration that does not use the syntactic form of a 5480 // function declarator to have a function type, the program 5481 // is ill-formed. 5482 if (!T->isFunctionType()) { 5483 Diag(Loc, diag::err_unexpected_friend); 5484 5485 // It might be worthwhile to try to recover by creating an 5486 // appropriate declaration. 5487 return DeclPtrTy(); 5488 } 5489 5490 // C++ [namespace.memdef]p3 5491 // - If a friend declaration in a non-local class first declares a 5492 // class or function, the friend class or function is a member 5493 // of the innermost enclosing namespace. 5494 // - The name of the friend is not found by simple name lookup 5495 // until a matching declaration is provided in that namespace 5496 // scope (either before or after the class declaration granting 5497 // friendship). 5498 // - If a friend function is called, its name may be found by the 5499 // name lookup that considers functions from namespaces and 5500 // classes associated with the types of the function arguments. 5501 // - When looking for a prior declaration of a class or a function 5502 // declared as a friend, scopes outside the innermost enclosing 5503 // namespace scope are not considered. 5504 5505 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 5506 DeclarationName Name = GetNameForDeclarator(D); 5507 assert(Name); 5508 5509 // The context we found the declaration in, or in which we should 5510 // create the declaration. 5511 DeclContext *DC; 5512 5513 // FIXME: handle local classes 5514 5515 // Recover from invalid scope qualifiers as if they just weren't there. 5516 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 5517 ForRedeclaration); 5518 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 5519 // FIXME: RequireCompleteDeclContext 5520 DC = computeDeclContext(ScopeQual); 5521 5522 // FIXME: handle dependent contexts 5523 if (!DC) return DeclPtrTy(); 5524 5525 LookupQualifiedName(Previous, DC); 5526 5527 // If searching in that context implicitly found a declaration in 5528 // a different context, treat it like it wasn't found at all. 5529 // TODO: better diagnostics for this case. Suggesting the right 5530 // qualified scope would be nice... 5531 // FIXME: getRepresentativeDecl() is not right here at all 5532 if (Previous.empty() || 5533 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 5534 D.setInvalidType(); 5535 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 5536 return DeclPtrTy(); 5537 } 5538 5539 // C++ [class.friend]p1: A friend of a class is a function or 5540 // class that is not a member of the class . . . 5541 if (DC->Equals(CurContext)) 5542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5543 5544 // Otherwise walk out to the nearest namespace scope looking for matches. 5545 } else { 5546 // TODO: handle local class contexts. 5547 5548 DC = CurContext; 5549 while (true) { 5550 // Skip class contexts. If someone can cite chapter and verse 5551 // for this behavior, that would be nice --- it's what GCC and 5552 // EDG do, and it seems like a reasonable intent, but the spec 5553 // really only says that checks for unqualified existing 5554 // declarations should stop at the nearest enclosing namespace, 5555 // not that they should only consider the nearest enclosing 5556 // namespace. 5557 while (DC->isRecord()) 5558 DC = DC->getParent(); 5559 5560 LookupQualifiedName(Previous, DC); 5561 5562 // TODO: decide what we think about using declarations. 5563 if (!Previous.empty()) 5564 break; 5565 5566 if (DC->isFileContext()) break; 5567 DC = DC->getParent(); 5568 } 5569 5570 // C++ [class.friend]p1: A friend of a class is a function or 5571 // class that is not a member of the class . . . 5572 // C++0x changes this for both friend types and functions. 5573 // Most C++ 98 compilers do seem to give an error here, so 5574 // we do, too. 5575 if (!Previous.empty() && DC->Equals(CurContext) 5576 && !getLangOptions().CPlusPlus0x) 5577 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5578 } 5579 5580 if (DC->isFileContext()) { 5581 // This implies that it has to be an operator or function. 5582 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 5583 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 5584 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 5585 Diag(Loc, diag::err_introducing_special_friend) << 5586 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 5587 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 5588 return DeclPtrTy(); 5589 } 5590 } 5591 5592 bool Redeclaration = false; 5593 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 5594 move(TemplateParams), 5595 IsDefinition, 5596 Redeclaration); 5597 if (!ND) return DeclPtrTy(); 5598 5599 assert(ND->getDeclContext() == DC); 5600 assert(ND->getLexicalDeclContext() == CurContext); 5601 5602 // Add the function declaration to the appropriate lookup tables, 5603 // adjusting the redeclarations list as necessary. We don't 5604 // want to do this yet if the friending class is dependent. 5605 // 5606 // Also update the scope-based lookup if the target context's 5607 // lookup context is in lexical scope. 5608 if (!CurContext->isDependentContext()) { 5609 DC = DC->getLookupContext(); 5610 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 5611 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5612 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 5613 } 5614 5615 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 5616 D.getIdentifierLoc(), ND, 5617 DS.getFriendSpecLoc()); 5618 FrD->setAccess(AS_public); 5619 CurContext->addDecl(FrD); 5620 5621 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) 5622 FrD->setSpecialization(true); 5623 5624 return DeclPtrTy::make(ND); 5625} 5626 5627void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 5628 AdjustDeclIfTemplate(dcl); 5629 5630 Decl *Dcl = dcl.getAs<Decl>(); 5631 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 5632 if (!Fn) { 5633 Diag(DelLoc, diag::err_deleted_non_function); 5634 return; 5635 } 5636 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 5637 Diag(DelLoc, diag::err_deleted_decl_not_first); 5638 Diag(Prev->getLocation(), diag::note_previous_declaration); 5639 // If the declaration wasn't the first, we delete the function anyway for 5640 // recovery. 5641 } 5642 Fn->setDeleted(); 5643} 5644 5645static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 5646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 5647 ++CI) { 5648 Stmt *SubStmt = *CI; 5649 if (!SubStmt) 5650 continue; 5651 if (isa<ReturnStmt>(SubStmt)) 5652 Self.Diag(SubStmt->getSourceRange().getBegin(), 5653 diag::err_return_in_constructor_handler); 5654 if (!isa<Expr>(SubStmt)) 5655 SearchForReturnInStmt(Self, SubStmt); 5656 } 5657} 5658 5659void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 5660 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 5661 CXXCatchStmt *Handler = TryBlock->getHandler(I); 5662 SearchForReturnInStmt(*this, Handler); 5663 } 5664} 5665 5666bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5667 const CXXMethodDecl *Old) { 5668 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 5669 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 5670 5671 if (Context.hasSameType(NewTy, OldTy)) 5672 return false; 5673 5674 // Check if the return types are covariant 5675 QualType NewClassTy, OldClassTy; 5676 5677 /// Both types must be pointers or references to classes. 5678 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 5679 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 5680 NewClassTy = NewPT->getPointeeType(); 5681 OldClassTy = OldPT->getPointeeType(); 5682 } 5683 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 5684 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 5685 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 5686 NewClassTy = NewRT->getPointeeType(); 5687 OldClassTy = OldRT->getPointeeType(); 5688 } 5689 } 5690 } 5691 5692 // The return types aren't either both pointers or references to a class type. 5693 if (NewClassTy.isNull()) { 5694 Diag(New->getLocation(), 5695 diag::err_different_return_type_for_overriding_virtual_function) 5696 << New->getDeclName() << NewTy << OldTy; 5697 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5698 5699 return true; 5700 } 5701 5702 // C++ [class.virtual]p6: 5703 // If the return type of D::f differs from the return type of B::f, the 5704 // class type in the return type of D::f shall be complete at the point of 5705 // declaration of D::f or shall be the class type D. 5706 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 5707 if (!RT->isBeingDefined() && 5708 RequireCompleteType(New->getLocation(), NewClassTy, 5709 PDiag(diag::err_covariant_return_incomplete) 5710 << New->getDeclName())) 5711 return true; 5712 } 5713 5714 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 5715 // Check if the new class derives from the old class. 5716 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 5717 Diag(New->getLocation(), 5718 diag::err_covariant_return_not_derived) 5719 << New->getDeclName() << NewTy << OldTy; 5720 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5721 return true; 5722 } 5723 5724 // Check if we the conversion from derived to base is valid. 5725 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 5726 diag::err_covariant_return_inaccessible_base, 5727 diag::err_covariant_return_ambiguous_derived_to_base_conv, 5728 // FIXME: Should this point to the return type? 5729 New->getLocation(), SourceRange(), New->getDeclName())) { 5730 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5731 return true; 5732 } 5733 } 5734 5735 // The qualifiers of the return types must be the same. 5736 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 5737 Diag(New->getLocation(), 5738 diag::err_covariant_return_type_different_qualifications) 5739 << New->getDeclName() << NewTy << OldTy; 5740 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5741 return true; 5742 }; 5743 5744 5745 // The new class type must have the same or less qualifiers as the old type. 5746 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 5747 Diag(New->getLocation(), 5748 diag::err_covariant_return_type_class_type_more_qualified) 5749 << New->getDeclName() << NewTy << OldTy; 5750 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5751 return true; 5752 }; 5753 5754 return false; 5755} 5756 5757bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5758 const CXXMethodDecl *Old) 5759{ 5760 if (Old->hasAttr<FinalAttr>()) { 5761 Diag(New->getLocation(), diag::err_final_function_overridden) 5762 << New->getDeclName(); 5763 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5764 return true; 5765 } 5766 5767 return false; 5768} 5769 5770/// \brief Mark the given method pure. 5771/// 5772/// \param Method the method to be marked pure. 5773/// 5774/// \param InitRange the source range that covers the "0" initializer. 5775bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 5776 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 5777 Method->setPure(); 5778 5779 // A class is abstract if at least one function is pure virtual. 5780 Method->getParent()->setAbstract(true); 5781 return false; 5782 } 5783 5784 if (!Method->isInvalidDecl()) 5785 Diag(Method->getLocation(), diag::err_non_virtual_pure) 5786 << Method->getDeclName() << InitRange; 5787 return true; 5788} 5789 5790/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 5791/// an initializer for the out-of-line declaration 'Dcl'. The scope 5792/// is a fresh scope pushed for just this purpose. 5793/// 5794/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 5795/// static data member of class X, names should be looked up in the scope of 5796/// class X. 5797void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5798 // If there is no declaration, there was an error parsing it. 5799 Decl *D = Dcl.getAs<Decl>(); 5800 if (D == 0) return; 5801 5802 // We should only get called for declarations with scope specifiers, like: 5803 // int foo::bar; 5804 assert(D->isOutOfLine()); 5805 EnterDeclaratorContext(S, D->getDeclContext()); 5806} 5807 5808/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 5809/// initializer for the out-of-line declaration 'Dcl'. 5810void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 5811 // If there is no declaration, there was an error parsing it. 5812 Decl *D = Dcl.getAs<Decl>(); 5813 if (D == 0) return; 5814 5815 assert(D->isOutOfLine()); 5816 ExitDeclaratorContext(S); 5817} 5818 5819/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 5820/// C++ if/switch/while/for statement. 5821/// e.g: "if (int x = f()) {...}" 5822Action::DeclResult 5823Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 5824 // C++ 6.4p2: 5825 // The declarator shall not specify a function or an array. 5826 // The type-specifier-seq shall not contain typedef and shall not declare a 5827 // new class or enumeration. 5828 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5829 "Parser allowed 'typedef' as storage class of condition decl."); 5830 5831 TypeSourceInfo *TInfo = 0; 5832 TagDecl *OwnedTag = 0; 5833 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 5834 5835 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 5836 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 5837 // would be created and CXXConditionDeclExpr wants a VarDecl. 5838 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 5839 << D.getSourceRange(); 5840 return DeclResult(); 5841 } else if (OwnedTag && OwnedTag->isDefinition()) { 5842 // The type-specifier-seq shall not declare a new class or enumeration. 5843 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 5844 } 5845 5846 DeclPtrTy Dcl = ActOnDeclarator(S, D); 5847 if (!Dcl) 5848 return DeclResult(); 5849 5850 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 5851 VD->setDeclaredInCondition(true); 5852 return Dcl; 5853} 5854 5855void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc, 5856 CXXMethodDecl *MD) { 5857 // Ignore dependent types. 5858 if (MD->isDependentContext()) 5859 return; 5860 5861 CXXRecordDecl *RD = MD->getParent(); 5862 5863 // Ignore classes without a vtable. 5864 if (!RD->isDynamicClass()) 5865 return; 5866 5867 // Ignore declarations that are not definitions. 5868 if (!MD->isThisDeclarationADefinition()) 5869 return; 5870 5871 if (isa<CXXConstructorDecl>(MD)) { 5872 switch (MD->getParent()->getTemplateSpecializationKind()) { 5873 case TSK_Undeclared: 5874 case TSK_ExplicitSpecialization: 5875 // Classes that aren't instantiations of templates don't need their 5876 // virtual methods marked until we see the definition of the key 5877 // function. 5878 return; 5879 5880 case TSK_ImplicitInstantiation: 5881 case TSK_ExplicitInstantiationDeclaration: 5882 case TSK_ExplicitInstantiationDefinition: 5883 // This is a constructor of a class template; mark all of the virtual 5884 // members as referenced to ensure that they get instantiatied. 5885 break; 5886 } 5887 } else if (!MD->isOutOfLine()) { 5888 // Consider only out-of-line definitions of member functions. When we see 5889 // an inline definition, it's too early to compute the key function. 5890 return; 5891 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) { 5892 // If this is not the key function, we don't need to mark virtual members. 5893 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) 5894 return; 5895 } else { 5896 // The class has no key function, so we've already noted that we need to 5897 // mark the virtual members of this class. 5898 return; 5899 } 5900 5901 // We will need to mark all of the virtual members as referenced to build the 5902 // vtable. 5903 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc)); 5904} 5905 5906bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() { 5907 if (ClassesWithUnmarkedVirtualMembers.empty()) 5908 return false; 5909 5910 while (!ClassesWithUnmarkedVirtualMembers.empty()) { 5911 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first; 5912 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second; 5913 ClassesWithUnmarkedVirtualMembers.pop_back(); 5914 MarkVirtualMembersReferenced(Loc, RD); 5915 } 5916 5917 return true; 5918} 5919 5920void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) { 5921 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 5922 e = RD->method_end(); i != e; ++i) { 5923 CXXMethodDecl *MD = *i; 5924 5925 // C++ [basic.def.odr]p2: 5926 // [...] A virtual member function is used if it is not pure. [...] 5927 if (MD->isVirtual() && !MD->isPure()) 5928 MarkDeclarationReferenced(Loc, MD); 5929 } 5930} 5931 5932