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