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