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