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