SemaDeclCXX.cpp revision 2b51138433969b163e6899836bba6c14ec2397cb
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 "Sema.h" 15#include "SemaInherit.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/TypeOrdering.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25#include "llvm/Support/Compiler.h" 26#include <algorithm> // for std::equal 27#include <map> 28 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// CheckDefaultArgumentVisitor 33//===----------------------------------------------------------------------===// 34 35namespace { 36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 37 /// the default argument of a parameter to determine whether it 38 /// contains any ill-formed subexpressions. For example, this will 39 /// diagnose the use of local variables or parameters within the 40 /// default argument expression. 41 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 42 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 43 Expr *DefaultArg; 44 Sema *S; 45 46 public: 47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 48 : DefaultArg(defarg), S(s) {} 49 50 bool VisitExpr(Expr *Node); 51 bool VisitDeclRefExpr(DeclRefExpr *DRE); 52 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 53 }; 54 55 /// VisitExpr - Visit all of the children of this expression. 56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 57 bool IsInvalid = false; 58 for (Stmt::child_iterator I = Node->child_begin(), 59 E = Node->child_end(); I != E; ++I) 60 IsInvalid |= Visit(*I); 61 return IsInvalid; 62 } 63 64 /// VisitDeclRefExpr - Visit a reference to a declaration, to 65 /// determine whether this declaration can be used in the default 66 /// argument expression. 67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 68 NamedDecl *Decl = DRE->getDecl(); 69 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 70 // C++ [dcl.fct.default]p9 71 // Default arguments are evaluated each time the function is 72 // called. The order of evaluation of function arguments is 73 // unspecified. Consequently, parameters of a function shall not 74 // be used in default argument expressions, even if they are not 75 // evaluated. Parameters of a function declared before a default 76 // argument expression are in scope and can hide namespace and 77 // class member names. 78 return S->Diag(DRE->getSourceRange().getBegin(), 79 diag::err_param_default_argument_references_param) 80 << Param->getDeclName() << DefaultArg->getSourceRange(); 81 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 82 // C++ [dcl.fct.default]p7 83 // Local variables shall not be used in default argument 84 // expressions. 85 if (VDecl->isBlockVarDecl()) 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_local) 88 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 89 } 90 91 return false; 92 } 93 94 /// VisitCXXThisExpr - Visit a C++ "this" expression. 95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 96 // C++ [dcl.fct.default]p8: 97 // The keyword this shall not be used in a default argument of a 98 // member function. 99 return S->Diag(ThisE->getSourceRange().getBegin(), 100 diag::err_param_default_argument_references_this) 101 << ThisE->getSourceRange(); 102 } 103} 104 105bool 106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 107 SourceLocation EqualLoc) { 108 QualType ParamType = Param->getType(); 109 110 if (RequireCompleteType(Param->getLocation(), Param->getType(), 111 diag::err_typecheck_decl_incomplete_type)) { 112 Param->setInvalidDecl(); 113 return true; 114 } 115 116 Expr *Arg = (Expr *)DefaultArg.get(); 117 118 // C++ [dcl.fct.default]p5 119 // A default argument expression is implicitly converted (clause 120 // 4) to the parameter type. The default argument expression has 121 // the same semantic constraints as the initializer expression in 122 // a declaration of a variable of the parameter type, using the 123 // copy-initialization semantics (8.5). 124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 125 Param->getDeclName(), /*DirectInit=*/false)) 126 return true; 127 128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 129 130 // Okay: add the default argument to the parameter 131 Param->setDefaultArg(Arg); 132 133 DefaultArg.release(); 134 135 return false; 136} 137 138/// ActOnParamDefaultArgument - Check whether the default argument 139/// provided for a function parameter is well-formed. If so, attach it 140/// to the parameter declaration. 141void 142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 143 ExprArg defarg) { 144 if (!param || !defarg.get()) 145 return; 146 147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 148 UnparsedDefaultArgLocs.erase(Param); 149 150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 151 QualType ParamType = Param->getType(); 152 153 // Default arguments are only permitted in C++ 154 if (!getLangOptions().CPlusPlus) { 155 Diag(EqualLoc, diag::err_param_default_argument) 156 << DefaultArg->getSourceRange(); 157 Param->setInvalidDecl(); 158 return; 159 } 160 161 // Check that the default argument is well-formed 162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 163 if (DefaultArgChecker.Visit(DefaultArg.get())) { 164 Param->setInvalidDecl(); 165 return; 166 } 167 168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 169} 170 171/// ActOnParamUnparsedDefaultArgument - We've seen a default 172/// argument for a function parameter, but we can't parse it yet 173/// because we're inside a class definition. Note that this default 174/// argument will be parsed later. 175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 176 SourceLocation EqualLoc, 177 SourceLocation ArgLoc) { 178 if (!param) 179 return; 180 181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 182 if (Param) 183 Param->setUnparsedDefaultArg(); 184 185 UnparsedDefaultArgLocs[Param] = ArgLoc; 186} 187 188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 189/// the default argument for the parameter param failed. 190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 191 if (!param) 192 return; 193 194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 195 196 Param->setInvalidDecl(); 197 198 UnparsedDefaultArgLocs.erase(Param); 199} 200 201/// CheckExtraCXXDefaultArguments - Check for any extra default 202/// arguments in the declarator, which is not a function declaration 203/// or definition and therefore is not permitted to have default 204/// arguments. This routine should be invoked for every declarator 205/// that is not a function declaration or definition. 206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 207 // C++ [dcl.fct.default]p3 208 // A default argument expression shall be specified only in the 209 // parameter-declaration-clause of a function declaration or in a 210 // template-parameter (14.1). It shall not be specified for a 211 // parameter pack. If it is specified in a 212 // parameter-declaration-clause, it shall not occur within a 213 // declarator or abstract-declarator of a parameter-declaration. 214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 215 DeclaratorChunk &chunk = D.getTypeObject(i); 216 if (chunk.Kind == DeclaratorChunk::Function) { 217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 218 ParmVarDecl *Param = 219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 220 if (Param->hasUnparsedDefaultArg()) { 221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 224 delete Toks; 225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 226 } else if (Param->getDefaultArg()) { 227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 228 << Param->getDefaultArg()->getSourceRange(); 229 Param->setDefaultArg(0); 230 } 231 } 232 } 233 } 234} 235 236// MergeCXXFunctionDecl - Merge two declarations of the same C++ 237// function, once we already know that they have the same 238// type. Subroutine of MergeFunctionDecl. Returns true if there was an 239// error, false otherwise. 240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 241 bool Invalid = false; 242 243 // C++ [dcl.fct.default]p4: 244 // For non-template functions, default arguments can be added in 245 // later declarations of a function in the same 246 // scope. Declarations in different scopes have completely 247 // distinct sets of default arguments. That is, declarations in 248 // inner scopes do not acquire default arguments from 249 // declarations in outer scopes, and vice versa. In a given 250 // function declaration, all parameters subsequent to a 251 // parameter with a default argument shall have default 252 // arguments supplied in this or previous declarations. A 253 // default argument shall not be redefined by a later 254 // declaration (not even to the same value). 255 // 256 // C++ [dcl.fct.default]p6: 257 // Except for member functions of class templates, the default arguments 258 // in a member function definition that appears outside of the class 259 // definition are added to the set of default arguments provided by the 260 // member function declaration in the class definition. 261 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 262 ParmVarDecl *OldParam = Old->getParamDecl(p); 263 ParmVarDecl *NewParam = New->getParamDecl(p); 264 265 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 266 Diag(NewParam->getLocation(), 267 diag::err_param_default_argument_redefinition) 268 << NewParam->getDefaultArgRange(); 269 270 // Look for the function declaration where the default argument was 271 // actually written, which may be a declaration prior to Old. 272 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 273 Older; Older = Older->getPreviousDeclaration()) { 274 if (!Older->getParamDecl(p)->hasDefaultArg()) 275 break; 276 277 OldParam = Older->getParamDecl(p); 278 } 279 280 Diag(OldParam->getLocation(), diag::note_previous_definition) 281 << OldParam->getDefaultArgRange(); 282 Invalid = true; 283 } else if (OldParam->hasDefaultArg()) { 284 // Merge the old default argument into the new parameter 285 if (OldParam->hasUninstantiatedDefaultArg()) 286 NewParam->setUninstantiatedDefaultArg( 287 OldParam->getUninstantiatedDefaultArg()); 288 else 289 NewParam->setDefaultArg(OldParam->getDefaultArg()); 290 } else if (NewParam->hasDefaultArg()) { 291 if (New->getDescribedFunctionTemplate()) { 292 // Paragraph 4, quoted above, only applies to non-template functions. 293 Diag(NewParam->getLocation(), 294 diag::err_param_default_argument_template_redecl) 295 << NewParam->getDefaultArgRange(); 296 Diag(Old->getLocation(), diag::note_template_prev_declaration) 297 << false; 298 } else if (New->getDeclContext()->isDependentContext()) { 299 // C++ [dcl.fct.default]p6 (DR217): 300 // Default arguments for a member function of a class template shall 301 // be specified on the initial declaration of the member function 302 // within the class template. 303 // 304 // Reading the tea leaves a bit in DR217 and its reference to DR205 305 // leads me to the conclusion that one cannot add default function 306 // arguments for an out-of-line definition of a member function of a 307 // dependent type. 308 int WhichKind = 2; 309 if (CXXRecordDecl *Record 310 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 311 if (Record->getDescribedClassTemplate()) 312 WhichKind = 0; 313 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 314 WhichKind = 1; 315 else 316 WhichKind = 2; 317 } 318 319 Diag(NewParam->getLocation(), 320 diag::err_param_default_argument_member_template_redecl) 321 << WhichKind 322 << NewParam->getDefaultArgRange(); 323 } 324 } 325 } 326 327 if (CheckEquivalentExceptionSpec( 328 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(), 329 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) { 330 Invalid = true; 331 } 332 333 return Invalid; 334} 335 336/// CheckCXXDefaultArguments - Verify that the default arguments for a 337/// function declaration are well-formed according to C++ 338/// [dcl.fct.default]. 339void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 340 unsigned NumParams = FD->getNumParams(); 341 unsigned p; 342 343 // Find first parameter with a default argument 344 for (p = 0; p < NumParams; ++p) { 345 ParmVarDecl *Param = FD->getParamDecl(p); 346 if (Param->hasDefaultArg()) 347 break; 348 } 349 350 // C++ [dcl.fct.default]p4: 351 // In a given function declaration, all parameters 352 // subsequent to a parameter with a default argument shall 353 // have default arguments supplied in this or previous 354 // declarations. A default argument shall not be redefined 355 // by a later declaration (not even to the same value). 356 unsigned LastMissingDefaultArg = 0; 357 for (; p < NumParams; ++p) { 358 ParmVarDecl *Param = FD->getParamDecl(p); 359 if (!Param->hasDefaultArg()) { 360 if (Param->isInvalidDecl()) 361 /* We already complained about this parameter. */; 362 else if (Param->getIdentifier()) 363 Diag(Param->getLocation(), 364 diag::err_param_default_argument_missing_name) 365 << Param->getIdentifier(); 366 else 367 Diag(Param->getLocation(), 368 diag::err_param_default_argument_missing); 369 370 LastMissingDefaultArg = p; 371 } 372 } 373 374 if (LastMissingDefaultArg > 0) { 375 // Some default arguments were missing. Clear out all of the 376 // default arguments up to (and including) the last missing 377 // default argument, so that we leave the function parameters 378 // in a semantically valid state. 379 for (p = 0; p <= LastMissingDefaultArg; ++p) { 380 ParmVarDecl *Param = FD->getParamDecl(p); 381 if (Param->hasDefaultArg()) { 382 if (!Param->hasUnparsedDefaultArg()) 383 Param->getDefaultArg()->Destroy(Context); 384 Param->setDefaultArg(0); 385 } 386 } 387 } 388} 389 390/// isCurrentClassName - Determine whether the identifier II is the 391/// name of the class type currently being defined. In the case of 392/// nested classes, this will only return true if II is the name of 393/// the innermost class. 394bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 395 const CXXScopeSpec *SS) { 396 CXXRecordDecl *CurDecl; 397 if (SS && SS->isSet() && !SS->isInvalid()) { 398 DeclContext *DC = computeDeclContext(*SS, true); 399 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 400 } else 401 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 402 403 if (CurDecl) 404 return &II == CurDecl->getIdentifier(); 405 else 406 return false; 407} 408 409/// \brief Check the validity of a C++ base class specifier. 410/// 411/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 412/// and returns NULL otherwise. 413CXXBaseSpecifier * 414Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 415 SourceRange SpecifierRange, 416 bool Virtual, AccessSpecifier Access, 417 QualType BaseType, 418 SourceLocation BaseLoc) { 419 // C++ [class.union]p1: 420 // A union shall not have base classes. 421 if (Class->isUnion()) { 422 Diag(Class->getLocation(), diag::err_base_clause_on_union) 423 << SpecifierRange; 424 return 0; 425 } 426 427 if (BaseType->isDependentType()) 428 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 429 Class->getTagKind() == RecordDecl::TK_class, 430 Access, BaseType); 431 432 // Base specifiers must be record types. 433 if (!BaseType->isRecordType()) { 434 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 435 return 0; 436 } 437 438 // C++ [class.union]p1: 439 // A union shall not be used as a base class. 440 if (BaseType->isUnionType()) { 441 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 442 return 0; 443 } 444 445 // C++ [class.derived]p2: 446 // The class-name in a base-specifier shall not be an incompletely 447 // defined class. 448 if (RequireCompleteType(BaseLoc, BaseType, 449 PDiag(diag::err_incomplete_base_class) 450 << SpecifierRange)) 451 return 0; 452 453 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 454 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 455 assert(BaseDecl && "Record type has no declaration"); 456 BaseDecl = BaseDecl->getDefinition(Context); 457 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 458 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 459 assert(CXXBaseDecl && "Base type is not a C++ type"); 460 if (!CXXBaseDecl->isEmpty()) 461 Class->setEmpty(false); 462 if (CXXBaseDecl->isPolymorphic()) 463 Class->setPolymorphic(true); 464 465 // C++ [dcl.init.aggr]p1: 466 // An aggregate is [...] a class with [...] no base classes [...]. 467 Class->setAggregate(false); 468 Class->setPOD(false); 469 470 if (Virtual) { 471 // C++ [class.ctor]p5: 472 // A constructor is trivial if its class has no virtual base classes. 473 Class->setHasTrivialConstructor(false); 474 475 // C++ [class.copy]p6: 476 // A copy constructor is trivial if its class has no virtual base classes. 477 Class->setHasTrivialCopyConstructor(false); 478 479 // C++ [class.copy]p11: 480 // A copy assignment operator is trivial if its class has no virtual 481 // base classes. 482 Class->setHasTrivialCopyAssignment(false); 483 484 // C++0x [meta.unary.prop] is_empty: 485 // T is a class type, but not a union type, with ... no virtual base 486 // classes 487 Class->setEmpty(false); 488 } else { 489 // C++ [class.ctor]p5: 490 // A constructor is trivial if all the direct base classes of its 491 // class have trivial constructors. 492 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 493 Class->setHasTrivialConstructor(false); 494 495 // C++ [class.copy]p6: 496 // A copy constructor is trivial if all the direct base classes of its 497 // class have trivial copy constructors. 498 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 499 Class->setHasTrivialCopyConstructor(false); 500 501 // C++ [class.copy]p11: 502 // A copy assignment operator is trivial if all the direct base classes 503 // of its class have trivial copy assignment operators. 504 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 505 Class->setHasTrivialCopyAssignment(false); 506 } 507 508 // C++ [class.ctor]p3: 509 // A destructor is trivial if all the direct base classes of its class 510 // have trivial destructors. 511 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 512 Class->setHasTrivialDestructor(false); 513 514 // Create the base specifier. 515 // FIXME: Allocate via ASTContext? 516 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 517 Class->getTagKind() == RecordDecl::TK_class, 518 Access, BaseType); 519} 520 521/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 522/// one entry in the base class list of a class specifier, for 523/// example: 524/// class foo : public bar, virtual private baz { 525/// 'public bar' and 'virtual private baz' are each base-specifiers. 526Sema::BaseResult 527Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 528 bool Virtual, AccessSpecifier Access, 529 TypeTy *basetype, SourceLocation BaseLoc) { 530 if (!classdecl) 531 return true; 532 533 AdjustDeclIfTemplate(classdecl); 534 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 535 QualType BaseType = GetTypeFromParser(basetype); 536 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 537 Virtual, Access, 538 BaseType, BaseLoc)) 539 return BaseSpec; 540 541 return true; 542} 543 544/// \brief Performs the actual work of attaching the given base class 545/// specifiers to a C++ class. 546bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 547 unsigned NumBases) { 548 if (NumBases == 0) 549 return false; 550 551 // Used to keep track of which base types we have already seen, so 552 // that we can properly diagnose redundant direct base types. Note 553 // that the key is always the unqualified canonical type of the base 554 // class. 555 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 556 557 // Copy non-redundant base specifiers into permanent storage. 558 unsigned NumGoodBases = 0; 559 bool Invalid = false; 560 for (unsigned idx = 0; idx < NumBases; ++idx) { 561 QualType NewBaseType 562 = Context.getCanonicalType(Bases[idx]->getType()); 563 NewBaseType = NewBaseType.getUnqualifiedType(); 564 565 if (KnownBaseTypes[NewBaseType]) { 566 // C++ [class.mi]p3: 567 // A class shall not be specified as a direct base class of a 568 // derived class more than once. 569 Diag(Bases[idx]->getSourceRange().getBegin(), 570 diag::err_duplicate_base_class) 571 << KnownBaseTypes[NewBaseType]->getType() 572 << Bases[idx]->getSourceRange(); 573 574 // Delete the duplicate base class specifier; we're going to 575 // overwrite its pointer later. 576 Context.Deallocate(Bases[idx]); 577 578 Invalid = true; 579 } else { 580 // Okay, add this new base class. 581 KnownBaseTypes[NewBaseType] = Bases[idx]; 582 Bases[NumGoodBases++] = Bases[idx]; 583 } 584 } 585 586 // Attach the remaining base class specifiers to the derived class. 587 Class->setBases(Context, Bases, NumGoodBases); 588 589 // Delete the remaining (good) base class specifiers, since their 590 // data has been copied into the CXXRecordDecl. 591 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 592 Context.Deallocate(Bases[idx]); 593 594 return Invalid; 595} 596 597/// ActOnBaseSpecifiers - Attach the given base specifiers to the 598/// class, after checking whether there are any duplicate base 599/// classes. 600void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 601 unsigned NumBases) { 602 if (!ClassDecl || !Bases || !NumBases) 603 return; 604 605 AdjustDeclIfTemplate(ClassDecl); 606 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 607 (CXXBaseSpecifier**)(Bases), NumBases); 608} 609 610//===----------------------------------------------------------------------===// 611// C++ class member Handling 612//===----------------------------------------------------------------------===// 613 614/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 615/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 616/// bitfield width if there is one and 'InitExpr' specifies the initializer if 617/// any. 618Sema::DeclPtrTy 619Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 620 MultiTemplateParamsArg TemplateParameterLists, 621 ExprTy *BW, ExprTy *InitExpr, bool Deleted) { 622 const DeclSpec &DS = D.getDeclSpec(); 623 DeclarationName Name = GetNameForDeclarator(D); 624 Expr *BitWidth = static_cast<Expr*>(BW); 625 Expr *Init = static_cast<Expr*>(InitExpr); 626 SourceLocation Loc = D.getIdentifierLoc(); 627 628 bool isFunc = D.isFunctionDeclarator(); 629 630 assert(!DS.isFriendSpecified()); 631 632 // C++ 9.2p6: A member shall not be declared to have automatic storage 633 // duration (auto, register) or with the extern storage-class-specifier. 634 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 635 // data members and cannot be applied to names declared const or static, 636 // and cannot be applied to reference members. 637 switch (DS.getStorageClassSpec()) { 638 case DeclSpec::SCS_unspecified: 639 case DeclSpec::SCS_typedef: 640 case DeclSpec::SCS_static: 641 // FALL THROUGH. 642 break; 643 case DeclSpec::SCS_mutable: 644 if (isFunc) { 645 if (DS.getStorageClassSpecLoc().isValid()) 646 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 647 else 648 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 649 650 // FIXME: It would be nicer if the keyword was ignored only for this 651 // declarator. Otherwise we could get follow-up errors. 652 D.getMutableDeclSpec().ClearStorageClassSpecs(); 653 } else { 654 QualType T = GetTypeForDeclarator(D, S); 655 diag::kind err = static_cast<diag::kind>(0); 656 if (T->isReferenceType()) 657 err = diag::err_mutable_reference; 658 else if (T.isConstQualified()) 659 err = diag::err_mutable_const; 660 if (err != 0) { 661 if (DS.getStorageClassSpecLoc().isValid()) 662 Diag(DS.getStorageClassSpecLoc(), err); 663 else 664 Diag(DS.getThreadSpecLoc(), err); 665 // FIXME: It would be nicer if the keyword was ignored only for this 666 // declarator. Otherwise we could get follow-up errors. 667 D.getMutableDeclSpec().ClearStorageClassSpecs(); 668 } 669 } 670 break; 671 default: 672 if (DS.getStorageClassSpecLoc().isValid()) 673 Diag(DS.getStorageClassSpecLoc(), 674 diag::err_storageclass_invalid_for_member); 675 else 676 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 677 D.getMutableDeclSpec().ClearStorageClassSpecs(); 678 } 679 680 if (!isFunc && 681 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 682 D.getNumTypeObjects() == 0) { 683 // Check also for this case: 684 // 685 // typedef int f(); 686 // f a; 687 // 688 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 689 isFunc = TDType->isFunctionType(); 690 } 691 692 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 693 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 694 !isFunc); 695 696 Decl *Member; 697 if (isInstField) { 698 // FIXME: Check for template parameters! 699 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 700 AS); 701 assert(Member && "HandleField never returns null"); 702 } else { 703 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false) 704 .getAs<Decl>(); 705 if (!Member) { 706 if (BitWidth) DeleteExpr(BitWidth); 707 return DeclPtrTy(); 708 } 709 710 // Non-instance-fields can't have a bitfield. 711 if (BitWidth) { 712 if (Member->isInvalidDecl()) { 713 // don't emit another diagnostic. 714 } else if (isa<VarDecl>(Member)) { 715 // C++ 9.6p3: A bit-field shall not be a static member. 716 // "static member 'A' cannot be a bit-field" 717 Diag(Loc, diag::err_static_not_bitfield) 718 << Name << BitWidth->getSourceRange(); 719 } else if (isa<TypedefDecl>(Member)) { 720 // "typedef member 'x' cannot be a bit-field" 721 Diag(Loc, diag::err_typedef_not_bitfield) 722 << Name << BitWidth->getSourceRange(); 723 } else { 724 // A function typedef ("typedef int f(); f a;"). 725 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 726 Diag(Loc, diag::err_not_integral_type_bitfield) 727 << Name << cast<ValueDecl>(Member)->getType() 728 << BitWidth->getSourceRange(); 729 } 730 731 DeleteExpr(BitWidth); 732 BitWidth = 0; 733 Member->setInvalidDecl(); 734 } 735 736 Member->setAccess(AS); 737 738 // If we have declared a member function template, set the access of the 739 // templated declaration as well. 740 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 741 FunTmpl->getTemplatedDecl()->setAccess(AS); 742 } 743 744 assert((Name || isInstField) && "No identifier for non-field ?"); 745 746 if (Init) 747 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 748 if (Deleted) // FIXME: Source location is not very good. 749 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 750 751 if (isInstField) { 752 FieldCollector->Add(cast<FieldDecl>(Member)); 753 return DeclPtrTy(); 754 } 755 return DeclPtrTy::make(Member); 756} 757 758/// ActOnMemInitializer - Handle a C++ member initializer. 759Sema::MemInitResult 760Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 761 Scope *S, 762 const CXXScopeSpec &SS, 763 IdentifierInfo *MemberOrBase, 764 TypeTy *TemplateTypeTy, 765 SourceLocation IdLoc, 766 SourceLocation LParenLoc, 767 ExprTy **Args, unsigned NumArgs, 768 SourceLocation *CommaLocs, 769 SourceLocation RParenLoc) { 770 if (!ConstructorD) 771 return true; 772 773 AdjustDeclIfTemplate(ConstructorD); 774 775 CXXConstructorDecl *Constructor 776 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 777 if (!Constructor) { 778 // The user wrote a constructor initializer on a function that is 779 // not a C++ constructor. Ignore the error for now, because we may 780 // have more member initializers coming; we'll diagnose it just 781 // once in ActOnMemInitializers. 782 return true; 783 } 784 785 CXXRecordDecl *ClassDecl = Constructor->getParent(); 786 787 // C++ [class.base.init]p2: 788 // Names in a mem-initializer-id are looked up in the scope of the 789 // constructor’s class and, if not found in that scope, are looked 790 // up in the scope containing the constructor’s 791 // definition. [Note: if the constructor’s class contains a member 792 // with the same name as a direct or virtual base class of the 793 // class, a mem-initializer-id naming the member or base class and 794 // composed of a single identifier refers to the class member. A 795 // mem-initializer-id for the hidden base class may be specified 796 // using a qualified name. ] 797 if (!SS.getScopeRep() && !TemplateTypeTy) { 798 // Look for a member, first. 799 FieldDecl *Member = 0; 800 DeclContext::lookup_result Result 801 = ClassDecl->lookup(MemberOrBase); 802 if (Result.first != Result.second) 803 Member = dyn_cast<FieldDecl>(*Result.first); 804 805 // FIXME: Handle members of an anonymous union. 806 807 if (Member) 808 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 809 RParenLoc); 810 } 811 // It didn't name a member, so see if it names a class. 812 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 813 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 814 if (!BaseTy) 815 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 816 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 817 818 QualType BaseType = GetTypeFromParser(BaseTy); 819 820 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 821 RParenLoc, ClassDecl); 822} 823 824Sema::MemInitResult 825Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 826 unsigned NumArgs, SourceLocation IdLoc, 827 SourceLocation RParenLoc) { 828 bool HasDependentArg = false; 829 for (unsigned i = 0; i < NumArgs; i++) 830 HasDependentArg |= Args[i]->isTypeDependent(); 831 832 CXXConstructorDecl *C = 0; 833 QualType FieldType = Member->getType(); 834 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 835 FieldType = Array->getElementType(); 836 if (FieldType->isDependentType()) { 837 // Can't check init for dependent type. 838 } else if (FieldType->getAs<RecordType>()) { 839 if (!HasDependentArg) { 840 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 841 842 C = PerformInitializationByConstructor(FieldType, 843 MultiExprArg(*this, 844 (void**)Args, 845 NumArgs), 846 IdLoc, 847 SourceRange(IdLoc, RParenLoc), 848 Member->getDeclName(), IK_Direct, 849 ConstructorArgs); 850 851 if (C) { 852 // Take over the constructor arguments as our own. 853 NumArgs = ConstructorArgs.size(); 854 Args = (Expr **)ConstructorArgs.take(); 855 } 856 } 857 } else if (NumArgs != 1 && NumArgs != 0) { 858 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 859 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 860 } else if (!HasDependentArg) { 861 Expr *NewExp; 862 if (NumArgs == 0) { 863 if (FieldType->isReferenceType()) { 864 Diag(IdLoc, diag::err_null_intialized_reference_member) 865 << Member->getDeclName(); 866 return Diag(Member->getLocation(), diag::note_declared_at); 867 } 868 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc); 869 NumArgs = 1; 870 } 871 else 872 NewExp = (Expr*)Args[0]; 873 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 874 return true; 875 Args[0] = NewExp; 876 } 877 // FIXME: Perform direct initialization of the member. 878 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 879 NumArgs, C, IdLoc, RParenLoc); 880} 881 882Sema::MemInitResult 883Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 884 unsigned NumArgs, SourceLocation IdLoc, 885 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 886 bool HasDependentArg = false; 887 for (unsigned i = 0; i < NumArgs; i++) 888 HasDependentArg |= Args[i]->isTypeDependent(); 889 890 if (!BaseType->isDependentType()) { 891 if (!BaseType->isRecordType()) 892 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 893 << BaseType << SourceRange(IdLoc, RParenLoc); 894 895 // C++ [class.base.init]p2: 896 // [...] Unless the mem-initializer-id names a nonstatic data 897 // member of the constructor’s class or a direct or virtual base 898 // of that class, the mem-initializer is ill-formed. A 899 // mem-initializer-list can initialize a base class using any 900 // name that denotes that base class type. 901 902 // First, check for a direct base class. 903 const CXXBaseSpecifier *DirectBaseSpec = 0; 904 for (CXXRecordDecl::base_class_const_iterator Base = 905 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 906 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 907 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 908 // We found a direct base of this type. That's what we're 909 // initializing. 910 DirectBaseSpec = &*Base; 911 break; 912 } 913 } 914 915 // Check for a virtual base class. 916 // FIXME: We might be able to short-circuit this if we know in advance that 917 // there are no virtual bases. 918 const CXXBaseSpecifier *VirtualBaseSpec = 0; 919 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 920 // We haven't found a base yet; search the class hierarchy for a 921 // virtual base class. 922 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 923 /*DetectVirtual=*/false); 924 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 925 for (BasePaths::paths_iterator Path = Paths.begin(); 926 Path != Paths.end(); ++Path) { 927 if (Path->back().Base->isVirtual()) { 928 VirtualBaseSpec = Path->back().Base; 929 break; 930 } 931 } 932 } 933 } 934 935 // C++ [base.class.init]p2: 936 // If a mem-initializer-id is ambiguous because it designates both 937 // a direct non-virtual base class and an inherited virtual base 938 // class, the mem-initializer is ill-formed. 939 if (DirectBaseSpec && VirtualBaseSpec) 940 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 941 << BaseType << SourceRange(IdLoc, RParenLoc); 942 // C++ [base.class.init]p2: 943 // Unless the mem-initializer-id names a nonstatic data membeer of the 944 // constructor's class ot a direst or virtual base of that class, the 945 // mem-initializer is ill-formed. 946 if (!DirectBaseSpec && !VirtualBaseSpec) 947 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 948 << BaseType << ClassDecl->getNameAsCString() 949 << SourceRange(IdLoc, RParenLoc); 950 } 951 952 CXXConstructorDecl *C = 0; 953 if (!BaseType->isDependentType() && !HasDependentArg) { 954 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 955 Context.getCanonicalType(BaseType)); 956 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 957 958 C = PerformInitializationByConstructor(BaseType, 959 MultiExprArg(*this, 960 (void**)Args, NumArgs), 961 IdLoc, SourceRange(IdLoc, RParenLoc), 962 Name, IK_Direct, 963 ConstructorArgs); 964 if (C) { 965 // Take over the constructor arguments as our own. 966 NumArgs = ConstructorArgs.size(); 967 Args = (Expr **)ConstructorArgs.take(); 968 } 969 } 970 971 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 972 NumArgs, C, IdLoc, RParenLoc); 973} 974 975void 976Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 977 CXXBaseOrMemberInitializer **Initializers, 978 unsigned NumInitializers, 979 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases, 980 llvm::SmallVectorImpl<FieldDecl *>&Fields) { 981 // We need to build the initializer AST according to order of construction 982 // and not what user specified in the Initializers list. 983 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 984 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 985 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 986 bool HasDependentBaseInit = false; 987 988 for (unsigned i = 0; i < NumInitializers; i++) { 989 CXXBaseOrMemberInitializer *Member = Initializers[i]; 990 if (Member->isBaseInitializer()) { 991 if (Member->getBaseClass()->isDependentType()) 992 HasDependentBaseInit = true; 993 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 994 } else { 995 AllBaseFields[Member->getMember()] = Member; 996 } 997 } 998 999 if (HasDependentBaseInit) { 1000 // FIXME. This does not preserve the ordering of the initializers. 1001 // Try (with -Wreorder) 1002 // template<class X> struct A {}; 1003 // template<class X> struct B : A<X> { 1004 // B() : x1(10), A<X>() {} 1005 // int x1; 1006 // }; 1007 // B<int> x; 1008 // On seeing one dependent type, we should essentially exit this routine 1009 // while preserving user-declared initializer list. When this routine is 1010 // called during instantiatiation process, this routine will rebuild the 1011 // oderdered initializer list correctly. 1012 1013 // If we have a dependent base initialization, we can't determine the 1014 // association between initializers and bases; just dump the known 1015 // initializers into the list, and don't try to deal with other bases. 1016 for (unsigned i = 0; i < NumInitializers; i++) { 1017 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1018 if (Member->isBaseInitializer()) 1019 AllToInit.push_back(Member); 1020 } 1021 } else { 1022 // Push virtual bases before others. 1023 for (CXXRecordDecl::base_class_iterator VBase = 1024 ClassDecl->vbases_begin(), 1025 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1026 if (VBase->getType()->isDependentType()) 1027 continue; 1028 if (CXXBaseOrMemberInitializer *Value = 1029 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1030 CXXRecordDecl *BaseDecl = 1031 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1032 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1033 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 1034 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1035 AllToInit.push_back(Value); 1036 } 1037 else { 1038 CXXRecordDecl *VBaseDecl = 1039 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1040 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null"); 1041 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context); 1042 if (!Ctor) 1043 Bases.push_back(VBase); 1044 else 1045 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1046 1047 CXXBaseOrMemberInitializer *Member = 1048 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0, 1049 Ctor, 1050 SourceLocation(), 1051 SourceLocation()); 1052 AllToInit.push_back(Member); 1053 } 1054 } 1055 1056 for (CXXRecordDecl::base_class_iterator Base = 1057 ClassDecl->bases_begin(), 1058 E = ClassDecl->bases_end(); Base != E; ++Base) { 1059 // Virtuals are in the virtual base list and already constructed. 1060 if (Base->isVirtual()) 1061 continue; 1062 // Skip dependent types. 1063 if (Base->getType()->isDependentType()) 1064 continue; 1065 if (CXXBaseOrMemberInitializer *Value = 1066 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1067 CXXRecordDecl *BaseDecl = 1068 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1069 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1070 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 1071 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1072 AllToInit.push_back(Value); 1073 } 1074 else { 1075 CXXRecordDecl *BaseDecl = 1076 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1077 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1078 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context); 1079 if (!Ctor) 1080 Bases.push_back(Base); 1081 else 1082 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1083 1084 CXXBaseOrMemberInitializer *Member = 1085 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0, 1086 BaseDecl->getDefaultConstructor(Context), 1087 SourceLocation(), 1088 SourceLocation()); 1089 AllToInit.push_back(Member); 1090 } 1091 } 1092 } 1093 1094 // non-static data members. 1095 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1096 E = ClassDecl->field_end(); Field != E; ++Field) { 1097 if ((*Field)->isAnonymousStructOrUnion()) { 1098 if (const RecordType *FieldClassType = 1099 Field->getType()->getAs<RecordType>()) { 1100 CXXRecordDecl *FieldClassDecl 1101 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1102 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1103 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1104 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1105 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1106 // set to the anonymous union data member used in the initializer 1107 // list. 1108 Value->setMember(*Field); 1109 Value->setAnonUnionMember(*FA); 1110 AllToInit.push_back(Value); 1111 break; 1112 } 1113 } 1114 } 1115 continue; 1116 } 1117 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1118 QualType FT = (*Field)->getType(); 1119 if (const RecordType* RT = FT->getAs<RecordType>()) { 1120 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl()); 1121 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1122 if (CXXConstructorDecl *Ctor = 1123 FieldRecDecl->getDefaultConstructor(Context)) 1124 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1125 } 1126 AllToInit.push_back(Value); 1127 continue; 1128 } 1129 1130 QualType FT = Context.getBaseElementType((*Field)->getType()); 1131 if (const RecordType* RT = FT->getAs<RecordType>()) { 1132 CXXConstructorDecl *Ctor = 1133 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context); 1134 if (!Ctor && !FT->isDependentType()) 1135 Fields.push_back(*Field); 1136 CXXBaseOrMemberInitializer *Member = 1137 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0, 1138 Ctor, 1139 SourceLocation(), 1140 SourceLocation()); 1141 AllToInit.push_back(Member); 1142 if (Ctor) 1143 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1144 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) { 1145 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1146 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1147 Diag((*Field)->getLocation(), diag::note_declared_at); 1148 } 1149 } 1150 else if (FT->isReferenceType()) { 1151 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1152 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName(); 1153 Diag((*Field)->getLocation(), diag::note_declared_at); 1154 } 1155 else if (FT.isConstQualified()) { 1156 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1157 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1158 Diag((*Field)->getLocation(), diag::note_declared_at); 1159 } 1160 } 1161 1162 NumInitializers = AllToInit.size(); 1163 if (NumInitializers > 0) { 1164 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1165 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1166 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1167 1168 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1169 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) 1170 baseOrMemberInitializers[Idx] = AllToInit[Idx]; 1171 } 1172} 1173 1174void 1175Sema::BuildBaseOrMemberInitializers(ASTContext &C, 1176 CXXConstructorDecl *Constructor, 1177 CXXBaseOrMemberInitializer **Initializers, 1178 unsigned NumInitializers 1179 ) { 1180 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases; 1181 llvm::SmallVector<FieldDecl *, 4>Members; 1182 1183 setBaseOrMemberInitializers(Constructor, 1184 Initializers, NumInitializers, Bases, Members); 1185 for (unsigned int i = 0; i < Bases.size(); i++) 1186 Diag(Bases[i]->getSourceRange().getBegin(), 1187 diag::err_missing_default_constructor) << 0 << Bases[i]->getType(); 1188 for (unsigned int i = 0; i < Members.size(); i++) 1189 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor) 1190 << 1 << Members[i]->getType(); 1191} 1192 1193static void *GetKeyForTopLevelField(FieldDecl *Field) { 1194 // For anonymous unions, use the class declaration as the key. 1195 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1196 if (RT->getDecl()->isAnonymousStructOrUnion()) 1197 return static_cast<void *>(RT->getDecl()); 1198 } 1199 return static_cast<void *>(Field); 1200} 1201 1202static void *GetKeyForBase(QualType BaseType) { 1203 if (const RecordType *RT = BaseType->getAs<RecordType>()) 1204 return (void *)RT; 1205 1206 assert(0 && "Unexpected base type!"); 1207 return 0; 1208} 1209 1210static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 1211 bool MemberMaybeAnon = false) { 1212 // For fields injected into the class via declaration of an anonymous union, 1213 // use its anonymous union class declaration as the unique key. 1214 if (Member->isMemberInitializer()) { 1215 FieldDecl *Field = Member->getMember(); 1216 1217 // After BuildBaseOrMemberInitializers call, Field is the anonymous union 1218 // data member of the class. Data member used in the initializer list is 1219 // in AnonUnionMember field. 1220 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1221 Field = Member->getAnonUnionMember(); 1222 if (Field->getDeclContext()->isRecord()) { 1223 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 1224 if (RD->isAnonymousStructOrUnion()) 1225 return static_cast<void *>(RD); 1226 } 1227 return static_cast<void *>(Field); 1228 } 1229 1230 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 1231} 1232 1233void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1234 SourceLocation ColonLoc, 1235 MemInitTy **MemInits, unsigned NumMemInits) { 1236 if (!ConstructorDecl) 1237 return; 1238 1239 AdjustDeclIfTemplate(ConstructorDecl); 1240 1241 CXXConstructorDecl *Constructor 1242 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1243 1244 if (!Constructor) { 1245 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1246 return; 1247 } 1248 1249 if (!Constructor->isDependentContext()) { 1250 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 1251 bool err = false; 1252 for (unsigned i = 0; i < NumMemInits; i++) { 1253 CXXBaseOrMemberInitializer *Member = 1254 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1255 void *KeyToMember = GetKeyForMember(Member); 1256 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1257 if (!PrevMember) { 1258 PrevMember = Member; 1259 continue; 1260 } 1261 if (FieldDecl *Field = Member->getMember()) 1262 Diag(Member->getSourceLocation(), 1263 diag::error_multiple_mem_initialization) 1264 << Field->getNameAsString(); 1265 else { 1266 Type *BaseClass = Member->getBaseClass(); 1267 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1268 Diag(Member->getSourceLocation(), 1269 diag::error_multiple_base_initialization) 1270 << BaseClass->getDesugaredType(true); 1271 } 1272 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1273 << 0; 1274 err = true; 1275 } 1276 1277 if (err) 1278 return; 1279 } 1280 1281 BuildBaseOrMemberInitializers(Context, Constructor, 1282 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 1283 NumMemInits); 1284 1285 if (Constructor->isDependentContext()) 1286 return; 1287 1288 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1289 Diagnostic::Ignored && 1290 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1291 Diagnostic::Ignored) 1292 return; 1293 1294 // Also issue warning if order of ctor-initializer list does not match order 1295 // of 1) base class declarations and 2) order of non-static data members. 1296 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1297 1298 CXXRecordDecl *ClassDecl 1299 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1300 // Push virtual bases before others. 1301 for (CXXRecordDecl::base_class_iterator VBase = 1302 ClassDecl->vbases_begin(), 1303 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1304 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 1305 1306 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1307 E = ClassDecl->bases_end(); Base != E; ++Base) { 1308 // Virtuals are alread in the virtual base list and are constructed 1309 // first. 1310 if (Base->isVirtual()) 1311 continue; 1312 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 1313 } 1314 1315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1316 E = ClassDecl->field_end(); Field != E; ++Field) 1317 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1318 1319 int Last = AllBaseOrMembers.size(); 1320 int curIndex = 0; 1321 CXXBaseOrMemberInitializer *PrevMember = 0; 1322 for (unsigned i = 0; i < NumMemInits; i++) { 1323 CXXBaseOrMemberInitializer *Member = 1324 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1325 void *MemberInCtorList = GetKeyForMember(Member, true); 1326 1327 for (; curIndex < Last; curIndex++) 1328 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1329 break; 1330 if (curIndex == Last) { 1331 assert(PrevMember && "Member not in member list?!"); 1332 // Initializer as specified in ctor-initializer list is out of order. 1333 // Issue a warning diagnostic. 1334 if (PrevMember->isBaseInitializer()) { 1335 // Diagnostics is for an initialized base class. 1336 Type *BaseClass = PrevMember->getBaseClass(); 1337 Diag(PrevMember->getSourceLocation(), 1338 diag::warn_base_initialized) 1339 << BaseClass->getDesugaredType(true); 1340 } else { 1341 FieldDecl *Field = PrevMember->getMember(); 1342 Diag(PrevMember->getSourceLocation(), 1343 diag::warn_field_initialized) 1344 << Field->getNameAsString(); 1345 } 1346 // Also the note! 1347 if (FieldDecl *Field = Member->getMember()) 1348 Diag(Member->getSourceLocation(), 1349 diag::note_fieldorbase_initialized_here) << 0 1350 << Field->getNameAsString(); 1351 else { 1352 Type *BaseClass = Member->getBaseClass(); 1353 Diag(Member->getSourceLocation(), 1354 diag::note_fieldorbase_initialized_here) << 1 1355 << BaseClass->getDesugaredType(true); 1356 } 1357 for (curIndex = 0; curIndex < Last; curIndex++) 1358 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1359 break; 1360 } 1361 PrevMember = Member; 1362 } 1363} 1364 1365void 1366Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) { 1367 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext()); 1368 llvm::SmallVector<uintptr_t, 32> AllToDestruct; 1369 1370 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1371 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1372 if (VBase->getType()->isDependentType()) 1373 continue; 1374 // Skip over virtual bases which have trivial destructors. 1375 CXXRecordDecl *BaseClassDecl 1376 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1377 if (BaseClassDecl->hasTrivialDestructor()) 1378 continue; 1379 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1380 MarkDeclarationReferenced(Destructor->getLocation(), 1381 const_cast<CXXDestructorDecl*>(Dtor)); 1382 1383 uintptr_t Member = 1384 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr()) 1385 | CXXDestructorDecl::VBASE; 1386 AllToDestruct.push_back(Member); 1387 } 1388 for (CXXRecordDecl::base_class_iterator Base = 1389 ClassDecl->bases_begin(), 1390 E = ClassDecl->bases_end(); Base != E; ++Base) { 1391 if (Base->isVirtual()) 1392 continue; 1393 if (Base->getType()->isDependentType()) 1394 continue; 1395 // Skip over virtual bases which have trivial destructors. 1396 CXXRecordDecl *BaseClassDecl 1397 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1398 if (BaseClassDecl->hasTrivialDestructor()) 1399 continue; 1400 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1401 MarkDeclarationReferenced(Destructor->getLocation(), 1402 const_cast<CXXDestructorDecl*>(Dtor)); 1403 uintptr_t Member = 1404 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr()) 1405 | CXXDestructorDecl::DRCTNONVBASE; 1406 AllToDestruct.push_back(Member); 1407 } 1408 1409 // non-static data members. 1410 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1411 E = ClassDecl->field_end(); Field != E; ++Field) { 1412 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 1413 1414 if (const RecordType* RT = FieldType->getAs<RecordType>()) { 1415 // Skip over virtual bases which have trivial destructors. 1416 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1417 if (FieldClassDecl->hasTrivialDestructor()) 1418 continue; 1419 if (const CXXDestructorDecl *Dtor = 1420 FieldClassDecl->getDestructor(Context)) 1421 MarkDeclarationReferenced(Destructor->getLocation(), 1422 const_cast<CXXDestructorDecl*>(Dtor)); 1423 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field); 1424 AllToDestruct.push_back(Member); 1425 } 1426 } 1427 1428 unsigned NumDestructions = AllToDestruct.size(); 1429 if (NumDestructions > 0) { 1430 Destructor->setNumBaseOrMemberDestructions(NumDestructions); 1431 uintptr_t *BaseOrMemberDestructions = 1432 new (Context) uintptr_t [NumDestructions]; 1433 // Insert in reverse order. 1434 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx) 1435 BaseOrMemberDestructions[i++] = AllToDestruct[Idx]; 1436 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions); 1437 } 1438} 1439 1440void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1441 if (!CDtorDecl) 1442 return; 1443 1444 AdjustDeclIfTemplate(CDtorDecl); 1445 1446 if (CXXConstructorDecl *Constructor 1447 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1448 BuildBaseOrMemberInitializers(Context, 1449 Constructor, 1450 (CXXBaseOrMemberInitializer **)0, 0); 1451} 1452 1453namespace { 1454 /// PureVirtualMethodCollector - traverses a class and its superclasses 1455 /// and determines if it has any pure virtual methods. 1456 class VISIBILITY_HIDDEN PureVirtualMethodCollector { 1457 ASTContext &Context; 1458 1459 public: 1460 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1461 1462 private: 1463 MethodList Methods; 1464 1465 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1466 1467 public: 1468 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1469 : Context(Ctx) { 1470 1471 MethodList List; 1472 Collect(RD, List); 1473 1474 // Copy the temporary list to methods, and make sure to ignore any 1475 // null entries. 1476 for (size_t i = 0, e = List.size(); i != e; ++i) { 1477 if (List[i]) 1478 Methods.push_back(List[i]); 1479 } 1480 } 1481 1482 bool empty() const { return Methods.empty(); } 1483 1484 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1485 MethodList::const_iterator methods_end() { return Methods.end(); } 1486 }; 1487 1488 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1489 MethodList& Methods) { 1490 // First, collect the pure virtual methods for the base classes. 1491 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1492 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1493 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1494 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1495 if (BaseDecl && BaseDecl->isAbstract()) 1496 Collect(BaseDecl, Methods); 1497 } 1498 } 1499 1500 // Next, zero out any pure virtual methods that this class overrides. 1501 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1502 1503 MethodSetTy OverriddenMethods; 1504 size_t MethodsSize = Methods.size(); 1505 1506 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1507 i != e; ++i) { 1508 // Traverse the record, looking for methods. 1509 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1510 // If the method is pure virtual, add it to the methods vector. 1511 if (MD->isPure()) { 1512 Methods.push_back(MD); 1513 continue; 1514 } 1515 1516 // Otherwise, record all the overridden methods in our set. 1517 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1518 E = MD->end_overridden_methods(); I != E; ++I) { 1519 // Keep track of the overridden methods. 1520 OverriddenMethods.insert(*I); 1521 } 1522 } 1523 } 1524 1525 // Now go through the methods and zero out all the ones we know are 1526 // overridden. 1527 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1528 if (OverriddenMethods.count(Methods[i])) 1529 Methods[i] = 0; 1530 } 1531 1532 } 1533} 1534 1535 1536bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1537 unsigned DiagID, AbstractDiagSelID SelID, 1538 const CXXRecordDecl *CurrentRD) { 1539 if (SelID == -1) 1540 return RequireNonAbstractType(Loc, T, 1541 PDiag(DiagID), CurrentRD); 1542 else 1543 return RequireNonAbstractType(Loc, T, 1544 PDiag(DiagID) << SelID, CurrentRD); 1545} 1546 1547bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1548 const PartialDiagnostic &PD, 1549 const CXXRecordDecl *CurrentRD) { 1550 if (!getLangOptions().CPlusPlus) 1551 return false; 1552 1553 if (const ArrayType *AT = Context.getAsArrayType(T)) 1554 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1555 CurrentRD); 1556 1557 if (const PointerType *PT = T->getAs<PointerType>()) { 1558 // Find the innermost pointer type. 1559 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1560 PT = T; 1561 1562 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1563 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1564 } 1565 1566 const RecordType *RT = T->getAs<RecordType>(); 1567 if (!RT) 1568 return false; 1569 1570 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1571 if (!RD) 1572 return false; 1573 1574 if (CurrentRD && CurrentRD != RD) 1575 return false; 1576 1577 if (!RD->isAbstract()) 1578 return false; 1579 1580 Diag(Loc, PD) << RD->getDeclName(); 1581 1582 // Check if we've already emitted the list of pure virtual functions for this 1583 // class. 1584 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1585 return true; 1586 1587 PureVirtualMethodCollector Collector(Context, RD); 1588 1589 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1590 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1591 const CXXMethodDecl *MD = *I; 1592 1593 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1594 MD->getDeclName(); 1595 } 1596 1597 if (!PureVirtualClassDiagSet) 1598 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1599 PureVirtualClassDiagSet->insert(RD); 1600 1601 return true; 1602} 1603 1604namespace { 1605 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser 1606 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1607 Sema &SemaRef; 1608 CXXRecordDecl *AbstractClass; 1609 1610 bool VisitDeclContext(const DeclContext *DC) { 1611 bool Invalid = false; 1612 1613 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1614 E = DC->decls_end(); I != E; ++I) 1615 Invalid |= Visit(*I); 1616 1617 return Invalid; 1618 } 1619 1620 public: 1621 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1622 : SemaRef(SemaRef), AbstractClass(ac) { 1623 Visit(SemaRef.Context.getTranslationUnitDecl()); 1624 } 1625 1626 bool VisitFunctionDecl(const FunctionDecl *FD) { 1627 if (FD->isThisDeclarationADefinition()) { 1628 // No need to do the check if we're in a definition, because it requires 1629 // that the return/param types are complete. 1630 // because that requires 1631 return VisitDeclContext(FD); 1632 } 1633 1634 // Check the return type. 1635 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 1636 bool Invalid = 1637 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1638 diag::err_abstract_type_in_decl, 1639 Sema::AbstractReturnType, 1640 AbstractClass); 1641 1642 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1643 E = FD->param_end(); I != E; ++I) { 1644 const ParmVarDecl *VD = *I; 1645 Invalid |= 1646 SemaRef.RequireNonAbstractType(VD->getLocation(), 1647 VD->getOriginalType(), 1648 diag::err_abstract_type_in_decl, 1649 Sema::AbstractParamType, 1650 AbstractClass); 1651 } 1652 1653 return Invalid; 1654 } 1655 1656 bool VisitDecl(const Decl* D) { 1657 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1658 return VisitDeclContext(DC); 1659 1660 return false; 1661 } 1662 }; 1663} 1664 1665void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1666 DeclPtrTy TagDecl, 1667 SourceLocation LBrac, 1668 SourceLocation RBrac) { 1669 if (!TagDecl) 1670 return; 1671 1672 AdjustDeclIfTemplate(TagDecl); 1673 ActOnFields(S, RLoc, TagDecl, 1674 (DeclPtrTy*)FieldCollector->getCurFields(), 1675 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1676 1677 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1678 if (!RD->isAbstract()) { 1679 // Collect all the pure virtual methods and see if this is an abstract 1680 // class after all. 1681 PureVirtualMethodCollector Collector(Context, RD); 1682 if (!Collector.empty()) 1683 RD->setAbstract(true); 1684 } 1685 1686 if (RD->isAbstract()) 1687 AbstractClassUsageDiagnoser(*this, RD); 1688 1689 if (!RD->isDependentType()) 1690 AddImplicitlyDeclaredMembersToClass(RD); 1691} 1692 1693/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1694/// special functions, such as the default constructor, copy 1695/// constructor, or destructor, to the given C++ class (C++ 1696/// [special]p1). This routine can only be executed just before the 1697/// definition of the class is complete. 1698void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1699 CanQualType ClassType 1700 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1701 1702 // FIXME: Implicit declarations have exception specifications, which are 1703 // the union of the specifications of the implicitly called functions. 1704 1705 if (!ClassDecl->hasUserDeclaredConstructor()) { 1706 // C++ [class.ctor]p5: 1707 // A default constructor for a class X is a constructor of class X 1708 // that can be called without an argument. If there is no 1709 // user-declared constructor for class X, a default constructor is 1710 // implicitly declared. An implicitly-declared default constructor 1711 // is an inline public member of its class. 1712 DeclarationName Name 1713 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1714 CXXConstructorDecl *DefaultCon = 1715 CXXConstructorDecl::Create(Context, ClassDecl, 1716 ClassDecl->getLocation(), Name, 1717 Context.getFunctionType(Context.VoidTy, 1718 0, 0, false, 0), 1719 /*DInfo=*/0, 1720 /*isExplicit=*/false, 1721 /*isInline=*/true, 1722 /*isImplicitlyDeclared=*/true); 1723 DefaultCon->setAccess(AS_public); 1724 DefaultCon->setImplicit(); 1725 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1726 ClassDecl->addDecl(DefaultCon); 1727 } 1728 1729 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1730 // C++ [class.copy]p4: 1731 // If the class definition does not explicitly declare a copy 1732 // constructor, one is declared implicitly. 1733 1734 // C++ [class.copy]p5: 1735 // The implicitly-declared copy constructor for a class X will 1736 // have the form 1737 // 1738 // X::X(const X&) 1739 // 1740 // if 1741 bool HasConstCopyConstructor = true; 1742 1743 // -- each direct or virtual base class B of X has a copy 1744 // constructor whose first parameter is of type const B& or 1745 // const volatile B&, and 1746 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1747 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 1748 const CXXRecordDecl *BaseClassDecl 1749 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1750 HasConstCopyConstructor 1751 = BaseClassDecl->hasConstCopyConstructor(Context); 1752 } 1753 1754 // -- for all the nonstatic data members of X that are of a 1755 // class type M (or array thereof), each such class type 1756 // has a copy constructor whose first parameter is of type 1757 // const M& or const volatile M&. 1758 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1759 HasConstCopyConstructor && Field != ClassDecl->field_end(); 1760 ++Field) { 1761 QualType FieldType = (*Field)->getType(); 1762 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1763 FieldType = Array->getElementType(); 1764 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1765 const CXXRecordDecl *FieldClassDecl 1766 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1767 HasConstCopyConstructor 1768 = FieldClassDecl->hasConstCopyConstructor(Context); 1769 } 1770 } 1771 1772 // Otherwise, the implicitly declared copy constructor will have 1773 // the form 1774 // 1775 // X::X(X&) 1776 QualType ArgType = ClassType; 1777 if (HasConstCopyConstructor) 1778 ArgType = ArgType.withConst(); 1779 ArgType = Context.getLValueReferenceType(ArgType); 1780 1781 // An implicitly-declared copy constructor is an inline public 1782 // member of its class. 1783 DeclarationName Name 1784 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1785 CXXConstructorDecl *CopyConstructor 1786 = CXXConstructorDecl::Create(Context, ClassDecl, 1787 ClassDecl->getLocation(), Name, 1788 Context.getFunctionType(Context.VoidTy, 1789 &ArgType, 1, 1790 false, 0), 1791 /*DInfo=*/0, 1792 /*isExplicit=*/false, 1793 /*isInline=*/true, 1794 /*isImplicitlyDeclared=*/true); 1795 CopyConstructor->setAccess(AS_public); 1796 CopyConstructor->setImplicit(); 1797 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 1798 1799 // Add the parameter to the constructor. 1800 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 1801 ClassDecl->getLocation(), 1802 /*IdentifierInfo=*/0, 1803 ArgType, /*DInfo=*/0, 1804 VarDecl::None, 0); 1805 CopyConstructor->setParams(Context, &FromParam, 1); 1806 ClassDecl->addDecl(CopyConstructor); 1807 } 1808 1809 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 1810 // Note: The following rules are largely analoguous to the copy 1811 // constructor rules. Note that virtual bases are not taken into account 1812 // for determining the argument type of the operator. Note also that 1813 // operators taking an object instead of a reference are allowed. 1814 // 1815 // C++ [class.copy]p10: 1816 // If the class definition does not explicitly declare a copy 1817 // assignment operator, one is declared implicitly. 1818 // The implicitly-defined copy assignment operator for a class X 1819 // will have the form 1820 // 1821 // X& X::operator=(const X&) 1822 // 1823 // if 1824 bool HasConstCopyAssignment = true; 1825 1826 // -- each direct base class B of X has a copy assignment operator 1827 // whose parameter is of type const B&, const volatile B& or B, 1828 // and 1829 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1830 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 1831 const CXXRecordDecl *BaseClassDecl 1832 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1833 const CXXMethodDecl *MD = 0; 1834 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 1835 MD); 1836 } 1837 1838 // -- for all the nonstatic data members of X that are of a class 1839 // type M (or array thereof), each such class type has a copy 1840 // assignment operator whose parameter is of type const M&, 1841 // const volatile M& or M. 1842 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1843 HasConstCopyAssignment && Field != ClassDecl->field_end(); 1844 ++Field) { 1845 QualType FieldType = (*Field)->getType(); 1846 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1847 FieldType = Array->getElementType(); 1848 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1849 const CXXRecordDecl *FieldClassDecl 1850 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1851 const CXXMethodDecl *MD = 0; 1852 HasConstCopyAssignment 1853 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 1854 } 1855 } 1856 1857 // Otherwise, the implicitly declared copy assignment operator will 1858 // have the form 1859 // 1860 // X& X::operator=(X&) 1861 QualType ArgType = ClassType; 1862 QualType RetType = Context.getLValueReferenceType(ArgType); 1863 if (HasConstCopyAssignment) 1864 ArgType = ArgType.withConst(); 1865 ArgType = Context.getLValueReferenceType(ArgType); 1866 1867 // An implicitly-declared copy assignment operator is an inline public 1868 // member of its class. 1869 DeclarationName Name = 1870 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 1871 CXXMethodDecl *CopyAssignment = 1872 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 1873 Context.getFunctionType(RetType, &ArgType, 1, 1874 false, 0), 1875 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 1876 CopyAssignment->setAccess(AS_public); 1877 CopyAssignment->setImplicit(); 1878 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 1879 CopyAssignment->setCopyAssignment(true); 1880 1881 // Add the parameter to the operator. 1882 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 1883 ClassDecl->getLocation(), 1884 /*IdentifierInfo=*/0, 1885 ArgType, /*DInfo=*/0, 1886 VarDecl::None, 0); 1887 CopyAssignment->setParams(Context, &FromParam, 1); 1888 1889 // Don't call addedAssignmentOperator. There is no way to distinguish an 1890 // implicit from an explicit assignment operator. 1891 ClassDecl->addDecl(CopyAssignment); 1892 } 1893 1894 if (!ClassDecl->hasUserDeclaredDestructor()) { 1895 // C++ [class.dtor]p2: 1896 // If a class has no user-declared destructor, a destructor is 1897 // declared implicitly. An implicitly-declared destructor is an 1898 // inline public member of its class. 1899 DeclarationName Name 1900 = Context.DeclarationNames.getCXXDestructorName(ClassType); 1901 CXXDestructorDecl *Destructor 1902 = CXXDestructorDecl::Create(Context, ClassDecl, 1903 ClassDecl->getLocation(), Name, 1904 Context.getFunctionType(Context.VoidTy, 1905 0, 0, false, 0), 1906 /*isInline=*/true, 1907 /*isImplicitlyDeclared=*/true); 1908 Destructor->setAccess(AS_public); 1909 Destructor->setImplicit(); 1910 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 1911 ClassDecl->addDecl(Destructor); 1912 } 1913} 1914 1915void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 1916 Decl *D = TemplateD.getAs<Decl>(); 1917 if (!D) 1918 return; 1919 1920 TemplateParameterList *Params = 0; 1921 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 1922 Params = Template->getTemplateParameters(); 1923 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1924 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 1925 Params = PartialSpec->getTemplateParameters(); 1926 else 1927 return; 1928 1929 for (TemplateParameterList::iterator Param = Params->begin(), 1930 ParamEnd = Params->end(); 1931 Param != ParamEnd; ++Param) { 1932 NamedDecl *Named = cast<NamedDecl>(*Param); 1933 if (Named->getDeclName()) { 1934 S->AddDecl(DeclPtrTy::make(Named)); 1935 IdResolver.AddDecl(Named); 1936 } 1937 } 1938} 1939 1940/// ActOnStartDelayedCXXMethodDeclaration - We have completed 1941/// parsing a top-level (non-nested) C++ class, and we are now 1942/// parsing those parts of the given Method declaration that could 1943/// not be parsed earlier (C++ [class.mem]p2), such as default 1944/// arguments. This action should enter the scope of the given 1945/// Method declaration as if we had just parsed the qualified method 1946/// name. However, it should not bring the parameters into scope; 1947/// that will be performed by ActOnDelayedCXXMethodParameter. 1948void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1949 if (!MethodD) 1950 return; 1951 1952 AdjustDeclIfTemplate(MethodD); 1953 1954 CXXScopeSpec SS; 1955 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1956 QualType ClassTy 1957 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1958 SS.setScopeRep( 1959 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1960 ActOnCXXEnterDeclaratorScope(S, SS); 1961} 1962 1963/// ActOnDelayedCXXMethodParameter - We've already started a delayed 1964/// C++ method declaration. We're (re-)introducing the given 1965/// function parameter into scope for use in parsing later parts of 1966/// the method declaration. For example, we could see an 1967/// ActOnParamDefaultArgument event for this parameter. 1968void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 1969 if (!ParamD) 1970 return; 1971 1972 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 1973 1974 // If this parameter has an unparsed default argument, clear it out 1975 // to make way for the parsed default argument. 1976 if (Param->hasUnparsedDefaultArg()) 1977 Param->setDefaultArg(0); 1978 1979 S->AddDecl(DeclPtrTy::make(Param)); 1980 if (Param->getDeclName()) 1981 IdResolver.AddDecl(Param); 1982} 1983 1984/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 1985/// processing the delayed method declaration for Method. The method 1986/// declaration is now considered finished. There may be a separate 1987/// ActOnStartOfFunctionDef action later (not necessarily 1988/// immediately!) for this method, if it was also defined inside the 1989/// class body. 1990void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1991 if (!MethodD) 1992 return; 1993 1994 AdjustDeclIfTemplate(MethodD); 1995 1996 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1997 CXXScopeSpec SS; 1998 QualType ClassTy 1999 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 2000 SS.setScopeRep( 2001 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 2002 ActOnCXXExitDeclaratorScope(S, SS); 2003 2004 // Now that we have our default arguments, check the constructor 2005 // again. It could produce additional diagnostics or affect whether 2006 // the class has implicitly-declared destructors, among other 2007 // things. 2008 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2009 CheckConstructor(Constructor); 2010 2011 // Check the default arguments, which we may have added. 2012 if (!Method->isInvalidDecl()) 2013 CheckCXXDefaultArguments(Method); 2014} 2015 2016/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2017/// the well-formedness of the constructor declarator @p D with type @p 2018/// R. If there are any errors in the declarator, this routine will 2019/// emit diagnostics and set the invalid bit to true. In any case, the type 2020/// will be updated to reflect a well-formed type for the constructor and 2021/// returned. 2022QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2023 FunctionDecl::StorageClass &SC) { 2024 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2025 2026 // C++ [class.ctor]p3: 2027 // A constructor shall not be virtual (10.3) or static (9.4). A 2028 // constructor can be invoked for a const, volatile or const 2029 // volatile object. A constructor shall not be declared const, 2030 // volatile, or const volatile (9.3.2). 2031 if (isVirtual) { 2032 if (!D.isInvalidType()) 2033 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2034 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2035 << SourceRange(D.getIdentifierLoc()); 2036 D.setInvalidType(); 2037 } 2038 if (SC == FunctionDecl::Static) { 2039 if (!D.isInvalidType()) 2040 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2041 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2042 << SourceRange(D.getIdentifierLoc()); 2043 D.setInvalidType(); 2044 SC = FunctionDecl::None; 2045 } 2046 2047 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2048 if (FTI.TypeQuals != 0) { 2049 if (FTI.TypeQuals & QualType::Const) 2050 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2051 << "const" << SourceRange(D.getIdentifierLoc()); 2052 if (FTI.TypeQuals & QualType::Volatile) 2053 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2054 << "volatile" << SourceRange(D.getIdentifierLoc()); 2055 if (FTI.TypeQuals & QualType::Restrict) 2056 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2057 << "restrict" << SourceRange(D.getIdentifierLoc()); 2058 } 2059 2060 // Rebuild the function type "R" without any type qualifiers (in 2061 // case any of the errors above fired) and with "void" as the 2062 // return type, since constructors don't have return types. We 2063 // *always* have to do this, because GetTypeForDeclarator will 2064 // put in a result type of "int" when none was specified. 2065 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2066 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2067 Proto->getNumArgs(), 2068 Proto->isVariadic(), 0); 2069} 2070 2071/// CheckConstructor - Checks a fully-formed constructor for 2072/// well-formedness, issuing any diagnostics required. Returns true if 2073/// the constructor declarator is invalid. 2074void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2075 CXXRecordDecl *ClassDecl 2076 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2077 if (!ClassDecl) 2078 return Constructor->setInvalidDecl(); 2079 2080 // C++ [class.copy]p3: 2081 // A declaration of a constructor for a class X is ill-formed if 2082 // its first parameter is of type (optionally cv-qualified) X and 2083 // either there are no other parameters or else all other 2084 // parameters have default arguments. 2085 if (!Constructor->isInvalidDecl() && 2086 ((Constructor->getNumParams() == 1) || 2087 (Constructor->getNumParams() > 1 && 2088 Constructor->getParamDecl(1)->hasDefaultArg()))) { 2089 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2090 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2091 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2092 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2093 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2094 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 2095 Constructor->setInvalidDecl(); 2096 } 2097 } 2098 2099 // Notify the class that we've added a constructor. 2100 ClassDecl->addedConstructor(Context, Constructor); 2101} 2102 2103static inline bool 2104FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2105 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2106 FTI.ArgInfo[0].Param && 2107 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2108} 2109 2110/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2111/// the well-formednes of the destructor declarator @p D with type @p 2112/// R. If there are any errors in the declarator, this routine will 2113/// emit diagnostics and set the declarator to invalid. Even if this happens, 2114/// will be updated to reflect a well-formed type for the destructor and 2115/// returned. 2116QualType Sema::CheckDestructorDeclarator(Declarator &D, 2117 FunctionDecl::StorageClass& SC) { 2118 // C++ [class.dtor]p1: 2119 // [...] A typedef-name that names a class is a class-name 2120 // (7.1.3); however, a typedef-name that names a class shall not 2121 // be used as the identifier in the declarator for a destructor 2122 // declaration. 2123 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType()); 2124 if (isa<TypedefType>(DeclaratorType)) { 2125 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2126 << DeclaratorType; 2127 D.setInvalidType(); 2128 } 2129 2130 // C++ [class.dtor]p2: 2131 // A destructor is used to destroy objects of its class type. A 2132 // destructor takes no parameters, and no return type can be 2133 // specified for it (not even void). The address of a destructor 2134 // shall not be taken. A destructor shall not be static. A 2135 // destructor can be invoked for a const, volatile or const 2136 // volatile object. A destructor shall not be declared const, 2137 // volatile or const volatile (9.3.2). 2138 if (SC == FunctionDecl::Static) { 2139 if (!D.isInvalidType()) 2140 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2141 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2142 << SourceRange(D.getIdentifierLoc()); 2143 SC = FunctionDecl::None; 2144 D.setInvalidType(); 2145 } 2146 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2147 // Destructors don't have return types, but the parser will 2148 // happily parse something like: 2149 // 2150 // class X { 2151 // float ~X(); 2152 // }; 2153 // 2154 // The return type will be eliminated later. 2155 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2156 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2157 << SourceRange(D.getIdentifierLoc()); 2158 } 2159 2160 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2161 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2162 if (FTI.TypeQuals & QualType::Const) 2163 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2164 << "const" << SourceRange(D.getIdentifierLoc()); 2165 if (FTI.TypeQuals & QualType::Volatile) 2166 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2167 << "volatile" << SourceRange(D.getIdentifierLoc()); 2168 if (FTI.TypeQuals & QualType::Restrict) 2169 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2170 << "restrict" << SourceRange(D.getIdentifierLoc()); 2171 D.setInvalidType(); 2172 } 2173 2174 // Make sure we don't have any parameters. 2175 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2176 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2177 2178 // Delete the parameters. 2179 FTI.freeArgs(); 2180 D.setInvalidType(); 2181 } 2182 2183 // Make sure the destructor isn't variadic. 2184 if (FTI.isVariadic) { 2185 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2186 D.setInvalidType(); 2187 } 2188 2189 // Rebuild the function type "R" without any type qualifiers or 2190 // parameters (in case any of the errors above fired) and with 2191 // "void" as the return type, since destructors don't have return 2192 // types. We *always* have to do this, because GetTypeForDeclarator 2193 // will put in a result type of "int" when none was specified. 2194 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 2195} 2196 2197/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2198/// well-formednes of the conversion function declarator @p D with 2199/// type @p R. If there are any errors in the declarator, this routine 2200/// will emit diagnostics and return true. Otherwise, it will return 2201/// false. Either way, the type @p R will be updated to reflect a 2202/// well-formed type for the conversion operator. 2203void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2204 FunctionDecl::StorageClass& SC) { 2205 // C++ [class.conv.fct]p1: 2206 // Neither parameter types nor return type can be specified. The 2207 // type of a conversion function (8.3.5) is "function taking no 2208 // parameter returning conversion-type-id." 2209 if (SC == FunctionDecl::Static) { 2210 if (!D.isInvalidType()) 2211 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2212 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2213 << SourceRange(D.getIdentifierLoc()); 2214 D.setInvalidType(); 2215 SC = FunctionDecl::None; 2216 } 2217 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2218 // Conversion functions don't have return types, but the parser will 2219 // happily parse something like: 2220 // 2221 // class X { 2222 // float operator bool(); 2223 // }; 2224 // 2225 // The return type will be changed later anyway. 2226 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2227 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2228 << SourceRange(D.getIdentifierLoc()); 2229 } 2230 2231 // Make sure we don't have any parameters. 2232 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) { 2233 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2234 2235 // Delete the parameters. 2236 D.getTypeObject(0).Fun.freeArgs(); 2237 D.setInvalidType(); 2238 } 2239 2240 // Make sure the conversion function isn't variadic. 2241 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) { 2242 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2243 D.setInvalidType(); 2244 } 2245 2246 // C++ [class.conv.fct]p4: 2247 // The conversion-type-id shall not represent a function type nor 2248 // an array type. 2249 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType()); 2250 if (ConvType->isArrayType()) { 2251 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2252 ConvType = Context.getPointerType(ConvType); 2253 D.setInvalidType(); 2254 } else if (ConvType->isFunctionType()) { 2255 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2256 ConvType = Context.getPointerType(ConvType); 2257 D.setInvalidType(); 2258 } 2259 2260 // Rebuild the function type "R" without any parameters (in case any 2261 // of the errors above fired) and with the conversion type as the 2262 // return type. 2263 R = Context.getFunctionType(ConvType, 0, 0, false, 2264 R->getAs<FunctionProtoType>()->getTypeQuals()); 2265 2266 // C++0x explicit conversion operators. 2267 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2268 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2269 diag::warn_explicit_conversion_functions) 2270 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2271} 2272 2273/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2274/// the declaration of the given C++ conversion function. This routine 2275/// is responsible for recording the conversion function in the C++ 2276/// class, if possible. 2277Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2278 assert(Conversion && "Expected to receive a conversion function declaration"); 2279 2280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2281 2282 // Make sure we aren't redeclaring the conversion function. 2283 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2284 2285 // C++ [class.conv.fct]p1: 2286 // [...] A conversion function is never used to convert a 2287 // (possibly cv-qualified) object to the (possibly cv-qualified) 2288 // same object type (or a reference to it), to a (possibly 2289 // cv-qualified) base class of that type (or a reference to it), 2290 // or to (possibly cv-qualified) void. 2291 // FIXME: Suppress this warning if the conversion function ends up being a 2292 // virtual function that overrides a virtual function in a base class. 2293 QualType ClassType 2294 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2295 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2296 ConvType = ConvTypeRef->getPointeeType(); 2297 if (ConvType->isRecordType()) { 2298 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2299 if (ConvType == ClassType) 2300 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2301 << ClassType; 2302 else if (IsDerivedFrom(ClassType, ConvType)) 2303 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2304 << ClassType << ConvType; 2305 } else if (ConvType->isVoidType()) { 2306 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2307 << ClassType << ConvType; 2308 } 2309 2310 if (Conversion->getPreviousDeclaration()) { 2311 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 2312 if (FunctionTemplateDecl *ConversionTemplate 2313 = Conversion->getDescribedFunctionTemplate()) 2314 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 2315 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 2316 for (OverloadedFunctionDecl::function_iterator 2317 Conv = Conversions->function_begin(), 2318 ConvEnd = Conversions->function_end(); 2319 Conv != ConvEnd; ++Conv) { 2320 if (*Conv == ExpectedPrevDecl) { 2321 *Conv = Conversion; 2322 return DeclPtrTy::make(Conversion); 2323 } 2324 } 2325 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2326 } else if (FunctionTemplateDecl *ConversionTemplate 2327 = Conversion->getDescribedFunctionTemplate()) 2328 ClassDecl->addConversionFunction(ConversionTemplate); 2329 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 2330 ClassDecl->addConversionFunction(Conversion); 2331 2332 return DeclPtrTy::make(Conversion); 2333} 2334 2335//===----------------------------------------------------------------------===// 2336// Namespace Handling 2337//===----------------------------------------------------------------------===// 2338 2339/// ActOnStartNamespaceDef - This is called at the start of a namespace 2340/// definition. 2341Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2342 SourceLocation IdentLoc, 2343 IdentifierInfo *II, 2344 SourceLocation LBrace) { 2345 NamespaceDecl *Namespc = 2346 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2347 Namespc->setLBracLoc(LBrace); 2348 2349 Scope *DeclRegionScope = NamespcScope->getParent(); 2350 2351 if (II) { 2352 // C++ [namespace.def]p2: 2353 // The identifier in an original-namespace-definition shall not have been 2354 // previously defined in the declarative region in which the 2355 // original-namespace-definition appears. The identifier in an 2356 // original-namespace-definition is the name of the namespace. Subsequently 2357 // in that declarative region, it is treated as an original-namespace-name. 2358 2359 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 2360 true); 2361 2362 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2363 // This is an extended namespace definition. 2364 // Attach this namespace decl to the chain of extended namespace 2365 // definitions. 2366 OrigNS->setNextNamespace(Namespc); 2367 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2368 2369 // Remove the previous declaration from the scope. 2370 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2371 IdResolver.RemoveDecl(OrigNS); 2372 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2373 } 2374 } else if (PrevDecl) { 2375 // This is an invalid name redefinition. 2376 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2377 << Namespc->getDeclName(); 2378 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2379 Namespc->setInvalidDecl(); 2380 // Continue on to push Namespc as current DeclContext and return it. 2381 } else if (II->isStr("std") && 2382 CurContext->getLookupContext()->isTranslationUnit()) { 2383 // This is the first "real" definition of the namespace "std", so update 2384 // our cache of the "std" namespace to point at this definition. 2385 if (StdNamespace) { 2386 // We had already defined a dummy namespace "std". Link this new 2387 // namespace definition to the dummy namespace "std". 2388 StdNamespace->setNextNamespace(Namespc); 2389 StdNamespace->setLocation(IdentLoc); 2390 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 2391 } 2392 2393 // Make our StdNamespace cache point at the first real definition of the 2394 // "std" namespace. 2395 StdNamespace = Namespc; 2396 } 2397 2398 PushOnScopeChains(Namespc, DeclRegionScope); 2399 } else { 2400 // FIXME: Handle anonymous namespaces 2401 } 2402 2403 // Although we could have an invalid decl (i.e. the namespace name is a 2404 // redefinition), push it as current DeclContext and try to continue parsing. 2405 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2406 // for the namespace has the declarations that showed up in that particular 2407 // namespace definition. 2408 PushDeclContext(NamespcScope, Namespc); 2409 return DeclPtrTy::make(Namespc); 2410} 2411 2412/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2413/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2414void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2415 Decl *Dcl = D.getAs<Decl>(); 2416 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2417 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2418 Namespc->setRBracLoc(RBrace); 2419 PopDeclContext(); 2420} 2421 2422Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2423 SourceLocation UsingLoc, 2424 SourceLocation NamespcLoc, 2425 const CXXScopeSpec &SS, 2426 SourceLocation IdentLoc, 2427 IdentifierInfo *NamespcName, 2428 AttributeList *AttrList) { 2429 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2430 assert(NamespcName && "Invalid NamespcName."); 2431 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2432 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2433 2434 UsingDirectiveDecl *UDir = 0; 2435 2436 // Lookup namespace name. 2437 LookupResult R = LookupParsedName(S, &SS, NamespcName, 2438 LookupNamespaceName, false); 2439 if (R.isAmbiguous()) { 2440 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 2441 return DeclPtrTy(); 2442 } 2443 if (NamedDecl *NS = R) { 2444 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 2445 // C++ [namespace.udir]p1: 2446 // A using-directive specifies that the names in the nominated 2447 // namespace can be used in the scope in which the 2448 // using-directive appears after the using-directive. During 2449 // unqualified name lookup (3.4.1), the names appear as if they 2450 // were declared in the nearest enclosing namespace which 2451 // contains both the using-directive and the nominated 2452 // namespace. [Note: in this context, "contains" means "contains 2453 // directly or indirectly". ] 2454 2455 // Find enclosing context containing both using-directive and 2456 // nominated namespace. 2457 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2458 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2459 CommonAncestor = CommonAncestor->getParent(); 2460 2461 UDir = UsingDirectiveDecl::Create(Context, 2462 CurContext, UsingLoc, 2463 NamespcLoc, 2464 SS.getRange(), 2465 (NestedNameSpecifier *)SS.getScopeRep(), 2466 IdentLoc, 2467 cast<NamespaceDecl>(NS), 2468 CommonAncestor); 2469 PushUsingDirective(S, UDir); 2470 } else { 2471 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2472 } 2473 2474 // FIXME: We ignore attributes for now. 2475 delete AttrList; 2476 return DeclPtrTy::make(UDir); 2477} 2478 2479void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2480 // If scope has associated entity, then using directive is at namespace 2481 // or translation unit scope. We add UsingDirectiveDecls, into 2482 // it's lookup structure. 2483 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2484 Ctx->addDecl(UDir); 2485 else 2486 // Otherwise it is block-sope. using-directives will affect lookup 2487 // only to the end of scope. 2488 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2489} 2490 2491 2492Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2493 AccessSpecifier AS, 2494 SourceLocation UsingLoc, 2495 const CXXScopeSpec &SS, 2496 SourceLocation IdentLoc, 2497 IdentifierInfo *TargetName, 2498 OverloadedOperatorKind Op, 2499 AttributeList *AttrList, 2500 bool IsTypeName) { 2501 assert((TargetName || Op) && "Invalid TargetName."); 2502 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2503 2504 DeclarationName Name; 2505 if (TargetName) 2506 Name = TargetName; 2507 else 2508 Name = Context.DeclarationNames.getCXXOperatorName(Op); 2509 2510 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc, 2511 Name, AttrList, IsTypeName); 2512 if (UD) { 2513 PushOnScopeChains(UD, S); 2514 UD->setAccess(AS); 2515 } 2516 2517 return DeclPtrTy::make(UD); 2518} 2519 2520NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc, 2521 const CXXScopeSpec &SS, 2522 SourceLocation IdentLoc, 2523 DeclarationName Name, 2524 AttributeList *AttrList, 2525 bool IsTypeName) { 2526 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2527 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2528 2529 // FIXME: We ignore attributes for now. 2530 delete AttrList; 2531 2532 if (SS.isEmpty()) { 2533 Diag(IdentLoc, diag::err_using_requires_qualname); 2534 return 0; 2535 } 2536 2537 NestedNameSpecifier *NNS = 2538 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2539 2540 if (isUnknownSpecialization(SS)) { 2541 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc, 2542 SS.getRange(), NNS, 2543 IdentLoc, Name, IsTypeName); 2544 } 2545 2546 DeclContext *LookupContext = 0; 2547 2548 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 2549 // C++0x N2914 [namespace.udecl]p3: 2550 // A using-declaration used as a member-declaration shall refer to a member 2551 // of a base class of the class being defined, shall refer to a member of an 2552 // anonymous union that is a member of a base class of the class being 2553 // defined, or shall refer to an enumerator for an enumeration type that is 2554 // a member of a base class of the class being defined. 2555 const Type *Ty = NNS->getAsType(); 2556 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) { 2557 Diag(SS.getRange().getBegin(), 2558 diag::err_using_decl_nested_name_specifier_is_not_a_base_class) 2559 << NNS << RD->getDeclName(); 2560 return 0; 2561 } 2562 2563 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0)); 2564 LookupContext = BaseTy->getAs<RecordType>()->getDecl(); 2565 } else { 2566 // C++0x N2914 [namespace.udecl]p8: 2567 // A using-declaration for a class member shall be a member-declaration. 2568 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) { 2569 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member) 2570 << SS.getRange(); 2571 return 0; 2572 } 2573 2574 // C++0x N2914 [namespace.udecl]p9: 2575 // In a using-declaration, a prefix :: refers to the global namespace. 2576 if (NNS->getKind() == NestedNameSpecifier::Global) 2577 LookupContext = Context.getTranslationUnitDecl(); 2578 else 2579 LookupContext = NNS->getAsNamespace(); 2580 } 2581 2582 2583 // Lookup target name. 2584 LookupResult R = LookupQualifiedName(LookupContext, 2585 Name, LookupOrdinaryName); 2586 2587 if (!R) { 2588 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange()); 2589 return 0; 2590 } 2591 2592 NamedDecl *ND = R.getAsDecl(); 2593 2594 if (IsTypeName && !isa<TypeDecl>(ND)) { 2595 Diag(IdentLoc, diag::err_using_typename_non_type); 2596 return 0; 2597 } 2598 2599 // C++0x N2914 [namespace.udecl]p6: 2600 // A using-declaration shall not name a namespace. 2601 if (isa<NamespaceDecl>(ND)) { 2602 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 2603 << SS.getRange(); 2604 return 0; 2605 } 2606 2607 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(), 2608 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName); 2609} 2610 2611/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2612/// is a namespace alias, returns the namespace it points to. 2613static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2614 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2615 return AD->getNamespace(); 2616 return dyn_cast_or_null<NamespaceDecl>(D); 2617} 2618 2619Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 2620 SourceLocation NamespaceLoc, 2621 SourceLocation AliasLoc, 2622 IdentifierInfo *Alias, 2623 const CXXScopeSpec &SS, 2624 SourceLocation IdentLoc, 2625 IdentifierInfo *Ident) { 2626 2627 // Lookup the namespace name. 2628 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false); 2629 2630 // Check if we have a previous declaration with the same name. 2631 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) { 2632 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 2633 // We already have an alias with the same name that points to the same 2634 // namespace, so don't create a new one. 2635 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R)) 2636 return DeclPtrTy(); 2637 } 2638 2639 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 2640 diag::err_redefinition_different_kind; 2641 Diag(AliasLoc, DiagID) << Alias; 2642 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2643 return DeclPtrTy(); 2644 } 2645 2646 if (R.isAmbiguous()) { 2647 DiagnoseAmbiguousLookup(R, Ident, IdentLoc); 2648 return DeclPtrTy(); 2649 } 2650 2651 if (!R) { 2652 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 2653 return DeclPtrTy(); 2654 } 2655 2656 NamespaceAliasDecl *AliasDecl = 2657 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 2658 Alias, SS.getRange(), 2659 (NestedNameSpecifier *)SS.getScopeRep(), 2660 IdentLoc, R); 2661 2662 CurContext->addDecl(AliasDecl); 2663 return DeclPtrTy::make(AliasDecl); 2664} 2665 2666void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2667 CXXConstructorDecl *Constructor) { 2668 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 2669 !Constructor->isUsed()) && 2670 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 2671 2672 CXXRecordDecl *ClassDecl 2673 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 2674 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 2675 // Before the implicitly-declared default constructor for a class is 2676 // implicitly defined, all the implicitly-declared default constructors 2677 // for its base class and its non-static data members shall have been 2678 // implicitly defined. 2679 bool err = false; 2680 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2681 E = ClassDecl->bases_end(); Base != E; ++Base) { 2682 CXXRecordDecl *BaseClassDecl 2683 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2684 if (!BaseClassDecl->hasTrivialConstructor()) { 2685 if (CXXConstructorDecl *BaseCtor = 2686 BaseClassDecl->getDefaultConstructor(Context)) 2687 MarkDeclarationReferenced(CurrentLocation, BaseCtor); 2688 else { 2689 Diag(CurrentLocation, diag::err_defining_default_ctor) 2690 << Context.getTagDeclType(ClassDecl) << 1 2691 << Context.getTagDeclType(BaseClassDecl); 2692 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl) 2693 << Context.getTagDeclType(BaseClassDecl); 2694 err = true; 2695 } 2696 } 2697 } 2698 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2699 E = ClassDecl->field_end(); Field != E; ++Field) { 2700 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2701 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2702 FieldType = Array->getElementType(); 2703 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2704 CXXRecordDecl *FieldClassDecl 2705 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2706 if (!FieldClassDecl->hasTrivialConstructor()) { 2707 if (CXXConstructorDecl *FieldCtor = 2708 FieldClassDecl->getDefaultConstructor(Context)) 2709 MarkDeclarationReferenced(CurrentLocation, FieldCtor); 2710 else { 2711 Diag(CurrentLocation, diag::err_defining_default_ctor) 2712 << Context.getTagDeclType(ClassDecl) << 0 << 2713 Context.getTagDeclType(FieldClassDecl); 2714 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl) 2715 << Context.getTagDeclType(FieldClassDecl); 2716 err = true; 2717 } 2718 } 2719 } else if (FieldType->isReferenceType()) { 2720 Diag(CurrentLocation, diag::err_unintialized_member) 2721 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2722 Diag((*Field)->getLocation(), diag::note_declared_at); 2723 err = true; 2724 } else if (FieldType.isConstQualified()) { 2725 Diag(CurrentLocation, diag::err_unintialized_member) 2726 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2727 Diag((*Field)->getLocation(), diag::note_declared_at); 2728 err = true; 2729 } 2730 } 2731 if (!err) 2732 Constructor->setUsed(); 2733 else 2734 Constructor->setInvalidDecl(); 2735} 2736 2737void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 2738 CXXDestructorDecl *Destructor) { 2739 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 2740 "DefineImplicitDestructor - call it for implicit default dtor"); 2741 2742 CXXRecordDecl *ClassDecl 2743 = cast<CXXRecordDecl>(Destructor->getDeclContext()); 2744 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 2745 // C++ [class.dtor] p5 2746 // Before the implicitly-declared default destructor for a class is 2747 // implicitly defined, all the implicitly-declared default destructors 2748 // for its base class and its non-static data members shall have been 2749 // implicitly defined. 2750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2751 E = ClassDecl->bases_end(); Base != E; ++Base) { 2752 CXXRecordDecl *BaseClassDecl 2753 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2754 if (!BaseClassDecl->hasTrivialDestructor()) { 2755 if (CXXDestructorDecl *BaseDtor = 2756 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 2757 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 2758 else 2759 assert(false && 2760 "DefineImplicitDestructor - missing dtor in a base class"); 2761 } 2762 } 2763 2764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2765 E = ClassDecl->field_end(); Field != E; ++Field) { 2766 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2767 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2768 FieldType = Array->getElementType(); 2769 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2770 CXXRecordDecl *FieldClassDecl 2771 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2772 if (!FieldClassDecl->hasTrivialDestructor()) { 2773 if (CXXDestructorDecl *FieldDtor = 2774 const_cast<CXXDestructorDecl*>( 2775 FieldClassDecl->getDestructor(Context))) 2776 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 2777 else 2778 assert(false && 2779 "DefineImplicitDestructor - missing dtor in class of a data member"); 2780 } 2781 } 2782 } 2783 Destructor->setUsed(); 2784} 2785 2786void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 2787 CXXMethodDecl *MethodDecl) { 2788 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 2789 MethodDecl->getOverloadedOperator() == OO_Equal && 2790 !MethodDecl->isUsed()) && 2791 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 2792 2793 CXXRecordDecl *ClassDecl 2794 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 2795 2796 // C++[class.copy] p12 2797 // Before the implicitly-declared copy assignment operator for a class is 2798 // implicitly defined, all implicitly-declared copy assignment operators 2799 // for its direct base classes and its nonstatic data members shall have 2800 // been implicitly defined. 2801 bool err = false; 2802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2803 E = ClassDecl->bases_end(); Base != E; ++Base) { 2804 CXXRecordDecl *BaseClassDecl 2805 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2806 if (CXXMethodDecl *BaseAssignOpMethod = 2807 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 2808 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 2809 } 2810 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2811 E = ClassDecl->field_end(); Field != E; ++Field) { 2812 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2813 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2814 FieldType = Array->getElementType(); 2815 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2816 CXXRecordDecl *FieldClassDecl 2817 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2818 if (CXXMethodDecl *FieldAssignOpMethod = 2819 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 2820 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 2821 } else if (FieldType->isReferenceType()) { 2822 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2823 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2824 Diag(Field->getLocation(), diag::note_declared_at); 2825 Diag(CurrentLocation, diag::note_first_required_here); 2826 err = true; 2827 } else if (FieldType.isConstQualified()) { 2828 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2829 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2830 Diag(Field->getLocation(), diag::note_declared_at); 2831 Diag(CurrentLocation, diag::note_first_required_here); 2832 err = true; 2833 } 2834 } 2835 if (!err) 2836 MethodDecl->setUsed(); 2837} 2838 2839CXXMethodDecl * 2840Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 2841 CXXRecordDecl *ClassDecl) { 2842 QualType LHSType = Context.getTypeDeclType(ClassDecl); 2843 QualType RHSType(LHSType); 2844 // If class's assignment operator argument is const/volatile qualified, 2845 // look for operator = (const/volatile B&). Otherwise, look for 2846 // operator = (B&). 2847 if (ParmDecl->getType().isConstQualified()) 2848 RHSType.addConst(); 2849 if (ParmDecl->getType().isVolatileQualified()) 2850 RHSType.addVolatile(); 2851 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 2852 LHSType, 2853 SourceLocation())); 2854 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 2855 RHSType, 2856 SourceLocation())); 2857 Expr *Args[2] = { &*LHS, &*RHS }; 2858 OverloadCandidateSet CandidateSet; 2859 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 2860 CandidateSet); 2861 OverloadCandidateSet::iterator Best; 2862 if (BestViableFunction(CandidateSet, 2863 ClassDecl->getLocation(), Best) == OR_Success) 2864 return cast<CXXMethodDecl>(Best->Function); 2865 assert(false && 2866 "getAssignOperatorMethod - copy assignment operator method not found"); 2867 return 0; 2868} 2869 2870void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2871 CXXConstructorDecl *CopyConstructor, 2872 unsigned TypeQuals) { 2873 assert((CopyConstructor->isImplicit() && 2874 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 2875 !CopyConstructor->isUsed()) && 2876 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 2877 2878 CXXRecordDecl *ClassDecl 2879 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 2880 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 2881 // C++ [class.copy] p209 2882 // Before the implicitly-declared copy constructor for a class is 2883 // implicitly defined, all the implicitly-declared copy constructors 2884 // for its base class and its non-static data members shall have been 2885 // implicitly defined. 2886 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2887 Base != ClassDecl->bases_end(); ++Base) { 2888 CXXRecordDecl *BaseClassDecl 2889 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2890 if (CXXConstructorDecl *BaseCopyCtor = 2891 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 2892 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 2893 } 2894 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2895 FieldEnd = ClassDecl->field_end(); 2896 Field != FieldEnd; ++Field) { 2897 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2898 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2899 FieldType = Array->getElementType(); 2900 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2901 CXXRecordDecl *FieldClassDecl 2902 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2903 if (CXXConstructorDecl *FieldCopyCtor = 2904 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 2905 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 2906 } 2907 } 2908 CopyConstructor->setUsed(); 2909} 2910 2911Sema::OwningExprResult 2912Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2913 CXXConstructorDecl *Constructor, 2914 MultiExprArg ExprArgs) { 2915 bool Elidable = false; 2916 2917 // C++ [class.copy]p15: 2918 // Whenever a temporary class object is copied using a copy constructor, and 2919 // this object and the copy have the same cv-unqualified type, an 2920 // implementation is permitted to treat the original and the copy as two 2921 // different ways of referring to the same object and not perform a copy at 2922 // all, even if the class copy constructor or destructor have side effects. 2923 2924 // FIXME: Is this enough? 2925 if (Constructor->isCopyConstructor(Context)) { 2926 Expr *E = ((Expr **)ExprArgs.get())[0]; 2927 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2928 E = BE->getSubExpr(); 2929 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 2930 if (ICE->getCastKind() == CastExpr::CK_NoOp) 2931 E = ICE->getSubExpr(); 2932 2933 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 2934 Elidable = true; 2935 } 2936 2937 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 2938 Elidable, move(ExprArgs)); 2939} 2940 2941/// BuildCXXConstructExpr - Creates a complete call to a constructor, 2942/// including handling of its default argument expressions. 2943Sema::OwningExprResult 2944Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2945 CXXConstructorDecl *Constructor, bool Elidable, 2946 MultiExprArg ExprArgs) { 2947 unsigned NumExprs = ExprArgs.size(); 2948 Expr **Exprs = (Expr **)ExprArgs.release(); 2949 2950 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor, 2951 Elidable, Exprs, NumExprs)); 2952} 2953 2954Sema::OwningExprResult 2955Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 2956 QualType Ty, 2957 SourceLocation TyBeginLoc, 2958 MultiExprArg Args, 2959 SourceLocation RParenLoc) { 2960 unsigned NumExprs = Args.size(); 2961 Expr **Exprs = (Expr **)Args.release(); 2962 2963 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, 2964 TyBeginLoc, Exprs, 2965 NumExprs, RParenLoc)); 2966} 2967 2968 2969bool Sema::InitializeVarWithConstructor(VarDecl *VD, 2970 CXXConstructorDecl *Constructor, 2971 QualType DeclInitType, 2972 MultiExprArg Exprs) { 2973 OwningExprResult TempResult = 2974 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor, 2975 move(Exprs)); 2976 if (TempResult.isInvalid()) 2977 return true; 2978 2979 Expr *Temp = TempResult.takeAs<Expr>(); 2980 MarkDeclarationReferenced(VD->getLocation(), Constructor); 2981 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 2982 VD->setInit(Context, Temp); 2983 2984 return false; 2985} 2986 2987void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) { 2988 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 2989 DeclInitType->getAs<RecordType>()->getDecl()); 2990 if (!ClassDecl->hasTrivialDestructor()) 2991 if (CXXDestructorDecl *Destructor = 2992 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 2993 MarkDeclarationReferenced(VD->getLocation(), Destructor); 2994} 2995 2996/// AddCXXDirectInitializerToDecl - This action is called immediately after 2997/// ActOnDeclarator, when a C++ direct initializer is present. 2998/// e.g: "int x(1);" 2999void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 3000 SourceLocation LParenLoc, 3001 MultiExprArg Exprs, 3002 SourceLocation *CommaLocs, 3003 SourceLocation RParenLoc) { 3004 unsigned NumExprs = Exprs.size(); 3005 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 3006 Decl *RealDecl = Dcl.getAs<Decl>(); 3007 3008 // If there is no declaration, there was an error parsing it. Just ignore 3009 // the initializer. 3010 if (RealDecl == 0) 3011 return; 3012 3013 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 3014 if (!VDecl) { 3015 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3016 RealDecl->setInvalidDecl(); 3017 return; 3018 } 3019 3020 // We will represent direct-initialization similarly to copy-initialization: 3021 // int x(1); -as-> int x = 1; 3022 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 3023 // 3024 // Clients that want to distinguish between the two forms, can check for 3025 // direct initializer using VarDecl::hasCXXDirectInitializer(). 3026 // A major benefit is that clients that don't particularly care about which 3027 // exactly form was it (like the CodeGen) can handle both cases without 3028 // special case code. 3029 3030 // If either the declaration has a dependent type or if any of the expressions 3031 // is type-dependent, we represent the initialization via a ParenListExpr for 3032 // later use during template instantiation. 3033 if (VDecl->getType()->isDependentType() || 3034 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 3035 // Let clients know that initialization was done with a direct initializer. 3036 VDecl->setCXXDirectInitializer(true); 3037 3038 // Store the initialization expressions as a ParenListExpr. 3039 unsigned NumExprs = Exprs.size(); 3040 VDecl->setInit(Context, 3041 new (Context) ParenListExpr(Context, LParenLoc, 3042 (Expr **)Exprs.release(), 3043 NumExprs, RParenLoc)); 3044 return; 3045 } 3046 3047 3048 // C++ 8.5p11: 3049 // The form of initialization (using parentheses or '=') is generally 3050 // insignificant, but does matter when the entity being initialized has a 3051 // class type. 3052 QualType DeclInitType = VDecl->getType(); 3053 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 3054 DeclInitType = Array->getElementType(); 3055 3056 // FIXME: This isn't the right place to complete the type. 3057 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3058 diag::err_typecheck_decl_incomplete_type)) { 3059 VDecl->setInvalidDecl(); 3060 return; 3061 } 3062 3063 if (VDecl->getType()->isRecordType()) { 3064 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 3065 3066 CXXConstructorDecl *Constructor 3067 = PerformInitializationByConstructor(DeclInitType, 3068 move(Exprs), 3069 VDecl->getLocation(), 3070 SourceRange(VDecl->getLocation(), 3071 RParenLoc), 3072 VDecl->getDeclName(), 3073 IK_Direct, 3074 ConstructorArgs); 3075 if (!Constructor) 3076 RealDecl->setInvalidDecl(); 3077 else { 3078 VDecl->setCXXDirectInitializer(true); 3079 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType, 3080 move_arg(ConstructorArgs))) 3081 RealDecl->setInvalidDecl(); 3082 FinalizeVarWithDestructor(VDecl, DeclInitType); 3083 } 3084 return; 3085 } 3086 3087 if (NumExprs > 1) { 3088 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 3089 << SourceRange(VDecl->getLocation(), RParenLoc); 3090 RealDecl->setInvalidDecl(); 3091 return; 3092 } 3093 3094 // Let clients know that initialization was done with a direct initializer. 3095 VDecl->setCXXDirectInitializer(true); 3096 3097 assert(NumExprs == 1 && "Expected 1 expression"); 3098 // Set the init expression, handles conversions. 3099 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 3100 /*DirectInit=*/true); 3101} 3102 3103/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which 3104/// may occur as part of direct-initialization or copy-initialization. 3105/// 3106/// \param ClassType the type of the object being initialized, which must have 3107/// class type. 3108/// 3109/// \param ArgsPtr the arguments provided to initialize the object 3110/// 3111/// \param Loc the source location where the initialization occurs 3112/// 3113/// \param Range the source range that covers the entire initialization 3114/// 3115/// \param InitEntity the name of the entity being initialized, if known 3116/// 3117/// \param Kind the type of initialization being performed 3118/// 3119/// \param ConvertedArgs a vector that will be filled in with the 3120/// appropriately-converted arguments to the constructor (if initialization 3121/// succeeded). 3122/// 3123/// \returns the constructor used to initialize the object, if successful. 3124/// Otherwise, emits a diagnostic and returns NULL. 3125CXXConstructorDecl * 3126Sema::PerformInitializationByConstructor(QualType ClassType, 3127 MultiExprArg ArgsPtr, 3128 SourceLocation Loc, SourceRange Range, 3129 DeclarationName InitEntity, 3130 InitializationKind Kind, 3131 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3132 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 3133 assert(ClassRec && "Can only initialize a class type here"); 3134 Expr **Args = (Expr **)ArgsPtr.get(); 3135 unsigned NumArgs = ArgsPtr.size(); 3136 3137 // C++ [dcl.init]p14: 3138 // If the initialization is direct-initialization, or if it is 3139 // copy-initialization where the cv-unqualified version of the 3140 // source type is the same class as, or a derived class of, the 3141 // class of the destination, constructors are considered. The 3142 // applicable constructors are enumerated (13.3.1.3), and the 3143 // best one is chosen through overload resolution (13.3). The 3144 // constructor so selected is called to initialize the object, 3145 // with the initializer expression(s) as its argument(s). If no 3146 // constructor applies, or the overload resolution is ambiguous, 3147 // the initialization is ill-formed. 3148 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 3149 OverloadCandidateSet CandidateSet; 3150 3151 // Add constructors to the overload set. 3152 DeclarationName ConstructorName 3153 = Context.DeclarationNames.getCXXConstructorName( 3154 Context.getCanonicalType(ClassType.getUnqualifiedType())); 3155 DeclContext::lookup_const_iterator Con, ConEnd; 3156 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 3157 Con != ConEnd; ++Con) { 3158 // Find the constructor (which may be a template). 3159 CXXConstructorDecl *Constructor = 0; 3160 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 3161 if (ConstructorTmpl) 3162 Constructor 3163 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3164 else 3165 Constructor = cast<CXXConstructorDecl>(*Con); 3166 3167 if ((Kind == IK_Direct) || 3168 (Kind == IK_Copy && 3169 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 3170 (Kind == IK_Default && Constructor->isDefaultConstructor())) { 3171 if (ConstructorTmpl) 3172 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, 3173 Args, NumArgs, CandidateSet); 3174 else 3175 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 3176 } 3177 } 3178 3179 // FIXME: When we decide not to synthesize the implicitly-declared 3180 // constructors, we'll need to make them appear here. 3181 3182 OverloadCandidateSet::iterator Best; 3183 switch (BestViableFunction(CandidateSet, Loc, Best)) { 3184 case OR_Success: 3185 // We found a constructor. Break out so that we can convert the arguments 3186 // appropriately. 3187 break; 3188 3189 case OR_No_Viable_Function: 3190 if (InitEntity) 3191 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3192 << InitEntity << Range; 3193 else 3194 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3195 << ClassType << Range; 3196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3197 return 0; 3198 3199 case OR_Ambiguous: 3200 if (InitEntity) 3201 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 3202 else 3203 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 3204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3205 return 0; 3206 3207 case OR_Deleted: 3208 if (InitEntity) 3209 Diag(Loc, diag::err_ovl_deleted_init) 3210 << Best->Function->isDeleted() 3211 << InitEntity << Range; 3212 else 3213 Diag(Loc, diag::err_ovl_deleted_init) 3214 << Best->Function->isDeleted() 3215 << InitEntity << Range; 3216 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3217 return 0; 3218 } 3219 3220 // Convert the arguments, fill in default arguments, etc. 3221 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3222 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs)) 3223 return 0; 3224 3225 return Constructor; 3226} 3227 3228/// \brief Given a constructor and the set of arguments provided for the 3229/// constructor, convert the arguments and add any required default arguments 3230/// to form a proper call to this constructor. 3231/// 3232/// \returns true if an error occurred, false otherwise. 3233bool 3234Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 3235 MultiExprArg ArgsPtr, 3236 SourceLocation Loc, 3237 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 3238 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 3239 unsigned NumArgs = ArgsPtr.size(); 3240 Expr **Args = (Expr **)ArgsPtr.get(); 3241 3242 const FunctionProtoType *Proto 3243 = Constructor->getType()->getAs<FunctionProtoType>(); 3244 assert(Proto && "Constructor without a prototype?"); 3245 unsigned NumArgsInProto = Proto->getNumArgs(); 3246 unsigned NumArgsToCheck = NumArgs; 3247 3248 // If too few arguments are available, we'll fill in the rest with defaults. 3249 if (NumArgs < NumArgsInProto) { 3250 NumArgsToCheck = NumArgsInProto; 3251 ConvertedArgs.reserve(NumArgsInProto); 3252 } else { 3253 ConvertedArgs.reserve(NumArgs); 3254 if (NumArgs > NumArgsInProto) 3255 NumArgsToCheck = NumArgsInProto; 3256 } 3257 3258 // Convert arguments 3259 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3260 QualType ProtoArgType = Proto->getArgType(i); 3261 3262 Expr *Arg; 3263 if (i < NumArgs) { 3264 Arg = Args[i]; 3265 3266 // Pass the argument. 3267 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3268 return true; 3269 3270 Args[i] = 0; 3271 } else { 3272 ParmVarDecl *Param = Constructor->getParamDecl(i); 3273 3274 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param); 3275 if (DefArg.isInvalid()) 3276 return true; 3277 3278 Arg = DefArg.takeAs<Expr>(); 3279 } 3280 3281 ConvertedArgs.push_back(Arg); 3282 } 3283 3284 // If this is a variadic call, handle args passed through "...". 3285 if (Proto->isVariadic()) { 3286 // Promote the arguments (C99 6.5.2.2p7). 3287 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3288 Expr *Arg = Args[i]; 3289 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor)) 3290 return true; 3291 3292 ConvertedArgs.push_back(Arg); 3293 Args[i] = 0; 3294 } 3295 } 3296 3297 return false; 3298} 3299 3300/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3301/// determine whether they are reference-related, 3302/// reference-compatible, reference-compatible with added 3303/// qualification, or incompatible, for use in C++ initialization by 3304/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3305/// type, and the first type (T1) is the pointee type of the reference 3306/// type being initialized. 3307Sema::ReferenceCompareResult 3308Sema::CompareReferenceRelationship(QualType T1, QualType T2, 3309 bool& DerivedToBase) { 3310 assert(!T1->isReferenceType() && 3311 "T1 must be the pointee type of the reference type"); 3312 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 3313 3314 T1 = Context.getCanonicalType(T1); 3315 T2 = Context.getCanonicalType(T2); 3316 QualType UnqualT1 = T1.getUnqualifiedType(); 3317 QualType UnqualT2 = T2.getUnqualifiedType(); 3318 3319 // C++ [dcl.init.ref]p4: 3320 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3321 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3322 // T1 is a base class of T2. 3323 if (UnqualT1 == UnqualT2) 3324 DerivedToBase = false; 3325 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 3326 DerivedToBase = true; 3327 else 3328 return Ref_Incompatible; 3329 3330 // At this point, we know that T1 and T2 are reference-related (at 3331 // least). 3332 3333 // C++ [dcl.init.ref]p4: 3334 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3335 // reference-related to T2 and cv1 is the same cv-qualification 3336 // as, or greater cv-qualification than, cv2. For purposes of 3337 // overload resolution, cases for which cv1 is greater 3338 // cv-qualification than cv2 are identified as 3339 // reference-compatible with added qualification (see 13.3.3.2). 3340 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3341 return Ref_Compatible; 3342 else if (T1.isMoreQualifiedThan(T2)) 3343 return Ref_Compatible_With_Added_Qualification; 3344 else 3345 return Ref_Related; 3346} 3347 3348/// CheckReferenceInit - Check the initialization of a reference 3349/// variable with the given initializer (C++ [dcl.init.ref]). Init is 3350/// the initializer (either a simple initializer or an initializer 3351/// list), and DeclType is the type of the declaration. When ICS is 3352/// non-null, this routine will compute the implicit conversion 3353/// sequence according to C++ [over.ics.ref] and will not produce any 3354/// diagnostics; when ICS is null, it will emit diagnostics when any 3355/// errors are found. Either way, a return value of true indicates 3356/// that there was a failure, a return value of false indicates that 3357/// the reference initialization succeeded. 3358/// 3359/// When @p SuppressUserConversions, user-defined conversions are 3360/// suppressed. 3361/// When @p AllowExplicit, we also permit explicit user-defined 3362/// conversion functions. 3363/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 3364bool 3365Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 3366 bool SuppressUserConversions, 3367 bool AllowExplicit, bool ForceRValue, 3368 ImplicitConversionSequence *ICS) { 3369 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3370 3371 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3372 QualType T2 = Init->getType(); 3373 3374 // If the initializer is the address of an overloaded function, try 3375 // to resolve the overloaded function. If all goes well, T2 is the 3376 // type of the resulting function. 3377 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 3378 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 3379 ICS != 0); 3380 if (Fn) { 3381 // Since we're performing this reference-initialization for 3382 // real, update the initializer with the resulting function. 3383 if (!ICS) { 3384 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin())) 3385 return true; 3386 3387 FixOverloadedFunctionReference(Init, Fn); 3388 } 3389 3390 T2 = Fn->getType(); 3391 } 3392 } 3393 3394 // Compute some basic properties of the types and the initializer. 3395 bool isRValRef = DeclType->isRValueReferenceType(); 3396 bool DerivedToBase = false; 3397 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 3398 Init->isLvalue(Context); 3399 ReferenceCompareResult RefRelationship 3400 = CompareReferenceRelationship(T1, T2, DerivedToBase); 3401 3402 // Most paths end in a failed conversion. 3403 if (ICS) 3404 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 3405 3406 // C++ [dcl.init.ref]p5: 3407 // A reference to type "cv1 T1" is initialized by an expression 3408 // of type "cv2 T2" as follows: 3409 3410 // -- If the initializer expression 3411 3412 // Rvalue references cannot bind to lvalues (N2812). 3413 // There is absolutely no situation where they can. In particular, note that 3414 // this is ill-formed, even if B has a user-defined conversion to A&&: 3415 // B b; 3416 // A&& r = b; 3417 if (isRValRef && InitLvalue == Expr::LV_Valid) { 3418 if (!ICS) 3419 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref) 3420 << Init->getSourceRange(); 3421 return true; 3422 } 3423 3424 bool BindsDirectly = false; 3425 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3426 // reference-compatible with "cv2 T2," or 3427 // 3428 // Note that the bit-field check is skipped if we are just computing 3429 // the implicit conversion sequence (C++ [over.best.ics]p2). 3430 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 3431 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3432 BindsDirectly = true; 3433 3434 if (ICS) { 3435 // C++ [over.ics.ref]p1: 3436 // When a parameter of reference type binds directly (8.5.3) 3437 // to an argument expression, the implicit conversion sequence 3438 // is the identity conversion, unless the argument expression 3439 // has a type that is a derived class of the parameter type, 3440 // in which case the implicit conversion sequence is a 3441 // derived-to-base Conversion (13.3.3.1). 3442 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3443 ICS->Standard.First = ICK_Identity; 3444 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3445 ICS->Standard.Third = ICK_Identity; 3446 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3447 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3448 ICS->Standard.ReferenceBinding = true; 3449 ICS->Standard.DirectBinding = true; 3450 ICS->Standard.RRefBinding = false; 3451 ICS->Standard.CopyConstructor = 0; 3452 3453 // Nothing more to do: the inaccessibility/ambiguity check for 3454 // derived-to-base conversions is suppressed when we're 3455 // computing the implicit conversion sequence (C++ 3456 // [over.best.ics]p2). 3457 return false; 3458 } else { 3459 // Perform the conversion. 3460 CastExpr::CastKind CK = CastExpr::CK_NoOp; 3461 if (DerivedToBase) 3462 CK = CastExpr::CK_DerivedToBase; 3463 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true); 3464 } 3465 } 3466 3467 // -- has a class type (i.e., T2 is a class type) and can be 3468 // implicitly converted to an lvalue of type "cv3 T3," 3469 // where "cv1 T1" is reference-compatible with "cv3 T3" 3470 // 92) (this conversion is selected by enumerating the 3471 // applicable conversion functions (13.3.1.6) and choosing 3472 // the best one through overload resolution (13.3)), 3473 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 3474 !RequireCompleteType(SourceLocation(), T2, 0)) { 3475 CXXRecordDecl *T2RecordDecl 3476 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3477 3478 OverloadCandidateSet CandidateSet; 3479 OverloadedFunctionDecl *Conversions 3480 = T2RecordDecl->getVisibleConversionFunctions(); 3481 for (OverloadedFunctionDecl::function_iterator Func 3482 = Conversions->function_begin(); 3483 Func != Conversions->function_end(); ++Func) { 3484 FunctionTemplateDecl *ConvTemplate 3485 = dyn_cast<FunctionTemplateDecl>(*Func); 3486 CXXConversionDecl *Conv; 3487 if (ConvTemplate) 3488 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3489 else 3490 Conv = cast<CXXConversionDecl>(*Func); 3491 3492 // If the conversion function doesn't return a reference type, 3493 // it can't be considered for this conversion. 3494 if (Conv->getConversionType()->isLValueReferenceType() && 3495 (AllowExplicit || !Conv->isExplicit())) { 3496 if (ConvTemplate) 3497 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 3498 CandidateSet); 3499 else 3500 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 3501 } 3502 } 3503 3504 OverloadCandidateSet::iterator Best; 3505 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) { 3506 case OR_Success: 3507 // This is a direct binding. 3508 BindsDirectly = true; 3509 3510 if (ICS) { 3511 // C++ [over.ics.ref]p1: 3512 // 3513 // [...] If the parameter binds directly to the result of 3514 // applying a conversion function to the argument 3515 // expression, the implicit conversion sequence is a 3516 // user-defined conversion sequence (13.3.3.1.2), with the 3517 // second standard conversion sequence either an identity 3518 // conversion or, if the conversion function returns an 3519 // entity of a type that is a derived class of the parameter 3520 // type, a derived-to-base Conversion. 3521 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 3522 ICS->UserDefined.Before = Best->Conversions[0].Standard; 3523 ICS->UserDefined.After = Best->FinalConversion; 3524 ICS->UserDefined.ConversionFunction = Best->Function; 3525 assert(ICS->UserDefined.After.ReferenceBinding && 3526 ICS->UserDefined.After.DirectBinding && 3527 "Expected a direct reference binding!"); 3528 return false; 3529 } else { 3530 // Perform the conversion. 3531 // FIXME: Binding to a subobject of the lvalue is going to require more 3532 // AST annotation than this. 3533 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 3534 } 3535 break; 3536 3537 case OR_Ambiguous: 3538 assert(false && "Ambiguous reference binding conversions not implemented."); 3539 return true; 3540 3541 case OR_No_Viable_Function: 3542 case OR_Deleted: 3543 // There was no suitable conversion, or we found a deleted 3544 // conversion; continue with other checks. 3545 break; 3546 } 3547 } 3548 3549 if (BindsDirectly) { 3550 // C++ [dcl.init.ref]p4: 3551 // [...] In all cases where the reference-related or 3552 // reference-compatible relationship of two types is used to 3553 // establish the validity of a reference binding, and T1 is a 3554 // base class of T2, a program that necessitates such a binding 3555 // is ill-formed if T1 is an inaccessible (clause 11) or 3556 // ambiguous (10.2) base class of T2. 3557 // 3558 // Note that we only check this condition when we're allowed to 3559 // complain about errors, because we should not be checking for 3560 // ambiguity (or inaccessibility) unless the reference binding 3561 // actually happens. 3562 if (DerivedToBase) 3563 return CheckDerivedToBaseConversion(T2, T1, 3564 Init->getSourceRange().getBegin(), 3565 Init->getSourceRange()); 3566 else 3567 return false; 3568 } 3569 3570 // -- Otherwise, the reference shall be to a non-volatile const 3571 // type (i.e., cv1 shall be const), or the reference shall be an 3572 // rvalue reference and the initializer expression shall be an rvalue. 3573 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) { 3574 if (!ICS) 3575 Diag(Init->getSourceRange().getBegin(), 3576 diag::err_not_reference_to_const_init) 3577 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3578 << T2 << Init->getSourceRange(); 3579 return true; 3580 } 3581 3582 // -- If the initializer expression is an rvalue, with T2 a 3583 // class type, and "cv1 T1" is reference-compatible with 3584 // "cv2 T2," the reference is bound in one of the 3585 // following ways (the choice is implementation-defined): 3586 // 3587 // -- The reference is bound to the object represented by 3588 // the rvalue (see 3.10) or to a sub-object within that 3589 // object. 3590 // 3591 // -- A temporary of type "cv1 T2" [sic] is created, and 3592 // a constructor is called to copy the entire rvalue 3593 // object into the temporary. The reference is bound to 3594 // the temporary or to a sub-object within the 3595 // temporary. 3596 // 3597 // The constructor that would be used to make the copy 3598 // shall be callable whether or not the copy is actually 3599 // done. 3600 // 3601 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 3602 // freedom, so we will always take the first option and never build 3603 // a temporary in this case. FIXME: We will, however, have to check 3604 // for the presence of a copy constructor in C++98/03 mode. 3605 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 3606 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3607 if (ICS) { 3608 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3609 ICS->Standard.First = ICK_Identity; 3610 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3611 ICS->Standard.Third = ICK_Identity; 3612 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3613 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3614 ICS->Standard.ReferenceBinding = true; 3615 ICS->Standard.DirectBinding = false; 3616 ICS->Standard.RRefBinding = isRValRef; 3617 ICS->Standard.CopyConstructor = 0; 3618 } else { 3619 CastExpr::CastKind CK = CastExpr::CK_NoOp; 3620 if (DerivedToBase) 3621 CK = CastExpr::CK_DerivedToBase; 3622 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false); 3623 } 3624 return false; 3625 } 3626 3627 // -- Otherwise, a temporary of type "cv1 T1" is created and 3628 // initialized from the initializer expression using the 3629 // rules for a non-reference copy initialization (8.5). The 3630 // reference is then bound to the temporary. If T1 is 3631 // reference-related to T2, cv1 must be the same 3632 // cv-qualification as, or greater cv-qualification than, 3633 // cv2; otherwise, the program is ill-formed. 3634 if (RefRelationship == Ref_Related) { 3635 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3636 // we would be reference-compatible or reference-compatible with 3637 // added qualification. But that wasn't the case, so the reference 3638 // initialization fails. 3639 if (!ICS) 3640 Diag(Init->getSourceRange().getBegin(), 3641 diag::err_reference_init_drops_quals) 3642 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3643 << T2 << Init->getSourceRange(); 3644 return true; 3645 } 3646 3647 // If at least one of the types is a class type, the types are not 3648 // related, and we aren't allowed any user conversions, the 3649 // reference binding fails. This case is important for breaking 3650 // recursion, since TryImplicitConversion below will attempt to 3651 // create a temporary through the use of a copy constructor. 3652 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 3653 (T1->isRecordType() || T2->isRecordType())) { 3654 if (!ICS) 3655 Diag(Init->getSourceRange().getBegin(), 3656 diag::err_typecheck_convert_incompatible) 3657 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 3658 return true; 3659 } 3660 3661 // Actually try to convert the initializer to T1. 3662 if (ICS) { 3663 // C++ [over.ics.ref]p2: 3664 // 3665 // When a parameter of reference type is not bound directly to 3666 // an argument expression, the conversion sequence is the one 3667 // required to convert the argument expression to the 3668 // underlying type of the reference according to 3669 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3670 // to copy-initializing a temporary of the underlying type with 3671 // the argument expression. Any difference in top-level 3672 // cv-qualification is subsumed by the initialization itself 3673 // and does not constitute a conversion. 3674 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 3675 /*AllowExplicit=*/false, 3676 /*ForceRValue=*/false, 3677 /*InOverloadResolution=*/false); 3678 3679 // Of course, that's still a reference binding. 3680 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 3681 ICS->Standard.ReferenceBinding = true; 3682 ICS->Standard.RRefBinding = isRValRef; 3683 } else if (ICS->ConversionKind == 3684 ImplicitConversionSequence::UserDefinedConversion) { 3685 ICS->UserDefined.After.ReferenceBinding = true; 3686 ICS->UserDefined.After.RRefBinding = isRValRef; 3687 } 3688 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 3689 } else { 3690 ImplicitConversionSequence Conversions; 3691 bool badConversion = PerformImplicitConversion(Init, T1, "initializing", 3692 false, false, 3693 Conversions); 3694 if (badConversion) { 3695 if ((Conversions.ConversionKind == 3696 ImplicitConversionSequence::BadConversion) 3697 && Conversions.ConversionFunctionSet.size() > 0) { 3698 Diag(Init->getSourceRange().getBegin(), 3699 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange(); 3700 for (int j = Conversions.ConversionFunctionSet.size()-1; 3701 j >= 0; j--) { 3702 FunctionDecl *Func = Conversions.ConversionFunctionSet[j]; 3703 Diag(Func->getLocation(), diag::err_ovl_candidate); 3704 } 3705 } 3706 else 3707 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref) 3708 << Init->getSourceRange(); 3709 } 3710 return badConversion; 3711 } 3712} 3713 3714/// CheckOverloadedOperatorDeclaration - Check whether the declaration 3715/// of this overloaded operator is well-formed. If so, returns false; 3716/// otherwise, emits appropriate diagnostics and returns true. 3717bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 3718 assert(FnDecl && FnDecl->isOverloadedOperator() && 3719 "Expected an overloaded operator declaration"); 3720 3721 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 3722 3723 // C++ [over.oper]p5: 3724 // The allocation and deallocation functions, operator new, 3725 // operator new[], operator delete and operator delete[], are 3726 // described completely in 3.7.3. The attributes and restrictions 3727 // found in the rest of this subclause do not apply to them unless 3728 // explicitly stated in 3.7.3. 3729 // FIXME: Write a separate routine for checking this. For now, just allow it. 3730 if (Op == OO_New || Op == OO_Array_New || 3731 Op == OO_Delete || Op == OO_Array_Delete) 3732 return false; 3733 3734 // C++ [over.oper]p6: 3735 // An operator function shall either be a non-static member 3736 // function or be a non-member function and have at least one 3737 // parameter whose type is a class, a reference to a class, an 3738 // enumeration, or a reference to an enumeration. 3739 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 3740 if (MethodDecl->isStatic()) 3741 return Diag(FnDecl->getLocation(), 3742 diag::err_operator_overload_static) << FnDecl->getDeclName(); 3743 } else { 3744 bool ClassOrEnumParam = false; 3745 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 3746 ParamEnd = FnDecl->param_end(); 3747 Param != ParamEnd; ++Param) { 3748 QualType ParamType = (*Param)->getType().getNonReferenceType(); 3749 if (ParamType->isDependentType() || ParamType->isRecordType() || 3750 ParamType->isEnumeralType()) { 3751 ClassOrEnumParam = true; 3752 break; 3753 } 3754 } 3755 3756 if (!ClassOrEnumParam) 3757 return Diag(FnDecl->getLocation(), 3758 diag::err_operator_overload_needs_class_or_enum) 3759 << FnDecl->getDeclName(); 3760 } 3761 3762 // C++ [over.oper]p8: 3763 // An operator function cannot have default arguments (8.3.6), 3764 // except where explicitly stated below. 3765 // 3766 // Only the function-call operator allows default arguments 3767 // (C++ [over.call]p1). 3768 if (Op != OO_Call) { 3769 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 3770 Param != FnDecl->param_end(); ++Param) { 3771 if ((*Param)->hasUnparsedDefaultArg()) 3772 return Diag((*Param)->getLocation(), 3773 diag::err_operator_overload_default_arg) 3774 << FnDecl->getDeclName(); 3775 else if (Expr *DefArg = (*Param)->getDefaultArg()) 3776 return Diag((*Param)->getLocation(), 3777 diag::err_operator_overload_default_arg) 3778 << FnDecl->getDeclName() << DefArg->getSourceRange(); 3779 } 3780 } 3781 3782 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 3783 { false, false, false } 3784#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3785 , { Unary, Binary, MemberOnly } 3786#include "clang/Basic/OperatorKinds.def" 3787 }; 3788 3789 bool CanBeUnaryOperator = OperatorUses[Op][0]; 3790 bool CanBeBinaryOperator = OperatorUses[Op][1]; 3791 bool MustBeMemberOperator = OperatorUses[Op][2]; 3792 3793 // C++ [over.oper]p8: 3794 // [...] Operator functions cannot have more or fewer parameters 3795 // than the number required for the corresponding operator, as 3796 // described in the rest of this subclause. 3797 unsigned NumParams = FnDecl->getNumParams() 3798 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 3799 if (Op != OO_Call && 3800 ((NumParams == 1 && !CanBeUnaryOperator) || 3801 (NumParams == 2 && !CanBeBinaryOperator) || 3802 (NumParams < 1) || (NumParams > 2))) { 3803 // We have the wrong number of parameters. 3804 unsigned ErrorKind; 3805 if (CanBeUnaryOperator && CanBeBinaryOperator) { 3806 ErrorKind = 2; // 2 -> unary or binary. 3807 } else if (CanBeUnaryOperator) { 3808 ErrorKind = 0; // 0 -> unary 3809 } else { 3810 assert(CanBeBinaryOperator && 3811 "All non-call overloaded operators are unary or binary!"); 3812 ErrorKind = 1; // 1 -> binary 3813 } 3814 3815 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 3816 << FnDecl->getDeclName() << NumParams << ErrorKind; 3817 } 3818 3819 // Overloaded operators other than operator() cannot be variadic. 3820 if (Op != OO_Call && 3821 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 3822 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 3823 << FnDecl->getDeclName(); 3824 } 3825 3826 // Some operators must be non-static member functions. 3827 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 3828 return Diag(FnDecl->getLocation(), 3829 diag::err_operator_overload_must_be_member) 3830 << FnDecl->getDeclName(); 3831 } 3832 3833 // C++ [over.inc]p1: 3834 // The user-defined function called operator++ implements the 3835 // prefix and postfix ++ operator. If this function is a member 3836 // function with no parameters, or a non-member function with one 3837 // parameter of class or enumeration type, it defines the prefix 3838 // increment operator ++ for objects of that type. If the function 3839 // is a member function with one parameter (which shall be of type 3840 // int) or a non-member function with two parameters (the second 3841 // of which shall be of type int), it defines the postfix 3842 // increment operator ++ for objects of that type. 3843 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 3844 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 3845 bool ParamIsInt = false; 3846 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 3847 ParamIsInt = BT->getKind() == BuiltinType::Int; 3848 3849 if (!ParamIsInt) 3850 return Diag(LastParam->getLocation(), 3851 diag::err_operator_overload_post_incdec_must_be_int) 3852 << LastParam->getType() << (Op == OO_MinusMinus); 3853 } 3854 3855 // Notify the class if it got an assignment operator. 3856 if (Op == OO_Equal) { 3857 // Would have returned earlier otherwise. 3858 assert(isa<CXXMethodDecl>(FnDecl) && 3859 "Overloaded = not member, but not filtered."); 3860 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 3861 Method->setCopyAssignment(true); 3862 Method->getParent()->addedAssignmentOperator(Context, Method); 3863 } 3864 3865 return false; 3866} 3867 3868/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 3869/// linkage specification, including the language and (if present) 3870/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 3871/// the location of the language string literal, which is provided 3872/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 3873/// the '{' brace. Otherwise, this linkage specification does not 3874/// have any braces. 3875Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 3876 SourceLocation ExternLoc, 3877 SourceLocation LangLoc, 3878 const char *Lang, 3879 unsigned StrSize, 3880 SourceLocation LBraceLoc) { 3881 LinkageSpecDecl::LanguageIDs Language; 3882 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3883 Language = LinkageSpecDecl::lang_c; 3884 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3885 Language = LinkageSpecDecl::lang_cxx; 3886 else { 3887 Diag(LangLoc, diag::err_bad_language); 3888 return DeclPtrTy(); 3889 } 3890 3891 // FIXME: Add all the various semantics of linkage specifications 3892 3893 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 3894 LangLoc, Language, 3895 LBraceLoc.isValid()); 3896 CurContext->addDecl(D); 3897 PushDeclContext(S, D); 3898 return DeclPtrTy::make(D); 3899} 3900 3901/// ActOnFinishLinkageSpecification - Completely the definition of 3902/// the C++ linkage specification LinkageSpec. If RBraceLoc is 3903/// valid, it's the position of the closing '}' brace in a linkage 3904/// specification that uses braces. 3905Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 3906 DeclPtrTy LinkageSpec, 3907 SourceLocation RBraceLoc) { 3908 if (LinkageSpec) 3909 PopDeclContext(); 3910 return LinkageSpec; 3911} 3912 3913/// \brief Perform semantic analysis for the variable declaration that 3914/// occurs within a C++ catch clause, returning the newly-created 3915/// variable. 3916VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 3917 DeclaratorInfo *DInfo, 3918 IdentifierInfo *Name, 3919 SourceLocation Loc, 3920 SourceRange Range) { 3921 bool Invalid = false; 3922 3923 // Arrays and functions decay. 3924 if (ExDeclType->isArrayType()) 3925 ExDeclType = Context.getArrayDecayedType(ExDeclType); 3926 else if (ExDeclType->isFunctionType()) 3927 ExDeclType = Context.getPointerType(ExDeclType); 3928 3929 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 3930 // The exception-declaration shall not denote a pointer or reference to an 3931 // incomplete type, other than [cv] void*. 3932 // N2844 forbids rvalue references. 3933 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 3934 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 3935 Invalid = true; 3936 } 3937 3938 QualType BaseType = ExDeclType; 3939 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 3940 unsigned DK = diag::err_catch_incomplete; 3941 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 3942 BaseType = Ptr->getPointeeType(); 3943 Mode = 1; 3944 DK = diag::err_catch_incomplete_ptr; 3945 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 3946 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 3947 BaseType = Ref->getPointeeType(); 3948 Mode = 2; 3949 DK = diag::err_catch_incomplete_ref; 3950 } 3951 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 3952 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 3953 Invalid = true; 3954 3955 if (!Invalid && !ExDeclType->isDependentType() && 3956 RequireNonAbstractType(Loc, ExDeclType, 3957 diag::err_abstract_type_in_decl, 3958 AbstractVariableType)) 3959 Invalid = true; 3960 3961 // FIXME: Need to test for ability to copy-construct and destroy the 3962 // exception variable. 3963 3964 // FIXME: Need to check for abstract classes. 3965 3966 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 3967 Name, ExDeclType, DInfo, VarDecl::None); 3968 3969 if (Invalid) 3970 ExDecl->setInvalidDecl(); 3971 3972 return ExDecl; 3973} 3974 3975/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 3976/// handler. 3977Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 3978 DeclaratorInfo *DInfo = 0; 3979 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 3980 3981 bool Invalid = D.isInvalidType(); 3982 IdentifierInfo *II = D.getIdentifier(); 3983 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3984 // The scope should be freshly made just for us. There is just no way 3985 // it contains any previous declaration. 3986 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 3987 if (PrevDecl->isTemplateParameter()) { 3988 // Maybe we will complain about the shadowed template parameter. 3989 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3990 } 3991 } 3992 3993 if (D.getCXXScopeSpec().isSet() && !Invalid) { 3994 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 3995 << D.getCXXScopeSpec().getRange(); 3996 Invalid = true; 3997 } 3998 3999 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 4000 D.getIdentifier(), 4001 D.getIdentifierLoc(), 4002 D.getDeclSpec().getSourceRange()); 4003 4004 if (Invalid) 4005 ExDecl->setInvalidDecl(); 4006 4007 // Add the exception declaration into this scope. 4008 if (II) 4009 PushOnScopeChains(ExDecl, S); 4010 else 4011 CurContext->addDecl(ExDecl); 4012 4013 ProcessDeclAttributes(S, ExDecl, D); 4014 return DeclPtrTy::make(ExDecl); 4015} 4016 4017Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 4018 ExprArg assertexpr, 4019 ExprArg assertmessageexpr) { 4020 Expr *AssertExpr = (Expr *)assertexpr.get(); 4021 StringLiteral *AssertMessage = 4022 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 4023 4024 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 4025 llvm::APSInt Value(32); 4026 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 4027 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 4028 AssertExpr->getSourceRange(); 4029 return DeclPtrTy(); 4030 } 4031 4032 if (Value == 0) { 4033 std::string str(AssertMessage->getStrData(), 4034 AssertMessage->getByteLength()); 4035 Diag(AssertLoc, diag::err_static_assert_failed) 4036 << str << AssertExpr->getSourceRange(); 4037 } 4038 } 4039 4040 assertexpr.release(); 4041 assertmessageexpr.release(); 4042 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 4043 AssertExpr, AssertMessage); 4044 4045 CurContext->addDecl(Decl); 4046 return DeclPtrTy::make(Decl); 4047} 4048 4049/// Handle a friend type declaration. This works in tandem with 4050/// ActOnTag. 4051/// 4052/// Notes on friend class templates: 4053/// 4054/// We generally treat friend class declarations as if they were 4055/// declaring a class. So, for example, the elaborated type specifier 4056/// in a friend declaration is required to obey the restrictions of a 4057/// class-head (i.e. no typedefs in the scope chain), template 4058/// parameters are required to match up with simple template-ids, &c. 4059/// However, unlike when declaring a template specialization, it's 4060/// okay to refer to a template specialization without an empty 4061/// template parameter declaration, e.g. 4062/// friend class A<T>::B<unsigned>; 4063/// We permit this as a special case; if there are any template 4064/// parameters present at all, require proper matching, i.e. 4065/// template <> template <class T> friend class A<int>::B; 4066Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, 4067 const DeclSpec &DS, 4068 MultiTemplateParamsArg TempParams) { 4069 SourceLocation Loc = DS.getSourceRange().getBegin(); 4070 4071 assert(DS.isFriendSpecified()); 4072 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4073 4074 // Try to convert the decl specifier to a type. This works for 4075 // friend templates because ActOnTag never produces a ClassTemplateDecl 4076 // for a TUK_Friend. 4077 bool invalid = false; 4078 QualType T = ConvertDeclSpecToType(DS, Loc, invalid); 4079 if (invalid) return DeclPtrTy(); 4080 4081 // This is definitely an error in C++98. It's probably meant to 4082 // be forbidden in C++0x, too, but the specification is just 4083 // poorly written. 4084 // 4085 // The problem is with declarations like the following: 4086 // template <T> friend A<T>::foo; 4087 // where deciding whether a class C is a friend or not now hinges 4088 // on whether there exists an instantiation of A that causes 4089 // 'foo' to equal C. There are restrictions on class-heads 4090 // (which we declare (by fiat) elaborated friend declarations to 4091 // be) that makes this tractable. 4092 // 4093 // FIXME: handle "template <> friend class A<T>;", which 4094 // is possibly well-formed? Who even knows? 4095 if (TempParams.size() && !isa<ElaboratedType>(T)) { 4096 Diag(Loc, diag::err_tagless_friend_type_template) 4097 << DS.getSourceRange(); 4098 return DeclPtrTy(); 4099 } 4100 4101 // C++ [class.friend]p2: 4102 // An elaborated-type-specifier shall be used in a friend declaration 4103 // for a class.* 4104 // * The class-key of the elaborated-type-specifier is required. 4105 // This is one of the rare places in Clang where it's legitimate to 4106 // ask about the "spelling" of the type. 4107 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 4108 // If we evaluated the type to a record type, suggest putting 4109 // a tag in front. 4110 if (const RecordType *RT = T->getAs<RecordType>()) { 4111 RecordDecl *RD = RT->getDecl(); 4112 4113 std::string InsertionText = std::string(" ") + RD->getKindName(); 4114 4115 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type) 4116 << (RD->isUnion()) 4117 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 4118 InsertionText); 4119 return DeclPtrTy(); 4120 }else { 4121 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 4122 << DS.getSourceRange(); 4123 return DeclPtrTy(); 4124 } 4125 } 4126 4127 bool IsDefinition = false; 4128 4129 // We want to do a few things differently if the type was declared with 4130 // a tag: specifically, we want to use the associated RecordDecl as 4131 // the object of our friend declaration, and we want to disallow 4132 // class definitions. 4133 switch (DS.getTypeSpecType()) { 4134 default: break; 4135 case DeclSpec::TST_class: 4136 case DeclSpec::TST_struct: 4137 case DeclSpec::TST_union: 4138 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep()); 4139 if (RD) 4140 IsDefinition |= RD->isDefinition(); 4141 break; 4142 } 4143 4144 // C++ [class.friend]p2: A class shall not be defined inside 4145 // a friend declaration. 4146 if (IsDefinition) { 4147 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class) 4148 << DS.getSourceRange(); 4149 return DeclPtrTy(); 4150 } 4151 4152 // C++98 [class.friend]p1: A friend of a class is a function 4153 // or class that is not a member of the class . . . 4154 // But that's a silly restriction which nobody implements for 4155 // inner classes, and C++0x removes it anyway, so we only report 4156 // this (as a warning) if we're being pedantic. 4157 if (!getLangOptions().CPlusPlus0x) 4158 if (const RecordType *RT = T->getAs<RecordType>()) 4159 if (RT->getDecl()->getDeclContext() == CurContext) 4160 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 4161 4162 Decl *D; 4163 if (TempParams.size()) 4164 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 4165 TempParams.size(), 4166 (TemplateParameterList**) TempParams.release(), 4167 T.getTypePtr(), 4168 DS.getFriendSpecLoc()); 4169 else 4170 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(), 4171 DS.getFriendSpecLoc()); 4172 D->setAccess(AS_public); 4173 CurContext->addDecl(D); 4174 4175 return DeclPtrTy::make(D); 4176} 4177 4178Sema::DeclPtrTy 4179Sema::ActOnFriendFunctionDecl(Scope *S, 4180 Declarator &D, 4181 bool IsDefinition, 4182 MultiTemplateParamsArg TemplateParams) { 4183 // FIXME: do something with template parameters 4184 4185 const DeclSpec &DS = D.getDeclSpec(); 4186 4187 assert(DS.isFriendSpecified()); 4188 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4189 4190 SourceLocation Loc = D.getIdentifierLoc(); 4191 DeclaratorInfo *DInfo = 0; 4192 QualType T = GetTypeForDeclarator(D, S, &DInfo); 4193 4194 // C++ [class.friend]p1 4195 // A friend of a class is a function or class.... 4196 // Note that this sees through typedefs, which is intended. 4197 // It *doesn't* see through dependent types, which is correct 4198 // according to [temp.arg.type]p3: 4199 // If a declaration acquires a function type through a 4200 // type dependent on a template-parameter and this causes 4201 // a declaration that does not use the syntactic form of a 4202 // function declarator to have a function type, the program 4203 // is ill-formed. 4204 if (!T->isFunctionType()) { 4205 Diag(Loc, diag::err_unexpected_friend); 4206 4207 // It might be worthwhile to try to recover by creating an 4208 // appropriate declaration. 4209 return DeclPtrTy(); 4210 } 4211 4212 // C++ [namespace.memdef]p3 4213 // - If a friend declaration in a non-local class first declares a 4214 // class or function, the friend class or function is a member 4215 // of the innermost enclosing namespace. 4216 // - The name of the friend is not found by simple name lookup 4217 // until a matching declaration is provided in that namespace 4218 // scope (either before or after the class declaration granting 4219 // friendship). 4220 // - If a friend function is called, its name may be found by the 4221 // name lookup that considers functions from namespaces and 4222 // classes associated with the types of the function arguments. 4223 // - When looking for a prior declaration of a class or a function 4224 // declared as a friend, scopes outside the innermost enclosing 4225 // namespace scope are not considered. 4226 4227 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 4228 DeclarationName Name = GetNameForDeclarator(D); 4229 assert(Name); 4230 4231 // The existing declaration we found. 4232 FunctionDecl *FD = NULL; 4233 4234 // The context we found the declaration in, or in which we should 4235 // create the declaration. 4236 DeclContext *DC; 4237 4238 // FIXME: handle local classes 4239 4240 // Recover from invalid scope qualifiers as if they just weren't there. 4241 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 4242 DC = computeDeclContext(ScopeQual); 4243 4244 // FIXME: handle dependent contexts 4245 if (!DC) return DeclPtrTy(); 4246 4247 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 4248 4249 // If searching in that context implicitly found a declaration in 4250 // a different context, treat it like it wasn't found at all. 4251 // TODO: better diagnostics for this case. Suggesting the right 4252 // qualified scope would be nice... 4253 if (!Dec || Dec->getDeclContext() != DC) { 4254 D.setInvalidType(); 4255 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 4256 return DeclPtrTy(); 4257 } 4258 4259 // C++ [class.friend]p1: A friend of a class is a function or 4260 // class that is not a member of the class . . . 4261 if (DC == CurContext) 4262 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4263 4264 FD = cast<FunctionDecl>(Dec); 4265 4266 // Otherwise walk out to the nearest namespace scope looking for matches. 4267 } else { 4268 // TODO: handle local class contexts. 4269 4270 DC = CurContext; 4271 while (true) { 4272 // Skip class contexts. If someone can cite chapter and verse 4273 // for this behavior, that would be nice --- it's what GCC and 4274 // EDG do, and it seems like a reasonable intent, but the spec 4275 // really only says that checks for unqualified existing 4276 // declarations should stop at the nearest enclosing namespace, 4277 // not that they should only consider the nearest enclosing 4278 // namespace. 4279 while (DC->isRecord()) DC = DC->getParent(); 4280 4281 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 4282 4283 // TODO: decide what we think about using declarations. 4284 if (Dec) { 4285 FD = cast<FunctionDecl>(Dec); 4286 break; 4287 } 4288 if (DC->isFileContext()) break; 4289 DC = DC->getParent(); 4290 } 4291 4292 // C++ [class.friend]p1: A friend of a class is a function or 4293 // class that is not a member of the class . . . 4294 // C++0x changes this for both friend types and functions. 4295 // Most C++ 98 compilers do seem to give an error here, so 4296 // we do, too. 4297 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x) 4298 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4299 } 4300 4301 bool Redeclaration = (FD != 0); 4302 4303 // If we found a match, create a friend function declaration with 4304 // that function as the previous declaration. 4305 if (Redeclaration) { 4306 // Create it in the semantic context of the original declaration. 4307 DC = FD->getDeclContext(); 4308 4309 // If we didn't find something matching the type exactly, create 4310 // a declaration. This declaration should only be findable via 4311 // argument-dependent lookup. 4312 } else { 4313 assert(DC->isFileContext()); 4314 4315 // This implies that it has to be an operator or function. 4316 if (D.getKind() == Declarator::DK_Constructor || 4317 D.getKind() == Declarator::DK_Destructor || 4318 D.getKind() == Declarator::DK_Conversion) { 4319 Diag(Loc, diag::err_introducing_special_friend) << 4320 (D.getKind() == Declarator::DK_Constructor ? 0 : 4321 D.getKind() == Declarator::DK_Destructor ? 1 : 2); 4322 return DeclPtrTy(); 4323 } 4324 } 4325 4326 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, 4327 /* PrevDecl = */ FD, 4328 MultiTemplateParamsArg(*this), 4329 IsDefinition, 4330 Redeclaration); 4331 if (!ND) return DeclPtrTy(); 4332 4333 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD && 4334 "lost reference to previous declaration"); 4335 4336 FD = cast<FunctionDecl>(ND); 4337 4338 assert(FD->getDeclContext() == DC); 4339 assert(FD->getLexicalDeclContext() == CurContext); 4340 4341 // Add the function declaration to the appropriate lookup tables, 4342 // adjusting the redeclarations list as necessary. We don't 4343 // want to do this yet if the friending class is dependent. 4344 // 4345 // Also update the scope-based lookup if the target context's 4346 // lookup context is in lexical scope. 4347 if (!CurContext->isDependentContext()) { 4348 DC = DC->getLookupContext(); 4349 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false); 4350 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4351 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false); 4352 } 4353 4354 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 4355 D.getIdentifierLoc(), FD, 4356 DS.getFriendSpecLoc()); 4357 FrD->setAccess(AS_public); 4358 CurContext->addDecl(FrD); 4359 4360 return DeclPtrTy::make(FD); 4361} 4362 4363void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 4364 AdjustDeclIfTemplate(dcl); 4365 4366 Decl *Dcl = dcl.getAs<Decl>(); 4367 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 4368 if (!Fn) { 4369 Diag(DelLoc, diag::err_deleted_non_function); 4370 return; 4371 } 4372 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 4373 Diag(DelLoc, diag::err_deleted_decl_not_first); 4374 Diag(Prev->getLocation(), diag::note_previous_declaration); 4375 // If the declaration wasn't the first, we delete the function anyway for 4376 // recovery. 4377 } 4378 Fn->setDeleted(); 4379} 4380 4381static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 4382 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 4383 ++CI) { 4384 Stmt *SubStmt = *CI; 4385 if (!SubStmt) 4386 continue; 4387 if (isa<ReturnStmt>(SubStmt)) 4388 Self.Diag(SubStmt->getSourceRange().getBegin(), 4389 diag::err_return_in_constructor_handler); 4390 if (!isa<Expr>(SubStmt)) 4391 SearchForReturnInStmt(Self, SubStmt); 4392 } 4393} 4394 4395void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 4396 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 4397 CXXCatchStmt *Handler = TryBlock->getHandler(I); 4398 SearchForReturnInStmt(*this, Handler); 4399 } 4400} 4401 4402bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4403 const CXXMethodDecl *Old) { 4404 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 4405 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 4406 4407 QualType CNewTy = Context.getCanonicalType(NewTy); 4408 QualType COldTy = Context.getCanonicalType(OldTy); 4409 4410 if (CNewTy == COldTy && 4411 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers()) 4412 return false; 4413 4414 // Check if the return types are covariant 4415 QualType NewClassTy, OldClassTy; 4416 4417 /// Both types must be pointers or references to classes. 4418 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 4419 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 4420 NewClassTy = NewPT->getPointeeType(); 4421 OldClassTy = OldPT->getPointeeType(); 4422 } 4423 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 4424 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 4425 NewClassTy = NewRT->getPointeeType(); 4426 OldClassTy = OldRT->getPointeeType(); 4427 } 4428 } 4429 4430 // The return types aren't either both pointers or references to a class type. 4431 if (NewClassTy.isNull()) { 4432 Diag(New->getLocation(), 4433 diag::err_different_return_type_for_overriding_virtual_function) 4434 << New->getDeclName() << NewTy << OldTy; 4435 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4436 4437 return true; 4438 } 4439 4440 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) { 4441 // Check if the new class derives from the old class. 4442 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 4443 Diag(New->getLocation(), 4444 diag::err_covariant_return_not_derived) 4445 << New->getDeclName() << NewTy << OldTy; 4446 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4447 return true; 4448 } 4449 4450 // Check if we the conversion from derived to base is valid. 4451 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 4452 diag::err_covariant_return_inaccessible_base, 4453 diag::err_covariant_return_ambiguous_derived_to_base_conv, 4454 // FIXME: Should this point to the return type? 4455 New->getLocation(), SourceRange(), New->getDeclName())) { 4456 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4457 return true; 4458 } 4459 } 4460 4461 // The qualifiers of the return types must be the same. 4462 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) { 4463 Diag(New->getLocation(), 4464 diag::err_covariant_return_type_different_qualifications) 4465 << New->getDeclName() << NewTy << OldTy; 4466 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4467 return true; 4468 }; 4469 4470 4471 // The new class type must have the same or less qualifiers as the old type. 4472 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 4473 Diag(New->getLocation(), 4474 diag::err_covariant_return_type_class_type_more_qualified) 4475 << New->getDeclName() << NewTy << OldTy; 4476 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4477 return true; 4478 }; 4479 4480 return false; 4481} 4482 4483bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4484 const CXXMethodDecl *Old) { 4485 return CheckExceptionSpecSubset(diag::err_override_exception_spec, 4486 diag::note_overridden_virtual_function, 4487 Old->getType()->getAs<FunctionProtoType>(), 4488 Old->getLocation(), 4489 New->getType()->getAs<FunctionProtoType>(), 4490 New->getLocation()); 4491} 4492 4493/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4494/// initializer for the declaration 'Dcl'. 4495/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4496/// static data member of class X, names should be looked up in the scope of 4497/// class X. 4498void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4499 AdjustDeclIfTemplate(Dcl); 4500 4501 Decl *D = Dcl.getAs<Decl>(); 4502 // If there is no declaration, there was an error parsing it. 4503 if (D == 0) 4504 return; 4505 4506 // Check whether it is a declaration with a nested name specifier like 4507 // int foo::bar; 4508 if (!D->isOutOfLine()) 4509 return; 4510 4511 // C++ [basic.lookup.unqual]p13 4512 // 4513 // A name used in the definition of a static data member of class X 4514 // (after the qualified-id of the static member) is looked up as if the name 4515 // was used in a member function of X. 4516 4517 // Change current context into the context of the initializing declaration. 4518 EnterDeclaratorContext(S, D->getDeclContext()); 4519} 4520 4521/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4522/// initializer for the declaration 'Dcl'. 4523void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4524 AdjustDeclIfTemplate(Dcl); 4525 4526 Decl *D = Dcl.getAs<Decl>(); 4527 // If there is no declaration, there was an error parsing it. 4528 if (D == 0) 4529 return; 4530 4531 // Check whether it is a declaration with a nested name specifier like 4532 // int foo::bar; 4533 if (!D->isOutOfLine()) 4534 return; 4535 4536 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 4537 ExitDeclaratorContext(S); 4538} 4539