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