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