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