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