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