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