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