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