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