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