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