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