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