SemaDeclCXX.cpp revision 6f52675ec400a0ee89ec6214c4845b8ee274304a
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CharUnits.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclVisitor.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Sema/DeclSpec.h" 29#include "clang/Sema/ParsedTemplate.h" 30#include "clang/Basic/PartialDiagnostic.h" 31#include "clang/Lex/Preprocessor.h" 32#include "llvm/ADT/DenseSet.h" 33#include "llvm/ADT/STLExtras.h" 34#include <map> 35#include <set> 36 37using namespace clang; 38 39//===----------------------------------------------------------------------===// 40// CheckDefaultArgumentVisitor 41//===----------------------------------------------------------------------===// 42 43namespace { 44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 45 /// the default argument of a parameter to determine whether it 46 /// contains any ill-formed subexpressions. For example, this will 47 /// diagnose the use of local variables or parameters within the 48 /// default argument expression. 49 class CheckDefaultArgumentVisitor 50 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 51 Expr *DefaultArg; 52 Sema *S; 53 54 public: 55 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 56 : DefaultArg(defarg), S(s) {} 57 58 bool VisitExpr(Expr *Node); 59 bool VisitDeclRefExpr(DeclRefExpr *DRE); 60 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 61 }; 62 63 /// VisitExpr - Visit all of the children of this expression. 64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 65 bool IsInvalid = false; 66 for (Stmt::child_iterator I = Node->child_begin(), 67 E = Node->child_end(); I != E; ++I) 68 IsInvalid |= Visit(*I); 69 return IsInvalid; 70 } 71 72 /// VisitDeclRefExpr - Visit a reference to a declaration, to 73 /// determine whether this declaration can be used in the default 74 /// argument expression. 75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 76 NamedDecl *Decl = DRE->getDecl(); 77 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 78 // C++ [dcl.fct.default]p9 79 // Default arguments are evaluated each time the function is 80 // called. The order of evaluation of function arguments is 81 // unspecified. Consequently, parameters of a function shall not 82 // be used in default argument expressions, even if they are not 83 // evaluated. Parameters of a function declared before a default 84 // argument expression are in scope and can hide namespace and 85 // class member names. 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_param) 88 << Param->getDeclName() << DefaultArg->getSourceRange(); 89 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p7 91 // Local variables shall not be used in default argument 92 // expressions. 93 if (VDecl->isLocalVarDecl()) 94 return S->Diag(DRE->getSourceRange().getBegin(), 95 diag::err_param_default_argument_references_local) 96 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 97 } 98 99 return false; 100 } 101 102 /// VisitCXXThisExpr - Visit a C++ "this" expression. 103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 104 // C++ [dcl.fct.default]p8: 105 // The keyword this shall not be used in a default argument of a 106 // member function. 107 return S->Diag(ThisE->getSourceRange().getBegin(), 108 diag::err_param_default_argument_references_this) 109 << ThisE->getSourceRange(); 110 } 111} 112 113bool 114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 115 SourceLocation EqualLoc) { 116 if (RequireCompleteType(Param->getLocation(), Param->getType(), 117 diag::err_typecheck_decl_incomplete_type)) { 118 Param->setInvalidDecl(); 119 return true; 120 } 121 122 // C++ [dcl.fct.default]p5 123 // A default argument expression is implicitly converted (clause 124 // 4) to the parameter type. The default argument expression has 125 // the same semantic constraints as the initializer expression in 126 // a declaration of a variable of the parameter type, using the 127 // copy-initialization semantics (8.5). 128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 129 Param); 130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 131 EqualLoc); 132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 134 MultiExprArg(*this, &Arg, 1)); 135 if (Result.isInvalid()) 136 return true; 137 Arg = Result.takeAs<Expr>(); 138 139 CheckImplicitConversions(Arg, EqualLoc); 140 Arg = MaybeCreateExprWithCleanups(Arg); 141 142 // Okay: add the default argument to the parameter 143 Param->setDefaultArg(Arg); 144 145 // We have already instantiated this parameter; provide each of the 146 // instantiations with the uninstantiated default argument. 147 UnparsedDefaultArgInstantiationsMap::iterator InstPos 148 = UnparsedDefaultArgInstantiations.find(Param); 149 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 152 153 // We're done tracking this parameter's instantiations. 154 UnparsedDefaultArgInstantiations.erase(InstPos); 155 } 156 157 return false; 158} 159 160/// ActOnParamDefaultArgument - Check whether the default argument 161/// provided for a function parameter is well-formed. If so, attach it 162/// to the parameter declaration. 163void 164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 165 Expr *DefaultArg) { 166 if (!param || !DefaultArg) 167 return; 168 169 ParmVarDecl *Param = cast<ParmVarDecl>(param); 170 UnparsedDefaultArgLocs.erase(Param); 171 172 // Default arguments are only permitted in C++ 173 if (!getLangOptions().CPlusPlus) { 174 Diag(EqualLoc, diag::err_param_default_argument) 175 << DefaultArg->getSourceRange(); 176 Param->setInvalidDecl(); 177 return; 178 } 179 180 // Check for unexpanded parameter packs. 181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 182 Param->setInvalidDecl(); 183 return; 184 } 185 186 // Check that the default argument is well-formed 187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 188 if (DefaultArgChecker.Visit(DefaultArg)) { 189 Param->setInvalidDecl(); 190 return; 191 } 192 193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 194} 195 196/// ActOnParamUnparsedDefaultArgument - We've seen a default 197/// argument for a function parameter, but we can't parse it yet 198/// because we're inside a class definition. Note that this default 199/// argument will be parsed later. 200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 201 SourceLocation EqualLoc, 202 SourceLocation ArgLoc) { 203 if (!param) 204 return; 205 206 ParmVarDecl *Param = cast<ParmVarDecl>(param); 207 if (Param) 208 Param->setUnparsedDefaultArg(); 209 210 UnparsedDefaultArgLocs[Param] = ArgLoc; 211} 212 213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 214/// the default argument for the parameter param failed. 215void Sema::ActOnParamDefaultArgumentError(Decl *param) { 216 if (!param) 217 return; 218 219 ParmVarDecl *Param = cast<ParmVarDecl>(param); 220 221 Param->setInvalidDecl(); 222 223 UnparsedDefaultArgLocs.erase(Param); 224} 225 226/// CheckExtraCXXDefaultArguments - Check for any extra default 227/// arguments in the declarator, which is not a function declaration 228/// or definition and therefore is not permitted to have default 229/// arguments. This routine should be invoked for every declarator 230/// that is not a function declaration or definition. 231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 232 // C++ [dcl.fct.default]p3 233 // A default argument expression shall be specified only in the 234 // parameter-declaration-clause of a function declaration or in a 235 // template-parameter (14.1). It shall not be specified for a 236 // parameter pack. If it is specified in a 237 // parameter-declaration-clause, it shall not occur within a 238 // declarator or abstract-declarator of a parameter-declaration. 239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 240 DeclaratorChunk &chunk = D.getTypeObject(i); 241 if (chunk.Kind == DeclaratorChunk::Function) { 242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 243 ParmVarDecl *Param = 244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 245 if (Param->hasUnparsedDefaultArg()) { 246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 249 delete Toks; 250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 251 } else if (Param->getDefaultArg()) { 252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 253 << Param->getDefaultArg()->getSourceRange(); 254 Param->setDefaultArg(0); 255 } 256 } 257 } 258 } 259} 260 261// MergeCXXFunctionDecl - Merge two declarations of the same C++ 262// function, once we already know that they have the same 263// type. Subroutine of MergeFunctionDecl. Returns true if there was an 264// error, false otherwise. 265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 266 bool Invalid = false; 267 268 // C++ [dcl.fct.default]p4: 269 // For non-template functions, default arguments can be added in 270 // later declarations of a function in the same 271 // scope. Declarations in different scopes have completely 272 // distinct sets of default arguments. That is, declarations in 273 // inner scopes do not acquire default arguments from 274 // declarations in outer scopes, and vice versa. In a given 275 // function declaration, all parameters subsequent to a 276 // parameter with a default argument shall have default 277 // arguments supplied in this or previous declarations. A 278 // default argument shall not be redefined by a later 279 // declaration (not even to the same value). 280 // 281 // C++ [dcl.fct.default]p6: 282 // Except for member functions of class templates, the default arguments 283 // in a member function definition that appears outside of the class 284 // definition are added to the set of default arguments provided by the 285 // member function declaration in the class definition. 286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 287 ParmVarDecl *OldParam = Old->getParamDecl(p); 288 ParmVarDecl *NewParam = New->getParamDecl(p); 289 290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 292 // hint here. Alternatively, we could walk the type-source information 293 // for NewParam to find the last source location in the type... but it 294 // isn't worth the effort right now. This is the kind of test case that 295 // is hard to get right: 296 297 // int f(int); 298 // void g(int (*fp)(int) = f); 299 // void g(int (*fp)(int) = &f); 300 Diag(NewParam->getLocation(), 301 diag::err_param_default_argument_redefinition) 302 << NewParam->getDefaultArgRange(); 303 304 // Look for the function declaration where the default argument was 305 // actually written, which may be a declaration prior to Old. 306 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 307 Older; Older = Older->getPreviousDeclaration()) { 308 if (!Older->getParamDecl(p)->hasDefaultArg()) 309 break; 310 311 OldParam = Older->getParamDecl(p); 312 } 313 314 Diag(OldParam->getLocation(), diag::note_previous_definition) 315 << OldParam->getDefaultArgRange(); 316 Invalid = true; 317 } else if (OldParam->hasDefaultArg()) { 318 // Merge the old default argument into the new parameter. 319 // It's important to use getInit() here; getDefaultArg() 320 // strips off any top-level ExprWithCleanups. 321 NewParam->setHasInheritedDefaultArg(); 322 if (OldParam->hasUninstantiatedDefaultArg()) 323 NewParam->setUninstantiatedDefaultArg( 324 OldParam->getUninstantiatedDefaultArg()); 325 else 326 NewParam->setDefaultArg(OldParam->getInit()); 327 } else if (NewParam->hasDefaultArg()) { 328 if (New->getDescribedFunctionTemplate()) { 329 // Paragraph 4, quoted above, only applies to non-template functions. 330 Diag(NewParam->getLocation(), 331 diag::err_param_default_argument_template_redecl) 332 << NewParam->getDefaultArgRange(); 333 Diag(Old->getLocation(), diag::note_template_prev_declaration) 334 << false; 335 } else if (New->getTemplateSpecializationKind() 336 != TSK_ImplicitInstantiation && 337 New->getTemplateSpecializationKind() != TSK_Undeclared) { 338 // C++ [temp.expr.spec]p21: 339 // Default function arguments shall not be specified in a declaration 340 // or a definition for one of the following explicit specializations: 341 // - the explicit specialization of a function template; 342 // - the explicit specialization of a member function template; 343 // - the explicit specialization of a member function of a class 344 // template where the class template specialization to which the 345 // member function specialization belongs is implicitly 346 // instantiated. 347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 349 << New->getDeclName() 350 << NewParam->getDefaultArgRange(); 351 } else if (New->getDeclContext()->isDependentContext()) { 352 // C++ [dcl.fct.default]p6 (DR217): 353 // Default arguments for a member function of a class template shall 354 // be specified on the initial declaration of the member function 355 // within the class template. 356 // 357 // Reading the tea leaves a bit in DR217 and its reference to DR205 358 // leads me to the conclusion that one cannot add default function 359 // arguments for an out-of-line definition of a member function of a 360 // dependent type. 361 int WhichKind = 2; 362 if (CXXRecordDecl *Record 363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 364 if (Record->getDescribedClassTemplate()) 365 WhichKind = 0; 366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 367 WhichKind = 1; 368 else 369 WhichKind = 2; 370 } 371 372 Diag(NewParam->getLocation(), 373 diag::err_param_default_argument_member_template_redecl) 374 << WhichKind 375 << NewParam->getDefaultArgRange(); 376 } 377 } 378 } 379 380 if (CheckEquivalentExceptionSpec(Old, New)) 381 Invalid = true; 382 383 return Invalid; 384} 385 386/// CheckCXXDefaultArguments - Verify that the default arguments for a 387/// function declaration are well-formed according to C++ 388/// [dcl.fct.default]. 389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 390 unsigned NumParams = FD->getNumParams(); 391 unsigned p; 392 393 // Find first parameter with a default argument 394 for (p = 0; p < NumParams; ++p) { 395 ParmVarDecl *Param = FD->getParamDecl(p); 396 if (Param->hasDefaultArg()) 397 break; 398 } 399 400 // C++ [dcl.fct.default]p4: 401 // In a given function declaration, all parameters 402 // subsequent to a parameter with a default argument shall 403 // have default arguments supplied in this or previous 404 // declarations. A default argument shall not be redefined 405 // by a later declaration (not even to the same value). 406 unsigned LastMissingDefaultArg = 0; 407 for (; p < NumParams; ++p) { 408 ParmVarDecl *Param = FD->getParamDecl(p); 409 if (!Param->hasDefaultArg()) { 410 if (Param->isInvalidDecl()) 411 /* We already complained about this parameter. */; 412 else if (Param->getIdentifier()) 413 Diag(Param->getLocation(), 414 diag::err_param_default_argument_missing_name) 415 << Param->getIdentifier(); 416 else 417 Diag(Param->getLocation(), 418 diag::err_param_default_argument_missing); 419 420 LastMissingDefaultArg = p; 421 } 422 } 423 424 if (LastMissingDefaultArg > 0) { 425 // Some default arguments were missing. Clear out all of the 426 // default arguments up to (and including) the last missing 427 // default argument, so that we leave the function parameters 428 // in a semantically valid state. 429 for (p = 0; p <= LastMissingDefaultArg; ++p) { 430 ParmVarDecl *Param = FD->getParamDecl(p); 431 if (Param->hasDefaultArg()) { 432 Param->setDefaultArg(0); 433 } 434 } 435 } 436} 437 438/// isCurrentClassName - Determine whether the identifier II is the 439/// name of the class type currently being defined. In the case of 440/// nested classes, this will only return true if II is the name of 441/// the innermost class. 442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 443 const CXXScopeSpec *SS) { 444 assert(getLangOptions().CPlusPlus && "No class names in C!"); 445 446 CXXRecordDecl *CurDecl; 447 if (SS && SS->isSet() && !SS->isInvalid()) { 448 DeclContext *DC = computeDeclContext(*SS, true); 449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 450 } else 451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 452 453 if (CurDecl && CurDecl->getIdentifier()) 454 return &II == CurDecl->getIdentifier(); 455 else 456 return false; 457} 458 459/// \brief Check the validity of a C++ base class specifier. 460/// 461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 462/// and returns NULL otherwise. 463CXXBaseSpecifier * 464Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 465 SourceRange SpecifierRange, 466 bool Virtual, AccessSpecifier Access, 467 TypeSourceInfo *TInfo) { 468 QualType BaseType = TInfo->getType(); 469 470 // C++ [class.union]p1: 471 // A union shall not have base classes. 472 if (Class->isUnion()) { 473 Diag(Class->getLocation(), diag::err_base_clause_on_union) 474 << SpecifierRange; 475 return 0; 476 } 477 478 if (BaseType->isDependentType()) 479 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 480 Class->getTagKind() == TTK_Class, 481 Access, TInfo); 482 483 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 484 485 // Base specifiers must be record types. 486 if (!BaseType->isRecordType()) { 487 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 488 return 0; 489 } 490 491 // C++ [class.union]p1: 492 // A union shall not be used as a base class. 493 if (BaseType->isUnionType()) { 494 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 495 return 0; 496 } 497 498 // C++ [class.derived]p2: 499 // The class-name in a base-specifier shall not be an incompletely 500 // defined class. 501 if (RequireCompleteType(BaseLoc, BaseType, 502 PDiag(diag::err_incomplete_base_class) 503 << SpecifierRange)) { 504 Class->setInvalidDecl(); 505 return 0; 506 } 507 508 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 509 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 510 assert(BaseDecl && "Record type has no declaration"); 511 BaseDecl = BaseDecl->getDefinition(); 512 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 513 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 514 assert(CXXBaseDecl && "Base type is not a C++ type"); 515 516 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 517 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 518 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 519 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 520 << BaseType; 521 return 0; 522 } 523 524 if (BaseDecl->isInvalidDecl()) 525 Class->setInvalidDecl(); 526 527 // Create the base specifier. 528 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 529 Class->getTagKind() == TTK_Class, 530 Access, TInfo); 531} 532 533/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 534/// one entry in the base class list of a class specifier, for 535/// example: 536/// class foo : public bar, virtual private baz { 537/// 'public bar' and 'virtual private baz' are each base-specifiers. 538BaseResult 539Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 540 bool Virtual, AccessSpecifier Access, 541 ParsedType basetype, SourceLocation BaseLoc) { 542 if (!classdecl) 543 return true; 544 545 AdjustDeclIfTemplate(classdecl); 546 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 547 if (!Class) 548 return true; 549 550 TypeSourceInfo *TInfo = 0; 551 GetTypeFromParser(basetype, &TInfo); 552 553 if (DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 554 UPPC_BaseType)) 555 return true; 556 557 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 558 Virtual, Access, TInfo)) 559 return BaseSpec; 560 561 return true; 562} 563 564/// \brief Performs the actual work of attaching the given base class 565/// specifiers to a C++ class. 566bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 567 unsigned NumBases) { 568 if (NumBases == 0) 569 return false; 570 571 // Used to keep track of which base types we have already seen, so 572 // that we can properly diagnose redundant direct base types. Note 573 // that the key is always the unqualified canonical type of the base 574 // class. 575 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 576 577 // Copy non-redundant base specifiers into permanent storage. 578 unsigned NumGoodBases = 0; 579 bool Invalid = false; 580 for (unsigned idx = 0; idx < NumBases; ++idx) { 581 QualType NewBaseType 582 = Context.getCanonicalType(Bases[idx]->getType()); 583 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 584 if (!Class->hasObjectMember()) { 585 if (const RecordType *FDTTy = 586 NewBaseType.getTypePtr()->getAs<RecordType>()) 587 if (FDTTy->getDecl()->hasObjectMember()) 588 Class->setHasObjectMember(true); 589 } 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(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(Decl *ClassDecl, BaseTy **Bases, 627 unsigned NumBases) { 628 if (!ClassDecl || !Bases || !NumBases) 629 return; 630 631 AdjustDeclIfTemplate(ClassDecl); 632 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 633 (CXXBaseSpecifier**)(Bases), NumBases); 634} 635 636static CXXRecordDecl *GetClassForType(QualType T) { 637 if (const RecordType *RT = T->getAs<RecordType>()) 638 return cast<CXXRecordDecl>(RT->getDecl()); 639 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 640 return ICT->getDecl(); 641 else 642 return 0; 643} 644 645/// \brief Determine whether the type \p Derived is a C++ class that is 646/// derived from the type \p Base. 647bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 648 if (!getLangOptions().CPlusPlus) 649 return false; 650 651 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 652 if (!DerivedRD) 653 return false; 654 655 CXXRecordDecl *BaseRD = GetClassForType(Base); 656 if (!BaseRD) 657 return false; 658 659 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 660 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 661} 662 663/// \brief Determine whether the type \p Derived is a C++ class that is 664/// derived from the type \p Base. 665bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 666 if (!getLangOptions().CPlusPlus) 667 return false; 668 669 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 670 if (!DerivedRD) 671 return false; 672 673 CXXRecordDecl *BaseRD = GetClassForType(Base); 674 if (!BaseRD) 675 return false; 676 677 return DerivedRD->isDerivedFrom(BaseRD, Paths); 678} 679 680void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 681 CXXCastPath &BasePathArray) { 682 assert(BasePathArray.empty() && "Base path array must be empty!"); 683 assert(Paths.isRecordingPaths() && "Must record paths!"); 684 685 const CXXBasePath &Path = Paths.front(); 686 687 // We first go backward and check if we have a virtual base. 688 // FIXME: It would be better if CXXBasePath had the base specifier for 689 // the nearest virtual base. 690 unsigned Start = 0; 691 for (unsigned I = Path.size(); I != 0; --I) { 692 if (Path[I - 1].Base->isVirtual()) { 693 Start = I - 1; 694 break; 695 } 696 } 697 698 // Now add all bases. 699 for (unsigned I = Start, E = Path.size(); I != E; ++I) 700 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 701} 702 703/// \brief Determine whether the given base path includes a virtual 704/// base class. 705bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 706 for (CXXCastPath::const_iterator B = BasePath.begin(), 707 BEnd = BasePath.end(); 708 B != BEnd; ++B) 709 if ((*B)->isVirtual()) 710 return true; 711 712 return false; 713} 714 715/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 716/// conversion (where Derived and Base are class types) is 717/// well-formed, meaning that the conversion is unambiguous (and 718/// that all of the base classes are accessible). Returns true 719/// and emits a diagnostic if the code is ill-formed, returns false 720/// otherwise. Loc is the location where this routine should point to 721/// if there is an error, and Range is the source range to highlight 722/// if there is an error. 723bool 724Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 725 unsigned InaccessibleBaseID, 726 unsigned AmbigiousBaseConvID, 727 SourceLocation Loc, SourceRange Range, 728 DeclarationName Name, 729 CXXCastPath *BasePath) { 730 // First, determine whether the path from Derived to Base is 731 // ambiguous. This is slightly more expensive than checking whether 732 // the Derived to Base conversion exists, because here we need to 733 // explore multiple paths to determine if there is an ambiguity. 734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 735 /*DetectVirtual=*/false); 736 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 737 assert(DerivationOkay && 738 "Can only be used with a derived-to-base conversion"); 739 (void)DerivationOkay; 740 741 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 742 if (InaccessibleBaseID) { 743 // Check that the base class can be accessed. 744 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 745 InaccessibleBaseID)) { 746 case AR_inaccessible: 747 return true; 748 case AR_accessible: 749 case AR_dependent: 750 case AR_delayed: 751 break; 752 } 753 } 754 755 // Build a base path if necessary. 756 if (BasePath) 757 BuildBasePathArray(Paths, *BasePath); 758 return false; 759 } 760 761 // We know that the derived-to-base conversion is ambiguous, and 762 // we're going to produce a diagnostic. Perform the derived-to-base 763 // search just one more time to compute all of the possible paths so 764 // that we can print them out. This is more expensive than any of 765 // the previous derived-to-base checks we've done, but at this point 766 // performance isn't as much of an issue. 767 Paths.clear(); 768 Paths.setRecordingPaths(true); 769 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 770 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 771 (void)StillOkay; 772 773 // Build up a textual representation of the ambiguous paths, e.g., 774 // D -> B -> A, that will be used to illustrate the ambiguous 775 // conversions in the diagnostic. We only print one of the paths 776 // to each base class subobject. 777 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 778 779 Diag(Loc, AmbigiousBaseConvID) 780 << Derived << Base << PathDisplayStr << Range << Name; 781 return true; 782} 783 784bool 785Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 786 SourceLocation Loc, SourceRange Range, 787 CXXCastPath *BasePath, 788 bool IgnoreAccess) { 789 return CheckDerivedToBaseConversion(Derived, Base, 790 IgnoreAccess ? 0 791 : diag::err_upcast_to_inaccessible_base, 792 diag::err_ambiguous_derived_to_base_conv, 793 Loc, Range, DeclarationName(), 794 BasePath); 795} 796 797 798/// @brief Builds a string representing ambiguous paths from a 799/// specific derived class to different subobjects of the same base 800/// class. 801/// 802/// This function builds a string that can be used in error messages 803/// to show the different paths that one can take through the 804/// inheritance hierarchy to go from the derived class to different 805/// subobjects of a base class. The result looks something like this: 806/// @code 807/// struct D -> struct B -> struct A 808/// struct D -> struct C -> struct A 809/// @endcode 810std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 811 std::string PathDisplayStr; 812 std::set<unsigned> DisplayedPaths; 813 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 814 Path != Paths.end(); ++Path) { 815 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 816 // We haven't displayed a path to this particular base 817 // class subobject yet. 818 PathDisplayStr += "\n "; 819 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 820 for (CXXBasePath::const_iterator Element = Path->begin(); 821 Element != Path->end(); ++Element) 822 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 823 } 824 } 825 826 return PathDisplayStr; 827} 828 829//===----------------------------------------------------------------------===// 830// C++ class member Handling 831//===----------------------------------------------------------------------===// 832 833/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 834Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 835 SourceLocation ASLoc, 836 SourceLocation ColonLoc) { 837 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 838 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 839 ASLoc, ColonLoc); 840 CurContext->addHiddenDecl(ASDecl); 841 return ASDecl; 842} 843 844/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 845/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 846/// bitfield width if there is one and 'InitExpr' specifies the initializer if 847/// any. 848Decl * 849Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 850 MultiTemplateParamsArg TemplateParameterLists, 851 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 852 bool Deleted) { 853 const DeclSpec &DS = D.getDeclSpec(); 854 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 855 DeclarationName Name = NameInfo.getName(); 856 SourceLocation Loc = NameInfo.getLoc(); 857 858 // For anonymous bitfields, the location should point to the type. 859 if (Loc.isInvalid()) 860 Loc = D.getSourceRange().getBegin(); 861 862 Expr *BitWidth = static_cast<Expr*>(BW); 863 Expr *Init = static_cast<Expr*>(InitExpr); 864 865 assert(isa<CXXRecordDecl>(CurContext)); 866 assert(!DS.isFriendSpecified()); 867 868 bool isFunc = false; 869 if (D.isFunctionDeclarator()) 870 isFunc = true; 871 else if (D.getNumTypeObjects() == 0 && 872 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 873 QualType TDType = GetTypeFromParser(DS.getRepAsType()); 874 isFunc = TDType->isFunctionType(); 875 } 876 877 // C++ 9.2p6: A member shall not be declared to have automatic storage 878 // duration (auto, register) or with the extern storage-class-specifier. 879 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 880 // data members and cannot be applied to names declared const or static, 881 // and cannot be applied to reference members. 882 switch (DS.getStorageClassSpec()) { 883 case DeclSpec::SCS_unspecified: 884 case DeclSpec::SCS_typedef: 885 case DeclSpec::SCS_static: 886 // FALL THROUGH. 887 break; 888 case DeclSpec::SCS_mutable: 889 if (isFunc) { 890 if (DS.getStorageClassSpecLoc().isValid()) 891 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 892 else 893 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 894 895 // FIXME: It would be nicer if the keyword was ignored only for this 896 // declarator. Otherwise we could get follow-up errors. 897 D.getMutableDeclSpec().ClearStorageClassSpecs(); 898 } 899 break; 900 default: 901 if (DS.getStorageClassSpecLoc().isValid()) 902 Diag(DS.getStorageClassSpecLoc(), 903 diag::err_storageclass_invalid_for_member); 904 else 905 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 906 D.getMutableDeclSpec().ClearStorageClassSpecs(); 907 } 908 909 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 910 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 911 !isFunc); 912 913 Decl *Member; 914 if (isInstField) { 915 CXXScopeSpec &SS = D.getCXXScopeSpec(); 916 917 918 if (SS.isSet() && !SS.isInvalid()) { 919 // The user provided a superfluous scope specifier inside a class 920 // definition: 921 // 922 // class X { 923 // int X::member; 924 // }; 925 DeclContext *DC = 0; 926 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 927 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 928 << Name << FixItHint::CreateRemoval(SS.getRange()); 929 else 930 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 931 << Name << SS.getRange(); 932 933 SS.clear(); 934 } 935 936 // FIXME: Check for template parameters! 937 // FIXME: Check that the name is an identifier! 938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 939 AS); 940 assert(Member && "HandleField never returns null"); 941 } else { 942 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 943 if (!Member) { 944 return 0; 945 } 946 947 // Non-instance-fields can't have a bitfield. 948 if (BitWidth) { 949 if (Member->isInvalidDecl()) { 950 // don't emit another diagnostic. 951 } else if (isa<VarDecl>(Member)) { 952 // C++ 9.6p3: A bit-field shall not be a static member. 953 // "static member 'A' cannot be a bit-field" 954 Diag(Loc, diag::err_static_not_bitfield) 955 << Name << BitWidth->getSourceRange(); 956 } else if (isa<TypedefDecl>(Member)) { 957 // "typedef member 'x' cannot be a bit-field" 958 Diag(Loc, diag::err_typedef_not_bitfield) 959 << Name << BitWidth->getSourceRange(); 960 } else { 961 // A function typedef ("typedef int f(); f a;"). 962 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 963 Diag(Loc, diag::err_not_integral_type_bitfield) 964 << Name << cast<ValueDecl>(Member)->getType() 965 << BitWidth->getSourceRange(); 966 } 967 968 BitWidth = 0; 969 Member->setInvalidDecl(); 970 } 971 972 Member->setAccess(AS); 973 974 // If we have declared a member function template, set the access of the 975 // templated declaration as well. 976 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 977 FunTmpl->getTemplatedDecl()->setAccess(AS); 978 } 979 980 assert((Name || isInstField) && "No identifier for non-field ?"); 981 982 if (Init) 983 AddInitializerToDecl(Member, Init, false); 984 if (Deleted) // FIXME: Source location is not very good. 985 SetDeclDeleted(Member, D.getSourceRange().getBegin()); 986 987 if (isInstField) { 988 FieldCollector->Add(cast<FieldDecl>(Member)); 989 return 0; 990 } 991 return Member; 992} 993 994/// \brief Find the direct and/or virtual base specifiers that 995/// correspond to the given base type, for use in base initialization 996/// within a constructor. 997static bool FindBaseInitializer(Sema &SemaRef, 998 CXXRecordDecl *ClassDecl, 999 QualType BaseType, 1000 const CXXBaseSpecifier *&DirectBaseSpec, 1001 const CXXBaseSpecifier *&VirtualBaseSpec) { 1002 // First, check for a direct base class. 1003 DirectBaseSpec = 0; 1004 for (CXXRecordDecl::base_class_const_iterator Base 1005 = ClassDecl->bases_begin(); 1006 Base != ClassDecl->bases_end(); ++Base) { 1007 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1008 // We found a direct base of this type. That's what we're 1009 // initializing. 1010 DirectBaseSpec = &*Base; 1011 break; 1012 } 1013 } 1014 1015 // Check for a virtual base class. 1016 // FIXME: We might be able to short-circuit this if we know in advance that 1017 // there are no virtual bases. 1018 VirtualBaseSpec = 0; 1019 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1020 // We haven't found a base yet; search the class hierarchy for a 1021 // virtual base class. 1022 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1023 /*DetectVirtual=*/false); 1024 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1025 BaseType, Paths)) { 1026 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1027 Path != Paths.end(); ++Path) { 1028 if (Path->back().Base->isVirtual()) { 1029 VirtualBaseSpec = Path->back().Base; 1030 break; 1031 } 1032 } 1033 } 1034 } 1035 1036 return DirectBaseSpec || VirtualBaseSpec; 1037} 1038 1039/// ActOnMemInitializer - Handle a C++ member initializer. 1040MemInitResult 1041Sema::ActOnMemInitializer(Decl *ConstructorD, 1042 Scope *S, 1043 CXXScopeSpec &SS, 1044 IdentifierInfo *MemberOrBase, 1045 ParsedType TemplateTypeTy, 1046 SourceLocation IdLoc, 1047 SourceLocation LParenLoc, 1048 ExprTy **Args, unsigned NumArgs, 1049 SourceLocation RParenLoc) { 1050 if (!ConstructorD) 1051 return true; 1052 1053 AdjustDeclIfTemplate(ConstructorD); 1054 1055 CXXConstructorDecl *Constructor 1056 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1057 if (!Constructor) { 1058 // The user wrote a constructor initializer on a function that is 1059 // not a C++ constructor. Ignore the error for now, because we may 1060 // have more member initializers coming; we'll diagnose it just 1061 // once in ActOnMemInitializers. 1062 return true; 1063 } 1064 1065 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1066 1067 // C++ [class.base.init]p2: 1068 // Names in a mem-initializer-id are looked up in the scope of the 1069 // constructor's class and, if not found in that scope, are looked 1070 // up in the scope containing the constructor's definition. 1071 // [Note: if the constructor's class contains a member with the 1072 // same name as a direct or virtual base class of the class, a 1073 // mem-initializer-id naming the member or base class and composed 1074 // of a single identifier refers to the class member. A 1075 // mem-initializer-id for the hidden base class may be specified 1076 // using a qualified name. ] 1077 if (!SS.getScopeRep() && !TemplateTypeTy) { 1078 // Look for a member, first. 1079 FieldDecl *Member = 0; 1080 DeclContext::lookup_result Result 1081 = ClassDecl->lookup(MemberOrBase); 1082 if (Result.first != Result.second) { 1083 Member = dyn_cast<FieldDecl>(*Result.first); 1084 1085 if (Member) 1086 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1087 LParenLoc, RParenLoc); 1088 // Handle anonymous union case. 1089 if (IndirectFieldDecl* IndirectField 1090 = dyn_cast<IndirectFieldDecl>(*Result.first)) 1091 return BuildMemberInitializer(IndirectField, (Expr**)Args, 1092 NumArgs, IdLoc, 1093 LParenLoc, RParenLoc); 1094 } 1095 } 1096 // It didn't name a member, so see if it names a class. 1097 QualType BaseType; 1098 TypeSourceInfo *TInfo = 0; 1099 1100 if (TemplateTypeTy) { 1101 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1102 } else { 1103 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1104 LookupParsedName(R, S, &SS); 1105 1106 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1107 if (!TyD) { 1108 if (R.isAmbiguous()) return true; 1109 1110 // We don't want access-control diagnostics here. 1111 R.suppressDiagnostics(); 1112 1113 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1114 bool NotUnknownSpecialization = false; 1115 DeclContext *DC = computeDeclContext(SS, false); 1116 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1117 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1118 1119 if (!NotUnknownSpecialization) { 1120 // When the scope specifier can refer to a member of an unknown 1121 // specialization, we take it as a type name. 1122 BaseType = CheckTypenameType(ETK_None, 1123 (NestedNameSpecifier *)SS.getScopeRep(), 1124 *MemberOrBase, SourceLocation(), 1125 SS.getRange(), IdLoc); 1126 if (BaseType.isNull()) 1127 return true; 1128 1129 R.clear(); 1130 R.setLookupName(MemberOrBase); 1131 } 1132 } 1133 1134 // If no results were found, try to correct typos. 1135 if (R.empty() && BaseType.isNull() && 1136 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1137 R.isSingleResult()) { 1138 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1139 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1140 // We have found a non-static data member with a similar 1141 // name to what was typed; complain and initialize that 1142 // member. 1143 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1144 << MemberOrBase << true << R.getLookupName() 1145 << FixItHint::CreateReplacement(R.getNameLoc(), 1146 R.getLookupName().getAsString()); 1147 Diag(Member->getLocation(), diag::note_previous_decl) 1148 << Member->getDeclName(); 1149 1150 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1151 LParenLoc, RParenLoc); 1152 } 1153 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1154 const CXXBaseSpecifier *DirectBaseSpec; 1155 const CXXBaseSpecifier *VirtualBaseSpec; 1156 if (FindBaseInitializer(*this, ClassDecl, 1157 Context.getTypeDeclType(Type), 1158 DirectBaseSpec, VirtualBaseSpec)) { 1159 // We have found a direct or virtual base class with a 1160 // similar name to what was typed; complain and initialize 1161 // that base class. 1162 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1163 << MemberOrBase << false << R.getLookupName() 1164 << FixItHint::CreateReplacement(R.getNameLoc(), 1165 R.getLookupName().getAsString()); 1166 1167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1168 : VirtualBaseSpec; 1169 Diag(BaseSpec->getSourceRange().getBegin(), 1170 diag::note_base_class_specified_here) 1171 << BaseSpec->getType() 1172 << BaseSpec->getSourceRange(); 1173 1174 TyD = Type; 1175 } 1176 } 1177 } 1178 1179 if (!TyD && BaseType.isNull()) { 1180 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1181 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1182 return true; 1183 } 1184 } 1185 1186 if (BaseType.isNull()) { 1187 BaseType = Context.getTypeDeclType(TyD); 1188 if (SS.isSet()) { 1189 NestedNameSpecifier *Qualifier = 1190 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1191 1192 // FIXME: preserve source range information 1193 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1194 } 1195 } 1196 } 1197 1198 if (!TInfo) 1199 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1200 1201 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1202 LParenLoc, RParenLoc, ClassDecl); 1203} 1204 1205/// Checks an initializer expression for use of uninitialized fields, such as 1206/// containing the field that is being initialized. Returns true if there is an 1207/// uninitialized field was used an updates the SourceLocation parameter; false 1208/// otherwise. 1209static bool InitExprContainsUninitializedFields(const Stmt *S, 1210 const ValueDecl *LhsField, 1211 SourceLocation *L) { 1212 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1213 1214 if (isa<CallExpr>(S)) { 1215 // Do not descend into function calls or constructors, as the use 1216 // of an uninitialized field may be valid. One would have to inspect 1217 // the contents of the function/ctor to determine if it is safe or not. 1218 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1219 // may be safe, depending on what the function/ctor does. 1220 return false; 1221 } 1222 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1223 const NamedDecl *RhsField = ME->getMemberDecl(); 1224 1225 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1226 // The member expression points to a static data member. 1227 assert(VD->isStaticDataMember() && 1228 "Member points to non-static data member!"); 1229 (void)VD; 1230 return false; 1231 } 1232 1233 if (isa<EnumConstantDecl>(RhsField)) { 1234 // The member expression points to an enum. 1235 return false; 1236 } 1237 1238 if (RhsField == LhsField) { 1239 // Initializing a field with itself. Throw a warning. 1240 // But wait; there are exceptions! 1241 // Exception #1: The field may not belong to this record. 1242 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1243 const Expr *base = ME->getBase(); 1244 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1245 // Even though the field matches, it does not belong to this record. 1246 return false; 1247 } 1248 // None of the exceptions triggered; return true to indicate an 1249 // uninitialized field was used. 1250 *L = ME->getMemberLoc(); 1251 return true; 1252 } 1253 } else if (isa<SizeOfAlignOfExpr>(S)) { 1254 // sizeof/alignof doesn't reference contents, do not warn. 1255 return false; 1256 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1257 // address-of doesn't reference contents (the pointer may be dereferenced 1258 // in the same expression but it would be rare; and weird). 1259 if (UOE->getOpcode() == UO_AddrOf) 1260 return false; 1261 } 1262 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end(); 1263 it != e; ++it) { 1264 if (!*it) { 1265 // An expression such as 'member(arg ?: "")' may trigger this. 1266 continue; 1267 } 1268 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1269 return true; 1270 } 1271 return false; 1272} 1273 1274MemInitResult 1275Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args, 1276 unsigned NumArgs, SourceLocation IdLoc, 1277 SourceLocation LParenLoc, 1278 SourceLocation RParenLoc) { 1279 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 1280 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 1281 assert((DirectMember || IndirectMember) && 1282 "Member must be a FieldDecl or IndirectFieldDecl"); 1283 1284 if (Member->isInvalidDecl()) 1285 return true; 1286 1287 // Diagnose value-uses of fields to initialize themselves, e.g. 1288 // foo(foo) 1289 // where foo is not also a parameter to the constructor. 1290 // TODO: implement -Wuninitialized and fold this into that framework. 1291 for (unsigned i = 0; i < NumArgs; ++i) { 1292 SourceLocation L; 1293 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1294 // FIXME: Return true in the case when other fields are used before being 1295 // uninitialized. For example, let this field be the i'th field. When 1296 // initializing the i'th field, throw a warning if any of the >= i'th 1297 // fields are used, as they are not yet initialized. 1298 // Right now we are only handling the case where the i'th field uses 1299 // itself in its initializer. 1300 Diag(L, diag::warn_field_is_uninit); 1301 } 1302 } 1303 1304 bool HasDependentArg = false; 1305 for (unsigned i = 0; i < NumArgs; i++) 1306 HasDependentArg |= Args[i]->isTypeDependent(); 1307 1308 Expr *Init; 1309 if (Member->getType()->isDependentType() || HasDependentArg) { 1310 // Can't check initialization for a member of dependent type or when 1311 // any of the arguments are type-dependent expressions. 1312 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1313 RParenLoc); 1314 1315 // Erase any temporaries within this evaluation context; we're not 1316 // going to track them in the AST, since we'll be rebuilding the 1317 // ASTs during template instantiation. 1318 ExprTemporaries.erase( 1319 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1320 ExprTemporaries.end()); 1321 } else { 1322 // Initialize the member. 1323 InitializedEntity MemberEntity = 1324 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 1325 : InitializedEntity::InitializeMember(IndirectMember, 0); 1326 InitializationKind Kind = 1327 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1328 1329 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1330 1331 ExprResult MemberInit = 1332 InitSeq.Perform(*this, MemberEntity, Kind, 1333 MultiExprArg(*this, Args, NumArgs), 0); 1334 if (MemberInit.isInvalid()) 1335 return true; 1336 1337 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1338 1339 // C++0x [class.base.init]p7: 1340 // The initialization of each base and member constitutes a 1341 // full-expression. 1342 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 1343 if (MemberInit.isInvalid()) 1344 return true; 1345 1346 // If we are in a dependent context, template instantiation will 1347 // perform this type-checking again. Just save the arguments that we 1348 // received in a ParenListExpr. 1349 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1350 // of the information that we have about the member 1351 // initializer. However, deconstructing the ASTs is a dicey process, 1352 // and this approach is far more likely to get the corner cases right. 1353 if (CurContext->isDependentContext()) 1354 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1355 RParenLoc); 1356 else 1357 Init = MemberInit.get(); 1358 } 1359 1360 if (DirectMember) { 1361 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember, 1362 IdLoc, LParenLoc, Init, 1363 RParenLoc); 1364 } else { 1365 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember, 1366 IdLoc, LParenLoc, Init, 1367 RParenLoc); 1368 } 1369} 1370 1371MemInitResult 1372Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1373 Expr **Args, unsigned NumArgs, 1374 SourceLocation LParenLoc, SourceLocation RParenLoc, 1375 CXXRecordDecl *ClassDecl) { 1376 bool HasDependentArg = false; 1377 for (unsigned i = 0; i < NumArgs; i++) 1378 HasDependentArg |= Args[i]->isTypeDependent(); 1379 1380 SourceLocation BaseLoc 1381 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1382 1383 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1384 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1385 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1386 1387 // C++ [class.base.init]p2: 1388 // [...] Unless the mem-initializer-id names a nonstatic data 1389 // member of the constructor's class or a direct or virtual base 1390 // of that class, the mem-initializer is ill-formed. A 1391 // mem-initializer-list can initialize a base class using any 1392 // name that denotes that base class type. 1393 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1394 1395 // Check for direct and virtual base classes. 1396 const CXXBaseSpecifier *DirectBaseSpec = 0; 1397 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1398 if (!Dependent) { 1399 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1400 VirtualBaseSpec); 1401 1402 // C++ [base.class.init]p2: 1403 // Unless the mem-initializer-id names a nonstatic data member of the 1404 // constructor's class or a direct or virtual base of that class, the 1405 // mem-initializer is ill-formed. 1406 if (!DirectBaseSpec && !VirtualBaseSpec) { 1407 // If the class has any dependent bases, then it's possible that 1408 // one of those types will resolve to the same type as 1409 // BaseType. Therefore, just treat this as a dependent base 1410 // class initialization. FIXME: Should we try to check the 1411 // initialization anyway? It seems odd. 1412 if (ClassDecl->hasAnyDependentBases()) 1413 Dependent = true; 1414 else 1415 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1416 << BaseType << Context.getTypeDeclType(ClassDecl) 1417 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1418 } 1419 } 1420 1421 if (Dependent) { 1422 // Can't check initialization for a base of dependent type or when 1423 // any of the arguments are type-dependent expressions. 1424 ExprResult BaseInit 1425 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1426 RParenLoc)); 1427 1428 // Erase any temporaries within this evaluation context; we're not 1429 // going to track them in the AST, since we'll be rebuilding the 1430 // ASTs during template instantiation. 1431 ExprTemporaries.erase( 1432 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1433 ExprTemporaries.end()); 1434 1435 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1436 /*IsVirtual=*/false, 1437 LParenLoc, 1438 BaseInit.takeAs<Expr>(), 1439 RParenLoc); 1440 } 1441 1442 // C++ [base.class.init]p2: 1443 // If a mem-initializer-id is ambiguous because it designates both 1444 // a direct non-virtual base class and an inherited virtual base 1445 // class, the mem-initializer is ill-formed. 1446 if (DirectBaseSpec && VirtualBaseSpec) 1447 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1448 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1449 1450 CXXBaseSpecifier *BaseSpec 1451 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1452 if (!BaseSpec) 1453 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1454 1455 // Initialize the base. 1456 InitializedEntity BaseEntity = 1457 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1458 InitializationKind Kind = 1459 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1460 1461 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1462 1463 ExprResult BaseInit = 1464 InitSeq.Perform(*this, BaseEntity, Kind, 1465 MultiExprArg(*this, Args, NumArgs), 0); 1466 if (BaseInit.isInvalid()) 1467 return true; 1468 1469 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1470 1471 // C++0x [class.base.init]p7: 1472 // The initialization of each base and member constitutes a 1473 // full-expression. 1474 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 1475 if (BaseInit.isInvalid()) 1476 return true; 1477 1478 // If we are in a dependent context, template instantiation will 1479 // perform this type-checking again. Just save the arguments that we 1480 // received in a ParenListExpr. 1481 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1482 // of the information that we have about the base 1483 // initializer. However, deconstructing the ASTs is a dicey process, 1484 // and this approach is far more likely to get the corner cases right. 1485 if (CurContext->isDependentContext()) { 1486 ExprResult Init 1487 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1488 RParenLoc)); 1489 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1490 BaseSpec->isVirtual(), 1491 LParenLoc, 1492 Init.takeAs<Expr>(), 1493 RParenLoc); 1494 } 1495 1496 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1497 BaseSpec->isVirtual(), 1498 LParenLoc, 1499 BaseInit.takeAs<Expr>(), 1500 RParenLoc); 1501} 1502 1503/// ImplicitInitializerKind - How an implicit base or member initializer should 1504/// initialize its base or member. 1505enum ImplicitInitializerKind { 1506 IIK_Default, 1507 IIK_Copy, 1508 IIK_Move 1509}; 1510 1511static bool 1512BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1513 ImplicitInitializerKind ImplicitInitKind, 1514 CXXBaseSpecifier *BaseSpec, 1515 bool IsInheritedVirtualBase, 1516 CXXBaseOrMemberInitializer *&CXXBaseInit) { 1517 InitializedEntity InitEntity 1518 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1519 IsInheritedVirtualBase); 1520 1521 ExprResult BaseInit; 1522 1523 switch (ImplicitInitKind) { 1524 case IIK_Default: { 1525 InitializationKind InitKind 1526 = InitializationKind::CreateDefault(Constructor->getLocation()); 1527 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1528 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1529 MultiExprArg(SemaRef, 0, 0)); 1530 break; 1531 } 1532 1533 case IIK_Copy: { 1534 ParmVarDecl *Param = Constructor->getParamDecl(0); 1535 QualType ParamType = Param->getType().getNonReferenceType(); 1536 1537 Expr *CopyCtorArg = 1538 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1539 Constructor->getLocation(), ParamType, 1540 VK_LValue, 0); 1541 1542 // Cast to the base class to avoid ambiguities. 1543 QualType ArgTy = 1544 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1545 ParamType.getQualifiers()); 1546 1547 CXXCastPath BasePath; 1548 BasePath.push_back(BaseSpec); 1549 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1550 CK_UncheckedDerivedToBase, 1551 VK_LValue, &BasePath); 1552 1553 InitializationKind InitKind 1554 = InitializationKind::CreateDirect(Constructor->getLocation(), 1555 SourceLocation(), SourceLocation()); 1556 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1557 &CopyCtorArg, 1); 1558 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1559 MultiExprArg(&CopyCtorArg, 1)); 1560 break; 1561 } 1562 1563 case IIK_Move: 1564 assert(false && "Unhandled initializer kind!"); 1565 } 1566 1567 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 1568 if (BaseInit.isInvalid()) 1569 return true; 1570 1571 CXXBaseInit = 1572 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1573 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1574 SourceLocation()), 1575 BaseSpec->isVirtual(), 1576 SourceLocation(), 1577 BaseInit.takeAs<Expr>(), 1578 SourceLocation()); 1579 1580 return false; 1581} 1582 1583static bool 1584BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1585 ImplicitInitializerKind ImplicitInitKind, 1586 FieldDecl *Field, 1587 CXXBaseOrMemberInitializer *&CXXMemberInit) { 1588 if (Field->isInvalidDecl()) 1589 return true; 1590 1591 SourceLocation Loc = Constructor->getLocation(); 1592 1593 if (ImplicitInitKind == IIK_Copy) { 1594 ParmVarDecl *Param = Constructor->getParamDecl(0); 1595 QualType ParamType = Param->getType().getNonReferenceType(); 1596 1597 Expr *MemberExprBase = 1598 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1599 Loc, ParamType, VK_LValue, 0); 1600 1601 // Build a reference to this field within the parameter. 1602 CXXScopeSpec SS; 1603 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1604 Sema::LookupMemberName); 1605 MemberLookup.addDecl(Field, AS_public); 1606 MemberLookup.resolveKind(); 1607 ExprResult CopyCtorArg 1608 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 1609 ParamType, Loc, 1610 /*IsArrow=*/false, 1611 SS, 1612 /*FirstQualifierInScope=*/0, 1613 MemberLookup, 1614 /*TemplateArgs=*/0); 1615 if (CopyCtorArg.isInvalid()) 1616 return true; 1617 1618 // When the field we are copying is an array, create index variables for 1619 // each dimension of the array. We use these index variables to subscript 1620 // the source array, and other clients (e.g., CodeGen) will perform the 1621 // necessary iteration with these index variables. 1622 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1623 QualType BaseType = Field->getType(); 1624 QualType SizeType = SemaRef.Context.getSizeType(); 1625 while (const ConstantArrayType *Array 1626 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1627 // Create the iteration variable for this array index. 1628 IdentifierInfo *IterationVarName = 0; 1629 { 1630 llvm::SmallString<8> Str; 1631 llvm::raw_svector_ostream OS(Str); 1632 OS << "__i" << IndexVariables.size(); 1633 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1634 } 1635 VarDecl *IterationVar 1636 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, 1637 IterationVarName, SizeType, 1638 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1639 SC_None, SC_None); 1640 IndexVariables.push_back(IterationVar); 1641 1642 // Create a reference to the iteration variable. 1643 ExprResult IterationVarRef 1644 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 1645 assert(!IterationVarRef.isInvalid() && 1646 "Reference to invented variable cannot fail!"); 1647 1648 // Subscript the array with this iteration variable. 1649 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(), 1650 Loc, 1651 IterationVarRef.take(), 1652 Loc); 1653 if (CopyCtorArg.isInvalid()) 1654 return true; 1655 1656 BaseType = Array->getElementType(); 1657 } 1658 1659 // Construct the entity that we will be initializing. For an array, this 1660 // will be first element in the array, which may require several levels 1661 // of array-subscript entities. 1662 llvm::SmallVector<InitializedEntity, 4> Entities; 1663 Entities.reserve(1 + IndexVariables.size()); 1664 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1667 0, 1668 Entities.back())); 1669 1670 // Direct-initialize to use the copy constructor. 1671 InitializationKind InitKind = 1672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1673 1674 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1676 &CopyCtorArgE, 1); 1677 1678 ExprResult MemberInit 1679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1680 MultiExprArg(&CopyCtorArgE, 1)); 1681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1682 if (MemberInit.isInvalid()) 1683 return true; 1684 1685 CXXMemberInit 1686 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1687 MemberInit.takeAs<Expr>(), Loc, 1688 IndexVariables.data(), 1689 IndexVariables.size()); 1690 return false; 1691 } 1692 1693 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1694 1695 QualType FieldBaseElementType = 1696 SemaRef.Context.getBaseElementType(Field->getType()); 1697 1698 if (FieldBaseElementType->isRecordType()) { 1699 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1700 InitializationKind InitKind = 1701 InitializationKind::CreateDefault(Loc); 1702 1703 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1704 ExprResult MemberInit = 1705 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 1706 1707 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1708 if (MemberInit.isInvalid()) 1709 return true; 1710 1711 CXXMemberInit = 1712 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1713 Field, Loc, Loc, 1714 MemberInit.get(), 1715 Loc); 1716 return false; 1717 } 1718 1719 if (FieldBaseElementType->isReferenceType()) { 1720 SemaRef.Diag(Constructor->getLocation(), 1721 diag::err_uninitialized_member_in_ctor) 1722 << (int)Constructor->isImplicit() 1723 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1724 << 0 << Field->getDeclName(); 1725 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1726 return true; 1727 } 1728 1729 if (FieldBaseElementType.isConstQualified()) { 1730 SemaRef.Diag(Constructor->getLocation(), 1731 diag::err_uninitialized_member_in_ctor) 1732 << (int)Constructor->isImplicit() 1733 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1734 << 1 << Field->getDeclName(); 1735 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1736 return true; 1737 } 1738 1739 // Nothing to initialize. 1740 CXXMemberInit = 0; 1741 return false; 1742} 1743 1744namespace { 1745struct BaseAndFieldInfo { 1746 Sema &S; 1747 CXXConstructorDecl *Ctor; 1748 bool AnyErrorsInInits; 1749 ImplicitInitializerKind IIK; 1750 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1751 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit; 1752 1753 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 1754 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 1755 // FIXME: Handle implicit move constructors. 1756 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 1757 IIK = IIK_Copy; 1758 else 1759 IIK = IIK_Default; 1760 } 1761}; 1762} 1763 1764static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 1765 FieldDecl *Top, FieldDecl *Field) { 1766 1767 // Overwhelmingly common case: we have a direct initializer for this field. 1768 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) { 1769 Info.AllToInit.push_back(Init); 1770 return false; 1771 } 1772 1773 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 1774 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 1775 assert(FieldClassType && "anonymous struct/union without record type"); 1776 CXXRecordDecl *FieldClassDecl 1777 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1778 1779 // Even though union members never have non-trivial default 1780 // constructions in C++03, we still build member initializers for aggregate 1781 // record types which can be union members, and C++0x allows non-trivial 1782 // default constructors for union members, so we ensure that only one 1783 // member is initialized for these. 1784 if (FieldClassDecl->isUnion()) { 1785 // First check for an explicit initializer for one field. 1786 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1787 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1788 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) { 1789 Info.AllToInit.push_back(Init); 1790 1791 // Once we've initialized a field of an anonymous union, the union 1792 // field in the class is also initialized, so exit immediately. 1793 return false; 1794 } else if ((*FA)->isAnonymousStructOrUnion()) { 1795 if (CollectFieldInitializer(Info, Top, *FA)) 1796 return true; 1797 } 1798 } 1799 1800 // Fallthrough and construct a default initializer for the union as 1801 // a whole, which can call its default constructor if such a thing exists 1802 // (C++0x perhaps). FIXME: It's not clear that this is the correct 1803 // behavior going forward with C++0x, when anonymous unions there are 1804 // finalized, we should revisit this. 1805 } else { 1806 // For structs, we simply descend through to initialize all members where 1807 // necessary. 1808 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1809 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1810 if (CollectFieldInitializer(Info, Top, *FA)) 1811 return true; 1812 } 1813 } 1814 } 1815 1816 // Don't try to build an implicit initializer if there were semantic 1817 // errors in any of the initializers (and therefore we might be 1818 // missing some that the user actually wrote). 1819 if (Info.AnyErrorsInInits) 1820 return false; 1821 1822 CXXBaseOrMemberInitializer *Init = 0; 1823 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 1824 return true; 1825 1826 if (Init) 1827 Info.AllToInit.push_back(Init); 1828 1829 return false; 1830} 1831 1832bool 1833Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1834 CXXBaseOrMemberInitializer **Initializers, 1835 unsigned NumInitializers, 1836 bool AnyErrors) { 1837 if (Constructor->getDeclContext()->isDependentContext()) { 1838 // Just store the initializers as written, they will be checked during 1839 // instantiation. 1840 if (NumInitializers > 0) { 1841 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1842 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1843 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1844 memcpy(baseOrMemberInitializers, Initializers, 1845 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1846 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1847 } 1848 1849 return false; 1850 } 1851 1852 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 1853 1854 // We need to build the initializer AST according to order of construction 1855 // and not what user specified in the Initializers list. 1856 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 1857 if (!ClassDecl) 1858 return true; 1859 1860 bool HadError = false; 1861 1862 for (unsigned i = 0; i < NumInitializers; i++) { 1863 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1864 1865 if (Member->isBaseInitializer()) 1866 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1867 else 1868 Info.AllBaseFields[Member->getAnyMember()] = Member; 1869 } 1870 1871 // Keep track of the direct virtual bases. 1872 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 1873 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 1874 E = ClassDecl->bases_end(); I != E; ++I) { 1875 if (I->isVirtual()) 1876 DirectVBases.insert(I); 1877 } 1878 1879 // Push virtual bases before others. 1880 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1881 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1882 1883 if (CXXBaseOrMemberInitializer *Value 1884 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1885 Info.AllToInit.push_back(Value); 1886 } else if (!AnyErrors) { 1887 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 1888 CXXBaseOrMemberInitializer *CXXBaseInit; 1889 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1890 VBase, IsInheritedVirtualBase, 1891 CXXBaseInit)) { 1892 HadError = true; 1893 continue; 1894 } 1895 1896 Info.AllToInit.push_back(CXXBaseInit); 1897 } 1898 } 1899 1900 // Non-virtual bases. 1901 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1902 E = ClassDecl->bases_end(); Base != E; ++Base) { 1903 // Virtuals are in the virtual base list and already constructed. 1904 if (Base->isVirtual()) 1905 continue; 1906 1907 if (CXXBaseOrMemberInitializer *Value 1908 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1909 Info.AllToInit.push_back(Value); 1910 } else if (!AnyErrors) { 1911 CXXBaseOrMemberInitializer *CXXBaseInit; 1912 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1913 Base, /*IsInheritedVirtualBase=*/false, 1914 CXXBaseInit)) { 1915 HadError = true; 1916 continue; 1917 } 1918 1919 Info.AllToInit.push_back(CXXBaseInit); 1920 } 1921 } 1922 1923 // Fields. 1924 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1925 E = ClassDecl->field_end(); Field != E; ++Field) { 1926 if ((*Field)->getType()->isIncompleteArrayType()) { 1927 assert(ClassDecl->hasFlexibleArrayMember() && 1928 "Incomplete array type is not valid"); 1929 continue; 1930 } 1931 if (CollectFieldInitializer(Info, *Field, *Field)) 1932 HadError = true; 1933 } 1934 1935 NumInitializers = Info.AllToInit.size(); 1936 if (NumInitializers > 0) { 1937 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1938 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1939 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1940 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 1941 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1942 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1943 1944 // Constructors implicitly reference the base and member 1945 // destructors. 1946 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 1947 Constructor->getParent()); 1948 } 1949 1950 return HadError; 1951} 1952 1953static void *GetKeyForTopLevelField(FieldDecl *Field) { 1954 // For anonymous unions, use the class declaration as the key. 1955 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1956 if (RT->getDecl()->isAnonymousStructOrUnion()) 1957 return static_cast<void *>(RT->getDecl()); 1958 } 1959 return static_cast<void *>(Field); 1960} 1961 1962static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 1963 return Context.getCanonicalType(BaseType).getTypePtr(); 1964} 1965 1966static void *GetKeyForMember(ASTContext &Context, 1967 CXXBaseOrMemberInitializer *Member) { 1968 if (!Member->isAnyMemberInitializer()) 1969 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 1970 1971 // For fields injected into the class via declaration of an anonymous union, 1972 // use its anonymous union class declaration as the unique key. 1973 FieldDecl *Field = Member->getAnyMember(); 1974 1975 // If the field is a member of an anonymous struct or union, our key 1976 // is the anonymous record decl that's a direct child of the class. 1977 RecordDecl *RD = Field->getParent(); 1978 if (RD->isAnonymousStructOrUnion()) { 1979 while (true) { 1980 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 1981 if (Parent->isAnonymousStructOrUnion()) 1982 RD = Parent; 1983 else 1984 break; 1985 } 1986 1987 return static_cast<void *>(RD); 1988 } 1989 1990 return static_cast<void *>(Field); 1991} 1992 1993static void 1994DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 1995 const CXXConstructorDecl *Constructor, 1996 CXXBaseOrMemberInitializer **Inits, 1997 unsigned NumInits) { 1998 if (Constructor->getDeclContext()->isDependentContext()) 1999 return; 2000 2001 // Don't check initializers order unless the warning is enabled at the 2002 // location of at least one initializer. 2003 bool ShouldCheckOrder = false; 2004 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2005 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 2006 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2007 Init->getSourceLocation()) 2008 != Diagnostic::Ignored) { 2009 ShouldCheckOrder = true; 2010 break; 2011 } 2012 } 2013 if (!ShouldCheckOrder) 2014 return; 2015 2016 // Build the list of bases and members in the order that they'll 2017 // actually be initialized. The explicit initializers should be in 2018 // this same order but may be missing things. 2019 llvm::SmallVector<const void*, 32> IdealInitKeys; 2020 2021 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2022 2023 // 1. Virtual bases. 2024 for (CXXRecordDecl::base_class_const_iterator VBase = 2025 ClassDecl->vbases_begin(), 2026 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2027 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2028 2029 // 2. Non-virtual bases. 2030 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2031 E = ClassDecl->bases_end(); Base != E; ++Base) { 2032 if (Base->isVirtual()) 2033 continue; 2034 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2035 } 2036 2037 // 3. Direct fields. 2038 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2039 E = ClassDecl->field_end(); Field != E; ++Field) 2040 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2041 2042 unsigned NumIdealInits = IdealInitKeys.size(); 2043 unsigned IdealIndex = 0; 2044 2045 CXXBaseOrMemberInitializer *PrevInit = 0; 2046 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2047 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 2048 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2049 2050 // Scan forward to try to find this initializer in the idealized 2051 // initializers list. 2052 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2053 if (InitKey == IdealInitKeys[IdealIndex]) 2054 break; 2055 2056 // If we didn't find this initializer, it must be because we 2057 // scanned past it on a previous iteration. That can only 2058 // happen if we're out of order; emit a warning. 2059 if (IdealIndex == NumIdealInits && PrevInit) { 2060 Sema::SemaDiagnosticBuilder D = 2061 SemaRef.Diag(PrevInit->getSourceLocation(), 2062 diag::warn_initializer_out_of_order); 2063 2064 if (PrevInit->isAnyMemberInitializer()) 2065 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2066 else 2067 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2068 2069 if (Init->isAnyMemberInitializer()) 2070 D << 0 << Init->getAnyMember()->getDeclName(); 2071 else 2072 D << 1 << Init->getBaseClassInfo()->getType(); 2073 2074 // Move back to the initializer's location in the ideal list. 2075 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2076 if (InitKey == IdealInitKeys[IdealIndex]) 2077 break; 2078 2079 assert(IdealIndex != NumIdealInits && 2080 "initializer not found in initializer list"); 2081 } 2082 2083 PrevInit = Init; 2084 } 2085} 2086 2087namespace { 2088bool CheckRedundantInit(Sema &S, 2089 CXXBaseOrMemberInitializer *Init, 2090 CXXBaseOrMemberInitializer *&PrevInit) { 2091 if (!PrevInit) { 2092 PrevInit = Init; 2093 return false; 2094 } 2095 2096 if (FieldDecl *Field = Init->getMember()) 2097 S.Diag(Init->getSourceLocation(), 2098 diag::err_multiple_mem_initialization) 2099 << Field->getDeclName() 2100 << Init->getSourceRange(); 2101 else { 2102 Type *BaseClass = Init->getBaseClass(); 2103 assert(BaseClass && "neither field nor base"); 2104 S.Diag(Init->getSourceLocation(), 2105 diag::err_multiple_base_initialization) 2106 << QualType(BaseClass, 0) 2107 << Init->getSourceRange(); 2108 } 2109 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2110 << 0 << PrevInit->getSourceRange(); 2111 2112 return true; 2113} 2114 2115typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry; 2116typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2117 2118bool CheckRedundantUnionInit(Sema &S, 2119 CXXBaseOrMemberInitializer *Init, 2120 RedundantUnionMap &Unions) { 2121 FieldDecl *Field = Init->getAnyMember(); 2122 RecordDecl *Parent = Field->getParent(); 2123 if (!Parent->isAnonymousStructOrUnion()) 2124 return false; 2125 2126 NamedDecl *Child = Field; 2127 do { 2128 if (Parent->isUnion()) { 2129 UnionEntry &En = Unions[Parent]; 2130 if (En.first && En.first != Child) { 2131 S.Diag(Init->getSourceLocation(), 2132 diag::err_multiple_mem_union_initialization) 2133 << Field->getDeclName() 2134 << Init->getSourceRange(); 2135 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2136 << 0 << En.second->getSourceRange(); 2137 return true; 2138 } else if (!En.first) { 2139 En.first = Child; 2140 En.second = Init; 2141 } 2142 } 2143 2144 Child = Parent; 2145 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2146 } while (Parent->isAnonymousStructOrUnion()); 2147 2148 return false; 2149} 2150} 2151 2152/// ActOnMemInitializers - Handle the member initializers for a constructor. 2153void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2154 SourceLocation ColonLoc, 2155 MemInitTy **meminits, unsigned NumMemInits, 2156 bool AnyErrors) { 2157 if (!ConstructorDecl) 2158 return; 2159 2160 AdjustDeclIfTemplate(ConstructorDecl); 2161 2162 CXXConstructorDecl *Constructor 2163 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2164 2165 if (!Constructor) { 2166 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2167 return; 2168 } 2169 2170 CXXBaseOrMemberInitializer **MemInits = 2171 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 2172 2173 // Mapping for the duplicate initializers check. 2174 // For member initializers, this is keyed with a FieldDecl*. 2175 // For base initializers, this is keyed with a Type*. 2176 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 2177 2178 // Mapping for the inconsistent anonymous-union initializers check. 2179 RedundantUnionMap MemberUnions; 2180 2181 bool HadError = false; 2182 for (unsigned i = 0; i < NumMemInits; i++) { 2183 CXXBaseOrMemberInitializer *Init = MemInits[i]; 2184 2185 // Set the source order index. 2186 Init->setSourceOrder(i); 2187 2188 if (Init->isAnyMemberInitializer()) { 2189 FieldDecl *Field = Init->getAnyMember(); 2190 if (CheckRedundantInit(*this, Init, Members[Field]) || 2191 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2192 HadError = true; 2193 } else { 2194 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2195 if (CheckRedundantInit(*this, Init, Members[Key])) 2196 HadError = true; 2197 } 2198 } 2199 2200 if (HadError) 2201 return; 2202 2203 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2204 2205 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2206} 2207 2208void 2209Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2210 CXXRecordDecl *ClassDecl) { 2211 // Ignore dependent contexts. 2212 if (ClassDecl->isDependentContext()) 2213 return; 2214 2215 // FIXME: all the access-control diagnostics are positioned on the 2216 // field/base declaration. That's probably good; that said, the 2217 // user might reasonably want to know why the destructor is being 2218 // emitted, and we currently don't say. 2219 2220 // Non-static data members. 2221 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2222 E = ClassDecl->field_end(); I != E; ++I) { 2223 FieldDecl *Field = *I; 2224 if (Field->isInvalidDecl()) 2225 continue; 2226 QualType FieldType = Context.getBaseElementType(Field->getType()); 2227 2228 const RecordType* RT = FieldType->getAs<RecordType>(); 2229 if (!RT) 2230 continue; 2231 2232 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2233 if (FieldClassDecl->hasTrivialDestructor()) 2234 continue; 2235 2236 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2237 CheckDestructorAccess(Field->getLocation(), Dtor, 2238 PDiag(diag::err_access_dtor_field) 2239 << Field->getDeclName() 2240 << FieldType); 2241 2242 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2243 } 2244 2245 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2246 2247 // Bases. 2248 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2249 E = ClassDecl->bases_end(); Base != E; ++Base) { 2250 // Bases are always records in a well-formed non-dependent class. 2251 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2252 2253 // Remember direct virtual bases. 2254 if (Base->isVirtual()) 2255 DirectVirtualBases.insert(RT); 2256 2257 // Ignore trivial destructors. 2258 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2259 if (BaseClassDecl->hasTrivialDestructor()) 2260 continue; 2261 2262 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2263 2264 // FIXME: caret should be on the start of the class name 2265 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2266 PDiag(diag::err_access_dtor_base) 2267 << Base->getType() 2268 << Base->getSourceRange()); 2269 2270 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2271 } 2272 2273 // Virtual bases. 2274 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2275 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2276 2277 // Bases are always records in a well-formed non-dependent class. 2278 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2279 2280 // Ignore direct virtual bases. 2281 if (DirectVirtualBases.count(RT)) 2282 continue; 2283 2284 // Ignore trivial destructors. 2285 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2286 if (BaseClassDecl->hasTrivialDestructor()) 2287 continue; 2288 2289 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2290 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2291 PDiag(diag::err_access_dtor_vbase) 2292 << VBase->getType()); 2293 2294 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2295 } 2296} 2297 2298void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2299 if (!CDtorDecl) 2300 return; 2301 2302 if (CXXConstructorDecl *Constructor 2303 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2304 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2305} 2306 2307bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2308 unsigned DiagID, AbstractDiagSelID SelID) { 2309 if (SelID == -1) 2310 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2311 else 2312 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2313} 2314 2315bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2316 const PartialDiagnostic &PD) { 2317 if (!getLangOptions().CPlusPlus) 2318 return false; 2319 2320 if (const ArrayType *AT = Context.getAsArrayType(T)) 2321 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2322 2323 if (const PointerType *PT = T->getAs<PointerType>()) { 2324 // Find the innermost pointer type. 2325 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2326 PT = T; 2327 2328 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2329 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2330 } 2331 2332 const RecordType *RT = T->getAs<RecordType>(); 2333 if (!RT) 2334 return false; 2335 2336 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2337 2338 // We can't answer whether something is abstract until it has a 2339 // definition. If it's currently being defined, we'll walk back 2340 // over all the declarations when we have a full definition. 2341 const CXXRecordDecl *Def = RD->getDefinition(); 2342 if (!Def || Def->isBeingDefined()) 2343 return false; 2344 2345 if (!RD->isAbstract()) 2346 return false; 2347 2348 Diag(Loc, PD) << RD->getDeclName(); 2349 DiagnoseAbstractType(RD); 2350 2351 return true; 2352} 2353 2354void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2355 // Check if we've already emitted the list of pure virtual functions 2356 // for this class. 2357 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2358 return; 2359 2360 CXXFinalOverriderMap FinalOverriders; 2361 RD->getFinalOverriders(FinalOverriders); 2362 2363 // Keep a set of seen pure methods so we won't diagnose the same method 2364 // more than once. 2365 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2366 2367 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2368 MEnd = FinalOverriders.end(); 2369 M != MEnd; 2370 ++M) { 2371 for (OverridingMethods::iterator SO = M->second.begin(), 2372 SOEnd = M->second.end(); 2373 SO != SOEnd; ++SO) { 2374 // C++ [class.abstract]p4: 2375 // A class is abstract if it contains or inherits at least one 2376 // pure virtual function for which the final overrider is pure 2377 // virtual. 2378 2379 // 2380 if (SO->second.size() != 1) 2381 continue; 2382 2383 if (!SO->second.front().Method->isPure()) 2384 continue; 2385 2386 if (!SeenPureMethods.insert(SO->second.front().Method)) 2387 continue; 2388 2389 Diag(SO->second.front().Method->getLocation(), 2390 diag::note_pure_virtual_function) 2391 << SO->second.front().Method->getDeclName(); 2392 } 2393 } 2394 2395 if (!PureVirtualClassDiagSet) 2396 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2397 PureVirtualClassDiagSet->insert(RD); 2398} 2399 2400namespace { 2401struct AbstractUsageInfo { 2402 Sema &S; 2403 CXXRecordDecl *Record; 2404 CanQualType AbstractType; 2405 bool Invalid; 2406 2407 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2408 : S(S), Record(Record), 2409 AbstractType(S.Context.getCanonicalType( 2410 S.Context.getTypeDeclType(Record))), 2411 Invalid(false) {} 2412 2413 void DiagnoseAbstractType() { 2414 if (Invalid) return; 2415 S.DiagnoseAbstractType(Record); 2416 Invalid = true; 2417 } 2418 2419 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2420}; 2421 2422struct CheckAbstractUsage { 2423 AbstractUsageInfo &Info; 2424 const NamedDecl *Ctx; 2425 2426 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2427 : Info(Info), Ctx(Ctx) {} 2428 2429 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2430 switch (TL.getTypeLocClass()) { 2431#define ABSTRACT_TYPELOC(CLASS, PARENT) 2432#define TYPELOC(CLASS, PARENT) \ 2433 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2434#include "clang/AST/TypeLocNodes.def" 2435 } 2436 } 2437 2438 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2439 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2440 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2441 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2442 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2443 } 2444 } 2445 2446 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2447 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2448 } 2449 2450 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2451 // Visit the type parameters from a permissive context. 2452 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2453 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2454 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2455 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2456 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2457 // TODO: other template argument types? 2458 } 2459 } 2460 2461 // Visit pointee types from a permissive context. 2462#define CheckPolymorphic(Type) \ 2463 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2464 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2465 } 2466 CheckPolymorphic(PointerTypeLoc) 2467 CheckPolymorphic(ReferenceTypeLoc) 2468 CheckPolymorphic(MemberPointerTypeLoc) 2469 CheckPolymorphic(BlockPointerTypeLoc) 2470 2471 /// Handle all the types we haven't given a more specific 2472 /// implementation for above. 2473 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2474 // Every other kind of type that we haven't called out already 2475 // that has an inner type is either (1) sugar or (2) contains that 2476 // inner type in some way as a subobject. 2477 if (TypeLoc Next = TL.getNextTypeLoc()) 2478 return Visit(Next, Sel); 2479 2480 // If there's no inner type and we're in a permissive context, 2481 // don't diagnose. 2482 if (Sel == Sema::AbstractNone) return; 2483 2484 // Check whether the type matches the abstract type. 2485 QualType T = TL.getType(); 2486 if (T->isArrayType()) { 2487 Sel = Sema::AbstractArrayType; 2488 T = Info.S.Context.getBaseElementType(T); 2489 } 2490 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2491 if (CT != Info.AbstractType) return; 2492 2493 // It matched; do some magic. 2494 if (Sel == Sema::AbstractArrayType) { 2495 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2496 << T << TL.getSourceRange(); 2497 } else { 2498 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2499 << Sel << T << TL.getSourceRange(); 2500 } 2501 Info.DiagnoseAbstractType(); 2502 } 2503}; 2504 2505void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2506 Sema::AbstractDiagSelID Sel) { 2507 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2508} 2509 2510} 2511 2512/// Check for invalid uses of an abstract type in a method declaration. 2513static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2514 CXXMethodDecl *MD) { 2515 // No need to do the check on definitions, which require that 2516 // the return/param types be complete. 2517 if (MD->isThisDeclarationADefinition()) 2518 return; 2519 2520 // For safety's sake, just ignore it if we don't have type source 2521 // information. This should never happen for non-implicit methods, 2522 // but... 2523 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2524 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2525} 2526 2527/// Check for invalid uses of an abstract type within a class definition. 2528static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2529 CXXRecordDecl *RD) { 2530 for (CXXRecordDecl::decl_iterator 2531 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2532 Decl *D = *I; 2533 if (D->isImplicit()) continue; 2534 2535 // Methods and method templates. 2536 if (isa<CXXMethodDecl>(D)) { 2537 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2538 } else if (isa<FunctionTemplateDecl>(D)) { 2539 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2540 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2541 2542 // Fields and static variables. 2543 } else if (isa<FieldDecl>(D)) { 2544 FieldDecl *FD = cast<FieldDecl>(D); 2545 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2546 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2547 } else if (isa<VarDecl>(D)) { 2548 VarDecl *VD = cast<VarDecl>(D); 2549 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2550 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2551 2552 // Nested classes and class templates. 2553 } else if (isa<CXXRecordDecl>(D)) { 2554 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2555 } else if (isa<ClassTemplateDecl>(D)) { 2556 CheckAbstractClassUsage(Info, 2557 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2558 } 2559 } 2560} 2561 2562/// \brief Perform semantic checks on a class definition that has been 2563/// completing, introducing implicitly-declared members, checking for 2564/// abstract types, etc. 2565void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2566 if (!Record) 2567 return; 2568 2569 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2570 AbstractUsageInfo Info(*this, Record); 2571 CheckAbstractClassUsage(Info, Record); 2572 } 2573 2574 // If this is not an aggregate type and has no user-declared constructor, 2575 // complain about any non-static data members of reference or const scalar 2576 // type, since they will never get initializers. 2577 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2578 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2579 bool Complained = false; 2580 for (RecordDecl::field_iterator F = Record->field_begin(), 2581 FEnd = Record->field_end(); 2582 F != FEnd; ++F) { 2583 if (F->getType()->isReferenceType() || 2584 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2585 if (!Complained) { 2586 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2587 << Record->getTagKind() << Record; 2588 Complained = true; 2589 } 2590 2591 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2592 << F->getType()->isReferenceType() 2593 << F->getDeclName(); 2594 } 2595 } 2596 } 2597 2598 if (Record->isDynamicClass()) 2599 DynamicClasses.push_back(Record); 2600 2601 if (Record->getIdentifier()) { 2602 // C++ [class.mem]p13: 2603 // If T is the name of a class, then each of the following shall have a 2604 // name different from T: 2605 // - every member of every anonymous union that is a member of class T. 2606 // 2607 // C++ [class.mem]p14: 2608 // In addition, if class T has a user-declared constructor (12.1), every 2609 // non-static data member of class T shall have a name different from T. 2610 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2611 R.first != R.second; ++R.first) { 2612 NamedDecl *D = *R.first; 2613 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 2614 isa<IndirectFieldDecl>(D)) { 2615 Diag(D->getLocation(), diag::err_member_name_of_class) 2616 << D->getDeclName(); 2617 break; 2618 } 2619 } 2620 } 2621} 2622 2623void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2624 Decl *TagDecl, 2625 SourceLocation LBrac, 2626 SourceLocation RBrac, 2627 AttributeList *AttrList) { 2628 if (!TagDecl) 2629 return; 2630 2631 AdjustDeclIfTemplate(TagDecl); 2632 2633 ActOnFields(S, RLoc, TagDecl, 2634 // strict aliasing violation! 2635 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 2636 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2637 2638 CheckCompletedCXXClass( 2639 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 2640} 2641 2642namespace { 2643 /// \brief Helper class that collects exception specifications for 2644 /// implicitly-declared special member functions. 2645 class ImplicitExceptionSpecification { 2646 ASTContext &Context; 2647 bool AllowsAllExceptions; 2648 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 2649 llvm::SmallVector<QualType, 4> Exceptions; 2650 2651 public: 2652 explicit ImplicitExceptionSpecification(ASTContext &Context) 2653 : Context(Context), AllowsAllExceptions(false) { } 2654 2655 /// \brief Whether the special member function should have any 2656 /// exception specification at all. 2657 bool hasExceptionSpecification() const { 2658 return !AllowsAllExceptions; 2659 } 2660 2661 /// \brief Whether the special member function should have a 2662 /// throw(...) exception specification (a Microsoft extension). 2663 bool hasAnyExceptionSpecification() const { 2664 return false; 2665 } 2666 2667 /// \brief The number of exceptions in the exception specification. 2668 unsigned size() const { return Exceptions.size(); } 2669 2670 /// \brief The set of exceptions in the exception specification. 2671 const QualType *data() const { return Exceptions.data(); } 2672 2673 /// \brief Note that 2674 void CalledDecl(CXXMethodDecl *Method) { 2675 // If we already know that we allow all exceptions, do nothing. 2676 if (AllowsAllExceptions || !Method) 2677 return; 2678 2679 const FunctionProtoType *Proto 2680 = Method->getType()->getAs<FunctionProtoType>(); 2681 2682 // If this function can throw any exceptions, make a note of that. 2683 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) { 2684 AllowsAllExceptions = true; 2685 ExceptionsSeen.clear(); 2686 Exceptions.clear(); 2687 return; 2688 } 2689 2690 // Record the exceptions in this function's exception specification. 2691 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 2692 EEnd = Proto->exception_end(); 2693 E != EEnd; ++E) 2694 if (ExceptionsSeen.insert(Context.getCanonicalType(*E))) 2695 Exceptions.push_back(*E); 2696 } 2697 }; 2698} 2699 2700 2701/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2702/// special functions, such as the default constructor, copy 2703/// constructor, or destructor, to the given C++ class (C++ 2704/// [special]p1). This routine can only be executed just before the 2705/// definition of the class is complete. 2706void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 2707 if (!ClassDecl->hasUserDeclaredConstructor()) 2708 ++ASTContext::NumImplicitDefaultConstructors; 2709 2710 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 2711 ++ASTContext::NumImplicitCopyConstructors; 2712 2713 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2714 ++ASTContext::NumImplicitCopyAssignmentOperators; 2715 2716 // If we have a dynamic class, then the copy assignment operator may be 2717 // virtual, so we have to declare it immediately. This ensures that, e.g., 2718 // it shows up in the right place in the vtable and that we diagnose 2719 // problems with the implicit exception specification. 2720 if (ClassDecl->isDynamicClass()) 2721 DeclareImplicitCopyAssignment(ClassDecl); 2722 } 2723 2724 if (!ClassDecl->hasUserDeclaredDestructor()) { 2725 ++ASTContext::NumImplicitDestructors; 2726 2727 // If we have a dynamic class, then the destructor may be virtual, so we 2728 // have to declare the destructor immediately. This ensures that, e.g., it 2729 // shows up in the right place in the vtable and that we diagnose problems 2730 // with the implicit exception specification. 2731 if (ClassDecl->isDynamicClass()) 2732 DeclareImplicitDestructor(ClassDecl); 2733 } 2734} 2735 2736void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 2737 if (!D) 2738 return; 2739 2740 TemplateParameterList *Params = 0; 2741 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2742 Params = Template->getTemplateParameters(); 2743 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2744 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2745 Params = PartialSpec->getTemplateParameters(); 2746 else 2747 return; 2748 2749 for (TemplateParameterList::iterator Param = Params->begin(), 2750 ParamEnd = Params->end(); 2751 Param != ParamEnd; ++Param) { 2752 NamedDecl *Named = cast<NamedDecl>(*Param); 2753 if (Named->getDeclName()) { 2754 S->AddDecl(Named); 2755 IdResolver.AddDecl(Named); 2756 } 2757 } 2758} 2759 2760void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 2761 if (!RecordD) return; 2762 AdjustDeclIfTemplate(RecordD); 2763 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 2764 PushDeclContext(S, Record); 2765} 2766 2767void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 2768 if (!RecordD) return; 2769 PopDeclContext(); 2770} 2771 2772/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2773/// parsing a top-level (non-nested) C++ class, and we are now 2774/// parsing those parts of the given Method declaration that could 2775/// not be parsed earlier (C++ [class.mem]p2), such as default 2776/// arguments. This action should enter the scope of the given 2777/// Method declaration as if we had just parsed the qualified method 2778/// name. However, it should not bring the parameters into scope; 2779/// that will be performed by ActOnDelayedCXXMethodParameter. 2780void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 2781} 2782 2783/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2784/// C++ method declaration. We're (re-)introducing the given 2785/// function parameter into scope for use in parsing later parts of 2786/// the method declaration. For example, we could see an 2787/// ActOnParamDefaultArgument event for this parameter. 2788void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 2789 if (!ParamD) 2790 return; 2791 2792 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 2793 2794 // If this parameter has an unparsed default argument, clear it out 2795 // to make way for the parsed default argument. 2796 if (Param->hasUnparsedDefaultArg()) 2797 Param->setDefaultArg(0); 2798 2799 S->AddDecl(Param); 2800 if (Param->getDeclName()) 2801 IdResolver.AddDecl(Param); 2802} 2803 2804/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2805/// processing the delayed method declaration for Method. The method 2806/// declaration is now considered finished. There may be a separate 2807/// ActOnStartOfFunctionDef action later (not necessarily 2808/// immediately!) for this method, if it was also defined inside the 2809/// class body. 2810void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 2811 if (!MethodD) 2812 return; 2813 2814 AdjustDeclIfTemplate(MethodD); 2815 2816 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 2817 2818 // Now that we have our default arguments, check the constructor 2819 // again. It could produce additional diagnostics or affect whether 2820 // the class has implicitly-declared destructors, among other 2821 // things. 2822 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2823 CheckConstructor(Constructor); 2824 2825 // Check the default arguments, which we may have added. 2826 if (!Method->isInvalidDecl()) 2827 CheckCXXDefaultArguments(Method); 2828} 2829 2830/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2831/// the well-formedness of the constructor declarator @p D with type @p 2832/// R. If there are any errors in the declarator, this routine will 2833/// emit diagnostics and set the invalid bit to true. In any case, the type 2834/// will be updated to reflect a well-formed type for the constructor and 2835/// returned. 2836QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2837 StorageClass &SC) { 2838 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2839 2840 // C++ [class.ctor]p3: 2841 // A constructor shall not be virtual (10.3) or static (9.4). A 2842 // constructor can be invoked for a const, volatile or const 2843 // volatile object. A constructor shall not be declared const, 2844 // volatile, or const volatile (9.3.2). 2845 if (isVirtual) { 2846 if (!D.isInvalidType()) 2847 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2848 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2849 << SourceRange(D.getIdentifierLoc()); 2850 D.setInvalidType(); 2851 } 2852 if (SC == SC_Static) { 2853 if (!D.isInvalidType()) 2854 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2855 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2856 << SourceRange(D.getIdentifierLoc()); 2857 D.setInvalidType(); 2858 SC = SC_None; 2859 } 2860 2861 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 2862 if (FTI.TypeQuals != 0) { 2863 if (FTI.TypeQuals & Qualifiers::Const) 2864 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2865 << "const" << SourceRange(D.getIdentifierLoc()); 2866 if (FTI.TypeQuals & Qualifiers::Volatile) 2867 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2868 << "volatile" << SourceRange(D.getIdentifierLoc()); 2869 if (FTI.TypeQuals & Qualifiers::Restrict) 2870 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2871 << "restrict" << SourceRange(D.getIdentifierLoc()); 2872 D.setInvalidType(); 2873 } 2874 2875 // Rebuild the function type "R" without any type qualifiers (in 2876 // case any of the errors above fired) and with "void" as the 2877 // return type, since constructors don't have return types. 2878 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2879 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 2880 return R; 2881 2882 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 2883 EPI.TypeQuals = 0; 2884 2885 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2886 Proto->getNumArgs(), EPI); 2887} 2888 2889/// CheckConstructor - Checks a fully-formed constructor for 2890/// well-formedness, issuing any diagnostics required. Returns true if 2891/// the constructor declarator is invalid. 2892void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2893 CXXRecordDecl *ClassDecl 2894 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2895 if (!ClassDecl) 2896 return Constructor->setInvalidDecl(); 2897 2898 // C++ [class.copy]p3: 2899 // A declaration of a constructor for a class X is ill-formed if 2900 // its first parameter is of type (optionally cv-qualified) X and 2901 // either there are no other parameters or else all other 2902 // parameters have default arguments. 2903 if (!Constructor->isInvalidDecl() && 2904 ((Constructor->getNumParams() == 1) || 2905 (Constructor->getNumParams() > 1 && 2906 Constructor->getParamDecl(1)->hasDefaultArg())) && 2907 Constructor->getTemplateSpecializationKind() 2908 != TSK_ImplicitInstantiation) { 2909 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2910 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2911 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2912 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2913 const char *ConstRef 2914 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 2915 : " const &"; 2916 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2917 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 2918 2919 // FIXME: Rather that making the constructor invalid, we should endeavor 2920 // to fix the type. 2921 Constructor->setInvalidDecl(); 2922 } 2923 } 2924} 2925 2926/// CheckDestructor - Checks a fully-formed destructor definition for 2927/// well-formedness, issuing any diagnostics required. Returns true 2928/// on error. 2929bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 2930 CXXRecordDecl *RD = Destructor->getParent(); 2931 2932 if (Destructor->isVirtual()) { 2933 SourceLocation Loc; 2934 2935 if (!Destructor->isImplicit()) 2936 Loc = Destructor->getLocation(); 2937 else 2938 Loc = RD->getLocation(); 2939 2940 // If we have a virtual destructor, look up the deallocation function 2941 FunctionDecl *OperatorDelete = 0; 2942 DeclarationName Name = 2943 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2944 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2945 return true; 2946 2947 MarkDeclarationReferenced(Loc, OperatorDelete); 2948 2949 Destructor->setOperatorDelete(OperatorDelete); 2950 } 2951 2952 return false; 2953} 2954 2955static inline bool 2956FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2957 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2958 FTI.ArgInfo[0].Param && 2959 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 2960} 2961 2962/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2963/// the well-formednes of the destructor declarator @p D with type @p 2964/// R. If there are any errors in the declarator, this routine will 2965/// emit diagnostics and set the declarator to invalid. Even if this happens, 2966/// will be updated to reflect a well-formed type for the destructor and 2967/// returned. 2968QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 2969 StorageClass& SC) { 2970 // C++ [class.dtor]p1: 2971 // [...] A typedef-name that names a class is a class-name 2972 // (7.1.3); however, a typedef-name that names a class shall not 2973 // be used as the identifier in the declarator for a destructor 2974 // declaration. 2975 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2976 if (isa<TypedefType>(DeclaratorType)) 2977 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2978 << DeclaratorType; 2979 2980 // C++ [class.dtor]p2: 2981 // A destructor is used to destroy objects of its class type. A 2982 // destructor takes no parameters, and no return type can be 2983 // specified for it (not even void). The address of a destructor 2984 // shall not be taken. A destructor shall not be static. A 2985 // destructor can be invoked for a const, volatile or const 2986 // volatile object. A destructor shall not be declared const, 2987 // volatile or const volatile (9.3.2). 2988 if (SC == SC_Static) { 2989 if (!D.isInvalidType()) 2990 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2991 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2992 << SourceRange(D.getIdentifierLoc()) 2993 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 2994 2995 SC = SC_None; 2996 } 2997 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2998 // Destructors don't have return types, but the parser will 2999 // happily parse something like: 3000 // 3001 // class X { 3002 // float ~X(); 3003 // }; 3004 // 3005 // The return type will be eliminated later. 3006 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 3007 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3008 << SourceRange(D.getIdentifierLoc()); 3009 } 3010 3011 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3012 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3013 if (FTI.TypeQuals & Qualifiers::Const) 3014 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3015 << "const" << SourceRange(D.getIdentifierLoc()); 3016 if (FTI.TypeQuals & Qualifiers::Volatile) 3017 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3018 << "volatile" << SourceRange(D.getIdentifierLoc()); 3019 if (FTI.TypeQuals & Qualifiers::Restrict) 3020 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3021 << "restrict" << SourceRange(D.getIdentifierLoc()); 3022 D.setInvalidType(); 3023 } 3024 3025 // Make sure we don't have any parameters. 3026 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3027 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3028 3029 // Delete the parameters. 3030 FTI.freeArgs(); 3031 D.setInvalidType(); 3032 } 3033 3034 // Make sure the destructor isn't variadic. 3035 if (FTI.isVariadic) { 3036 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3037 D.setInvalidType(); 3038 } 3039 3040 // Rebuild the function type "R" without any type qualifiers or 3041 // parameters (in case any of the errors above fired) and with 3042 // "void" as the return type, since destructors don't have return 3043 // types. 3044 if (!D.isInvalidType()) 3045 return R; 3046 3047 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3048 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3049 EPI.Variadic = false; 3050 EPI.TypeQuals = 0; 3051 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 3052} 3053 3054/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3055/// well-formednes of the conversion function declarator @p D with 3056/// type @p R. If there are any errors in the declarator, this routine 3057/// will emit diagnostics and return true. Otherwise, it will return 3058/// false. Either way, the type @p R will be updated to reflect a 3059/// well-formed type for the conversion operator. 3060void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3061 StorageClass& SC) { 3062 // C++ [class.conv.fct]p1: 3063 // Neither parameter types nor return type can be specified. The 3064 // type of a conversion function (8.3.5) is "function taking no 3065 // parameter returning conversion-type-id." 3066 if (SC == SC_Static) { 3067 if (!D.isInvalidType()) 3068 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3069 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3070 << SourceRange(D.getIdentifierLoc()); 3071 D.setInvalidType(); 3072 SC = SC_None; 3073 } 3074 3075 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3076 3077 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3078 // Conversion functions don't have return types, but the parser will 3079 // happily parse something like: 3080 // 3081 // class X { 3082 // float operator bool(); 3083 // }; 3084 // 3085 // The return type will be changed later anyway. 3086 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3087 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3088 << SourceRange(D.getIdentifierLoc()); 3089 D.setInvalidType(); 3090 } 3091 3092 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3093 3094 // Make sure we don't have any parameters. 3095 if (Proto->getNumArgs() > 0) { 3096 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3097 3098 // Delete the parameters. 3099 D.getFunctionTypeInfo().freeArgs(); 3100 D.setInvalidType(); 3101 } else if (Proto->isVariadic()) { 3102 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3103 D.setInvalidType(); 3104 } 3105 3106 // Diagnose "&operator bool()" and other such nonsense. This 3107 // is actually a gcc extension which we don't support. 3108 if (Proto->getResultType() != ConvType) { 3109 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3110 << Proto->getResultType(); 3111 D.setInvalidType(); 3112 ConvType = Proto->getResultType(); 3113 } 3114 3115 // C++ [class.conv.fct]p4: 3116 // The conversion-type-id shall not represent a function type nor 3117 // an array type. 3118 if (ConvType->isArrayType()) { 3119 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3120 ConvType = Context.getPointerType(ConvType); 3121 D.setInvalidType(); 3122 } else if (ConvType->isFunctionType()) { 3123 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3124 ConvType = Context.getPointerType(ConvType); 3125 D.setInvalidType(); 3126 } 3127 3128 // Rebuild the function type "R" without any parameters (in case any 3129 // of the errors above fired) and with the conversion type as the 3130 // return type. 3131 if (D.isInvalidType()) 3132 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 3133 3134 // C++0x explicit conversion operators. 3135 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3136 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3137 diag::warn_explicit_conversion_functions) 3138 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3139} 3140 3141/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3142/// the declaration of the given C++ conversion function. This routine 3143/// is responsible for recording the conversion function in the C++ 3144/// class, if possible. 3145Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3146 assert(Conversion && "Expected to receive a conversion function declaration"); 3147 3148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3149 3150 // Make sure we aren't redeclaring the conversion function. 3151 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3152 3153 // C++ [class.conv.fct]p1: 3154 // [...] A conversion function is never used to convert a 3155 // (possibly cv-qualified) object to the (possibly cv-qualified) 3156 // same object type (or a reference to it), to a (possibly 3157 // cv-qualified) base class of that type (or a reference to it), 3158 // or to (possibly cv-qualified) void. 3159 // FIXME: Suppress this warning if the conversion function ends up being a 3160 // virtual function that overrides a virtual function in a base class. 3161 QualType ClassType 3162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3163 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3164 ConvType = ConvTypeRef->getPointeeType(); 3165 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 3166 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 3167 /* Suppress diagnostics for instantiations. */; 3168 else if (ConvType->isRecordType()) { 3169 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3170 if (ConvType == ClassType) 3171 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3172 << ClassType; 3173 else if (IsDerivedFrom(ClassType, ConvType)) 3174 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3175 << ClassType << ConvType; 3176 } else if (ConvType->isVoidType()) { 3177 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3178 << ClassType << ConvType; 3179 } 3180 3181 if (FunctionTemplateDecl *ConversionTemplate 3182 = Conversion->getDescribedFunctionTemplate()) 3183 return ConversionTemplate; 3184 3185 return Conversion; 3186} 3187 3188//===----------------------------------------------------------------------===// 3189// Namespace Handling 3190//===----------------------------------------------------------------------===// 3191 3192 3193 3194/// ActOnStartNamespaceDef - This is called at the start of a namespace 3195/// definition. 3196Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3197 SourceLocation InlineLoc, 3198 SourceLocation IdentLoc, 3199 IdentifierInfo *II, 3200 SourceLocation LBrace, 3201 AttributeList *AttrList) { 3202 // anonymous namespace starts at its left brace 3203 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 3204 (II ? IdentLoc : LBrace) , II); 3205 Namespc->setLBracLoc(LBrace); 3206 Namespc->setInline(InlineLoc.isValid()); 3207 3208 Scope *DeclRegionScope = NamespcScope->getParent(); 3209 3210 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3211 3212 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 3213 PushNamespaceVisibilityAttr(Attr); 3214 3215 if (II) { 3216 // C++ [namespace.def]p2: 3217 // The identifier in an original-namespace-definition shall not 3218 // have been previously defined in the declarative region in 3219 // which the original-namespace-definition appears. The 3220 // identifier in an original-namespace-definition is the name of 3221 // the namespace. Subsequently in that declarative region, it is 3222 // treated as an original-namespace-name. 3223 // 3224 // Since namespace names are unique in their scope, and we don't 3225 // look through using directives, just 3226 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 3227 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first; 3228 3229 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3230 // This is an extended namespace definition. 3231 if (Namespc->isInline() != OrigNS->isInline()) { 3232 // inline-ness must match 3233 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3234 << Namespc->isInline(); 3235 Diag(OrigNS->getLocation(), diag::note_previous_definition); 3236 Namespc->setInvalidDecl(); 3237 // Recover by ignoring the new namespace's inline status. 3238 Namespc->setInline(OrigNS->isInline()); 3239 } 3240 3241 // Attach this namespace decl to the chain of extended namespace 3242 // definitions. 3243 OrigNS->setNextNamespace(Namespc); 3244 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3245 3246 // Remove the previous declaration from the scope. 3247 if (DeclRegionScope->isDeclScope(OrigNS)) { 3248 IdResolver.RemoveDecl(OrigNS); 3249 DeclRegionScope->RemoveDecl(OrigNS); 3250 } 3251 } else if (PrevDecl) { 3252 // This is an invalid name redefinition. 3253 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3254 << Namespc->getDeclName(); 3255 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3256 Namespc->setInvalidDecl(); 3257 // Continue on to push Namespc as current DeclContext and return it. 3258 } else if (II->isStr("std") && 3259 CurContext->getRedeclContext()->isTranslationUnit()) { 3260 // This is the first "real" definition of the namespace "std", so update 3261 // our cache of the "std" namespace to point at this definition. 3262 if (NamespaceDecl *StdNS = getStdNamespace()) { 3263 // We had already defined a dummy namespace "std". Link this new 3264 // namespace definition to the dummy namespace "std". 3265 StdNS->setNextNamespace(Namespc); 3266 StdNS->setLocation(IdentLoc); 3267 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 3268 } 3269 3270 // Make our StdNamespace cache point at the first real definition of the 3271 // "std" namespace. 3272 StdNamespace = Namespc; 3273 } 3274 3275 PushOnScopeChains(Namespc, DeclRegionScope); 3276 } else { 3277 // Anonymous namespaces. 3278 assert(Namespc->isAnonymousNamespace()); 3279 3280 // Link the anonymous namespace into its parent. 3281 NamespaceDecl *PrevDecl; 3282 DeclContext *Parent = CurContext->getRedeclContext(); 3283 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3284 PrevDecl = TU->getAnonymousNamespace(); 3285 TU->setAnonymousNamespace(Namespc); 3286 } else { 3287 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3288 PrevDecl = ND->getAnonymousNamespace(); 3289 ND->setAnonymousNamespace(Namespc); 3290 } 3291 3292 // Link the anonymous namespace with its previous declaration. 3293 if (PrevDecl) { 3294 assert(PrevDecl->isAnonymousNamespace()); 3295 assert(!PrevDecl->getNextNamespace()); 3296 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3297 PrevDecl->setNextNamespace(Namespc); 3298 3299 if (Namespc->isInline() != PrevDecl->isInline()) { 3300 // inline-ness must match 3301 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3302 << Namespc->isInline(); 3303 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3304 Namespc->setInvalidDecl(); 3305 // Recover by ignoring the new namespace's inline status. 3306 Namespc->setInline(PrevDecl->isInline()); 3307 } 3308 } 3309 3310 CurContext->addDecl(Namespc); 3311 3312 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3313 // behaves as if it were replaced by 3314 // namespace unique { /* empty body */ } 3315 // using namespace unique; 3316 // namespace unique { namespace-body } 3317 // where all occurrences of 'unique' in a translation unit are 3318 // replaced by the same identifier and this identifier differs 3319 // from all other identifiers in the entire program. 3320 3321 // We just create the namespace with an empty name and then add an 3322 // implicit using declaration, just like the standard suggests. 3323 // 3324 // CodeGen enforces the "universally unique" aspect by giving all 3325 // declarations semantically contained within an anonymous 3326 // namespace internal linkage. 3327 3328 if (!PrevDecl) { 3329 UsingDirectiveDecl* UD 3330 = UsingDirectiveDecl::Create(Context, CurContext, 3331 /* 'using' */ LBrace, 3332 /* 'namespace' */ SourceLocation(), 3333 /* qualifier */ SourceRange(), 3334 /* NNS */ NULL, 3335 /* identifier */ SourceLocation(), 3336 Namespc, 3337 /* Ancestor */ CurContext); 3338 UD->setImplicit(); 3339 CurContext->addDecl(UD); 3340 } 3341 } 3342 3343 // Although we could have an invalid decl (i.e. the namespace name is a 3344 // redefinition), push it as current DeclContext and try to continue parsing. 3345 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3346 // for the namespace has the declarations that showed up in that particular 3347 // namespace definition. 3348 PushDeclContext(NamespcScope, Namespc); 3349 return Namespc; 3350} 3351 3352/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3353/// is a namespace alias, returns the namespace it points to. 3354static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3355 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3356 return AD->getNamespace(); 3357 return dyn_cast_or_null<NamespaceDecl>(D); 3358} 3359 3360/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3361/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3362void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 3363 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3364 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3365 Namespc->setRBracLoc(RBrace); 3366 PopDeclContext(); 3367 if (Namespc->hasAttr<VisibilityAttr>()) 3368 PopPragmaVisibility(); 3369} 3370 3371CXXRecordDecl *Sema::getStdBadAlloc() const { 3372 return cast_or_null<CXXRecordDecl>( 3373 StdBadAlloc.get(Context.getExternalSource())); 3374} 3375 3376NamespaceDecl *Sema::getStdNamespace() const { 3377 return cast_or_null<NamespaceDecl>( 3378 StdNamespace.get(Context.getExternalSource())); 3379} 3380 3381/// \brief Retrieve the special "std" namespace, which may require us to 3382/// implicitly define the namespace. 3383NamespaceDecl *Sema::getOrCreateStdNamespace() { 3384 if (!StdNamespace) { 3385 // The "std" namespace has not yet been defined, so build one implicitly. 3386 StdNamespace = NamespaceDecl::Create(Context, 3387 Context.getTranslationUnitDecl(), 3388 SourceLocation(), 3389 &PP.getIdentifierTable().get("std")); 3390 getStdNamespace()->setImplicit(true); 3391 } 3392 3393 return getStdNamespace(); 3394} 3395 3396Decl *Sema::ActOnUsingDirective(Scope *S, 3397 SourceLocation UsingLoc, 3398 SourceLocation NamespcLoc, 3399 CXXScopeSpec &SS, 3400 SourceLocation IdentLoc, 3401 IdentifierInfo *NamespcName, 3402 AttributeList *AttrList) { 3403 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3404 assert(NamespcName && "Invalid NamespcName."); 3405 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3406 3407 // This can only happen along a recovery path. 3408 while (S->getFlags() & Scope::TemplateParamScope) 3409 S = S->getParent(); 3410 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3411 3412 UsingDirectiveDecl *UDir = 0; 3413 NestedNameSpecifier *Qualifier = 0; 3414 if (SS.isSet()) 3415 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3416 3417 // Lookup namespace name. 3418 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3419 LookupParsedName(R, S, &SS); 3420 if (R.isAmbiguous()) 3421 return 0; 3422 3423 if (R.empty()) { 3424 // Allow "using namespace std;" or "using namespace ::std;" even if 3425 // "std" hasn't been defined yet, for GCC compatibility. 3426 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 3427 NamespcName->isStr("std")) { 3428 Diag(IdentLoc, diag::ext_using_undefined_std); 3429 R.addDecl(getOrCreateStdNamespace()); 3430 R.resolveKind(); 3431 } 3432 // Otherwise, attempt typo correction. 3433 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 3434 CTC_NoKeywords, 0)) { 3435 if (R.getAsSingle<NamespaceDecl>() || 3436 R.getAsSingle<NamespaceAliasDecl>()) { 3437 if (DeclContext *DC = computeDeclContext(SS, false)) 3438 Diag(IdentLoc, diag::err_using_directive_member_suggest) 3439 << NamespcName << DC << Corrected << SS.getRange() 3440 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3441 else 3442 Diag(IdentLoc, diag::err_using_directive_suggest) 3443 << NamespcName << Corrected 3444 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3445 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 3446 << Corrected; 3447 3448 NamespcName = Corrected.getAsIdentifierInfo(); 3449 } else { 3450 R.clear(); 3451 R.setLookupName(NamespcName); 3452 } 3453 } 3454 } 3455 3456 if (!R.empty()) { 3457 NamedDecl *Named = R.getFoundDecl(); 3458 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3459 && "expected namespace decl"); 3460 // C++ [namespace.udir]p1: 3461 // A using-directive specifies that the names in the nominated 3462 // namespace can be used in the scope in which the 3463 // using-directive appears after the using-directive. During 3464 // unqualified name lookup (3.4.1), the names appear as if they 3465 // were declared in the nearest enclosing namespace which 3466 // contains both the using-directive and the nominated 3467 // namespace. [Note: in this context, "contains" means "contains 3468 // directly or indirectly". ] 3469 3470 // Find enclosing context containing both using-directive and 3471 // nominated namespace. 3472 NamespaceDecl *NS = getNamespaceDecl(Named); 3473 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3474 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3475 CommonAncestor = CommonAncestor->getParent(); 3476 3477 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3478 SS.getRange(), 3479 (NestedNameSpecifier *)SS.getScopeRep(), 3480 IdentLoc, Named, CommonAncestor); 3481 PushUsingDirective(S, UDir); 3482 } else { 3483 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3484 } 3485 3486 // FIXME: We ignore attributes for now. 3487 return UDir; 3488} 3489 3490void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3491 // If scope has associated entity, then using directive is at namespace 3492 // or translation unit scope. We add UsingDirectiveDecls, into 3493 // it's lookup structure. 3494 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3495 Ctx->addDecl(UDir); 3496 else 3497 // Otherwise it is block-sope. using-directives will affect lookup 3498 // only to the end of scope. 3499 S->PushUsingDirective(UDir); 3500} 3501 3502 3503Decl *Sema::ActOnUsingDeclaration(Scope *S, 3504 AccessSpecifier AS, 3505 bool HasUsingKeyword, 3506 SourceLocation UsingLoc, 3507 CXXScopeSpec &SS, 3508 UnqualifiedId &Name, 3509 AttributeList *AttrList, 3510 bool IsTypeName, 3511 SourceLocation TypenameLoc) { 3512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3513 3514 switch (Name.getKind()) { 3515 case UnqualifiedId::IK_Identifier: 3516 case UnqualifiedId::IK_OperatorFunctionId: 3517 case UnqualifiedId::IK_LiteralOperatorId: 3518 case UnqualifiedId::IK_ConversionFunctionId: 3519 break; 3520 3521 case UnqualifiedId::IK_ConstructorName: 3522 case UnqualifiedId::IK_ConstructorTemplateId: 3523 // C++0x inherited constructors. 3524 if (getLangOptions().CPlusPlus0x) break; 3525 3526 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3527 << SS.getRange(); 3528 return 0; 3529 3530 case UnqualifiedId::IK_DestructorName: 3531 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3532 << SS.getRange(); 3533 return 0; 3534 3535 case UnqualifiedId::IK_TemplateId: 3536 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3537 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3538 return 0; 3539 } 3540 3541 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 3542 DeclarationName TargetName = TargetNameInfo.getName(); 3543 if (!TargetName) 3544 return 0; 3545 3546 // Warn about using declarations. 3547 // TODO: store that the declaration was written without 'using' and 3548 // talk about access decls instead of using decls in the 3549 // diagnostics. 3550 if (!HasUsingKeyword) { 3551 UsingLoc = Name.getSourceRange().getBegin(); 3552 3553 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3554 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3555 } 3556 3557 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 3558 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 3559 return 0; 3560 3561 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3562 TargetNameInfo, AttrList, 3563 /* IsInstantiation */ false, 3564 IsTypeName, TypenameLoc); 3565 if (UD) 3566 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3567 3568 return UD; 3569} 3570 3571/// \brief Determine whether a using declaration considers the given 3572/// declarations as "equivalent", e.g., if they are redeclarations of 3573/// the same entity or are both typedefs of the same type. 3574static bool 3575IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 3576 bool &SuppressRedeclaration) { 3577 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 3578 SuppressRedeclaration = false; 3579 return true; 3580 } 3581 3582 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1)) 3583 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) { 3584 SuppressRedeclaration = true; 3585 return Context.hasSameType(TD1->getUnderlyingType(), 3586 TD2->getUnderlyingType()); 3587 } 3588 3589 return false; 3590} 3591 3592 3593/// Determines whether to create a using shadow decl for a particular 3594/// decl, given the set of decls existing prior to this using lookup. 3595bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3596 const LookupResult &Previous) { 3597 // Diagnose finding a decl which is not from a base class of the 3598 // current class. We do this now because there are cases where this 3599 // function will silently decide not to build a shadow decl, which 3600 // will pre-empt further diagnostics. 3601 // 3602 // We don't need to do this in C++0x because we do the check once on 3603 // the qualifier. 3604 // 3605 // FIXME: diagnose the following if we care enough: 3606 // struct A { int foo; }; 3607 // struct B : A { using A::foo; }; 3608 // template <class T> struct C : A {}; 3609 // template <class T> struct D : C<T> { using B::foo; } // <--- 3610 // This is invalid (during instantiation) in C++03 because B::foo 3611 // resolves to the using decl in B, which is not a base class of D<T>. 3612 // We can't diagnose it immediately because C<T> is an unknown 3613 // specialization. The UsingShadowDecl in D<T> then points directly 3614 // to A::foo, which will look well-formed when we instantiate. 3615 // The right solution is to not collapse the shadow-decl chain. 3616 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3617 DeclContext *OrigDC = Orig->getDeclContext(); 3618 3619 // Handle enums and anonymous structs. 3620 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3621 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3622 while (OrigRec->isAnonymousStructOrUnion()) 3623 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3624 3625 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3626 if (OrigDC == CurContext) { 3627 Diag(Using->getLocation(), 3628 diag::err_using_decl_nested_name_specifier_is_current_class) 3629 << Using->getNestedNameRange(); 3630 Diag(Orig->getLocation(), diag::note_using_decl_target); 3631 return true; 3632 } 3633 3634 Diag(Using->getNestedNameRange().getBegin(), 3635 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3636 << Using->getTargetNestedNameDecl() 3637 << cast<CXXRecordDecl>(CurContext) 3638 << Using->getNestedNameRange(); 3639 Diag(Orig->getLocation(), diag::note_using_decl_target); 3640 return true; 3641 } 3642 } 3643 3644 if (Previous.empty()) return false; 3645 3646 NamedDecl *Target = Orig; 3647 if (isa<UsingShadowDecl>(Target)) 3648 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3649 3650 // If the target happens to be one of the previous declarations, we 3651 // don't have a conflict. 3652 // 3653 // FIXME: but we might be increasing its access, in which case we 3654 // should redeclare it. 3655 NamedDecl *NonTag = 0, *Tag = 0; 3656 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3657 I != E; ++I) { 3658 NamedDecl *D = (*I)->getUnderlyingDecl(); 3659 bool Result; 3660 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 3661 return Result; 3662 3663 (isa<TagDecl>(D) ? Tag : NonTag) = D; 3664 } 3665 3666 if (Target->isFunctionOrFunctionTemplate()) { 3667 FunctionDecl *FD; 3668 if (isa<FunctionTemplateDecl>(Target)) 3669 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3670 else 3671 FD = cast<FunctionDecl>(Target); 3672 3673 NamedDecl *OldDecl = 0; 3674 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 3675 case Ovl_Overload: 3676 return false; 3677 3678 case Ovl_NonFunction: 3679 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3680 break; 3681 3682 // We found a decl with the exact signature. 3683 case Ovl_Match: 3684 // If we're in a record, we want to hide the target, so we 3685 // return true (without a diagnostic) to tell the caller not to 3686 // build a shadow decl. 3687 if (CurContext->isRecord()) 3688 return true; 3689 3690 // If we're not in a record, this is an error. 3691 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3692 break; 3693 } 3694 3695 Diag(Target->getLocation(), diag::note_using_decl_target); 3696 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3697 return true; 3698 } 3699 3700 // Target is not a function. 3701 3702 if (isa<TagDecl>(Target)) { 3703 // No conflict between a tag and a non-tag. 3704 if (!Tag) return false; 3705 3706 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3707 Diag(Target->getLocation(), diag::note_using_decl_target); 3708 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3709 return true; 3710 } 3711 3712 // No conflict between a tag and a non-tag. 3713 if (!NonTag) return false; 3714 3715 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3716 Diag(Target->getLocation(), diag::note_using_decl_target); 3717 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3718 return true; 3719} 3720 3721/// Builds a shadow declaration corresponding to a 'using' declaration. 3722UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3723 UsingDecl *UD, 3724 NamedDecl *Orig) { 3725 3726 // If we resolved to another shadow declaration, just coalesce them. 3727 NamedDecl *Target = Orig; 3728 if (isa<UsingShadowDecl>(Target)) { 3729 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3730 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3731 } 3732 3733 UsingShadowDecl *Shadow 3734 = UsingShadowDecl::Create(Context, CurContext, 3735 UD->getLocation(), UD, Target); 3736 UD->addShadowDecl(Shadow); 3737 3738 Shadow->setAccess(UD->getAccess()); 3739 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3740 Shadow->setInvalidDecl(); 3741 3742 if (S) 3743 PushOnScopeChains(Shadow, S); 3744 else 3745 CurContext->addDecl(Shadow); 3746 3747 3748 return Shadow; 3749} 3750 3751/// Hides a using shadow declaration. This is required by the current 3752/// using-decl implementation when a resolvable using declaration in a 3753/// class is followed by a declaration which would hide or override 3754/// one or more of the using decl's targets; for example: 3755/// 3756/// struct Base { void foo(int); }; 3757/// struct Derived : Base { 3758/// using Base::foo; 3759/// void foo(int); 3760/// }; 3761/// 3762/// The governing language is C++03 [namespace.udecl]p12: 3763/// 3764/// When a using-declaration brings names from a base class into a 3765/// derived class scope, member functions in the derived class 3766/// override and/or hide member functions with the same name and 3767/// parameter types in a base class (rather than conflicting). 3768/// 3769/// There are two ways to implement this: 3770/// (1) optimistically create shadow decls when they're not hidden 3771/// by existing declarations, or 3772/// (2) don't create any shadow decls (or at least don't make them 3773/// visible) until we've fully parsed/instantiated the class. 3774/// The problem with (1) is that we might have to retroactively remove 3775/// a shadow decl, which requires several O(n) operations because the 3776/// decl structures are (very reasonably) not designed for removal. 3777/// (2) avoids this but is very fiddly and phase-dependent. 3778void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3779 if (Shadow->getDeclName().getNameKind() == 3780 DeclarationName::CXXConversionFunctionName) 3781 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 3782 3783 // Remove it from the DeclContext... 3784 Shadow->getDeclContext()->removeDecl(Shadow); 3785 3786 // ...and the scope, if applicable... 3787 if (S) { 3788 S->RemoveDecl(Shadow); 3789 IdResolver.RemoveDecl(Shadow); 3790 } 3791 3792 // ...and the using decl. 3793 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3794 3795 // TODO: complain somehow if Shadow was used. It shouldn't 3796 // be possible for this to happen, because...? 3797} 3798 3799/// Builds a using declaration. 3800/// 3801/// \param IsInstantiation - Whether this call arises from an 3802/// instantiation of an unresolved using declaration. We treat 3803/// the lookup differently for these declarations. 3804NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3805 SourceLocation UsingLoc, 3806 CXXScopeSpec &SS, 3807 const DeclarationNameInfo &NameInfo, 3808 AttributeList *AttrList, 3809 bool IsInstantiation, 3810 bool IsTypeName, 3811 SourceLocation TypenameLoc) { 3812 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3813 SourceLocation IdentLoc = NameInfo.getLoc(); 3814 assert(IdentLoc.isValid() && "Invalid TargetName location."); 3815 3816 // FIXME: We ignore attributes for now. 3817 3818 if (SS.isEmpty()) { 3819 Diag(IdentLoc, diag::err_using_requires_qualname); 3820 return 0; 3821 } 3822 3823 // Do the redeclaration lookup in the current scope. 3824 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 3825 ForRedeclaration); 3826 Previous.setHideTags(false); 3827 if (S) { 3828 LookupName(Previous, S); 3829 3830 // It is really dumb that we have to do this. 3831 LookupResult::Filter F = Previous.makeFilter(); 3832 while (F.hasNext()) { 3833 NamedDecl *D = F.next(); 3834 if (!isDeclInScope(D, CurContext, S)) 3835 F.erase(); 3836 } 3837 F.done(); 3838 } else { 3839 assert(IsInstantiation && "no scope in non-instantiation"); 3840 assert(CurContext->isRecord() && "scope not record in instantiation"); 3841 LookupQualifiedName(Previous, CurContext); 3842 } 3843 3844 NestedNameSpecifier *NNS = 3845 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3846 3847 // Check for invalid redeclarations. 3848 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3849 return 0; 3850 3851 // Check for bad qualifiers. 3852 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3853 return 0; 3854 3855 DeclContext *LookupContext = computeDeclContext(SS); 3856 NamedDecl *D; 3857 if (!LookupContext) { 3858 if (IsTypeName) { 3859 // FIXME: not all declaration name kinds are legal here 3860 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3861 UsingLoc, TypenameLoc, 3862 SS.getRange(), NNS, 3863 IdentLoc, NameInfo.getName()); 3864 } else { 3865 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3866 UsingLoc, SS.getRange(), 3867 NNS, NameInfo); 3868 } 3869 } else { 3870 D = UsingDecl::Create(Context, CurContext, 3871 SS.getRange(), UsingLoc, NNS, NameInfo, 3872 IsTypeName); 3873 } 3874 D->setAccess(AS); 3875 CurContext->addDecl(D); 3876 3877 if (!LookupContext) return D; 3878 UsingDecl *UD = cast<UsingDecl>(D); 3879 3880 if (RequireCompleteDeclContext(SS, LookupContext)) { 3881 UD->setInvalidDecl(); 3882 return UD; 3883 } 3884 3885 // Look up the target name. 3886 3887 LookupResult R(*this, NameInfo, LookupOrdinaryName); 3888 3889 // Unlike most lookups, we don't always want to hide tag 3890 // declarations: tag names are visible through the using declaration 3891 // even if hidden by ordinary names, *except* in a dependent context 3892 // where it's important for the sanity of two-phase lookup. 3893 if (!IsInstantiation) 3894 R.setHideTags(false); 3895 3896 LookupQualifiedName(R, LookupContext); 3897 3898 if (R.empty()) { 3899 Diag(IdentLoc, diag::err_no_member) 3900 << NameInfo.getName() << LookupContext << SS.getRange(); 3901 UD->setInvalidDecl(); 3902 return UD; 3903 } 3904 3905 if (R.isAmbiguous()) { 3906 UD->setInvalidDecl(); 3907 return UD; 3908 } 3909 3910 if (IsTypeName) { 3911 // If we asked for a typename and got a non-type decl, error out. 3912 if (!R.getAsSingle<TypeDecl>()) { 3913 Diag(IdentLoc, diag::err_using_typename_non_type); 3914 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3915 Diag((*I)->getUnderlyingDecl()->getLocation(), 3916 diag::note_using_decl_target); 3917 UD->setInvalidDecl(); 3918 return UD; 3919 } 3920 } else { 3921 // If we asked for a non-typename and we got a type, error out, 3922 // but only if this is an instantiation of an unresolved using 3923 // decl. Otherwise just silently find the type name. 3924 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3925 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3926 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3927 UD->setInvalidDecl(); 3928 return UD; 3929 } 3930 } 3931 3932 // C++0x N2914 [namespace.udecl]p6: 3933 // A using-declaration shall not name a namespace. 3934 if (R.getAsSingle<NamespaceDecl>()) { 3935 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3936 << SS.getRange(); 3937 UD->setInvalidDecl(); 3938 return UD; 3939 } 3940 3941 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3942 if (!CheckUsingShadowDecl(UD, *I, Previous)) 3943 BuildUsingShadowDecl(S, UD, *I); 3944 } 3945 3946 return UD; 3947} 3948 3949/// Checks that the given using declaration is not an invalid 3950/// redeclaration. Note that this is checking only for the using decl 3951/// itself, not for any ill-formedness among the UsingShadowDecls. 3952bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3953 bool isTypeName, 3954 const CXXScopeSpec &SS, 3955 SourceLocation NameLoc, 3956 const LookupResult &Prev) { 3957 // C++03 [namespace.udecl]p8: 3958 // C++0x [namespace.udecl]p10: 3959 // A using-declaration is a declaration and can therefore be used 3960 // repeatedly where (and only where) multiple declarations are 3961 // allowed. 3962 // 3963 // That's in non-member contexts. 3964 if (!CurContext->getRedeclContext()->isRecord()) 3965 return false; 3966 3967 NestedNameSpecifier *Qual 3968 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3969 3970 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3971 NamedDecl *D = *I; 3972 3973 bool DTypename; 3974 NestedNameSpecifier *DQual; 3975 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3976 DTypename = UD->isTypeName(); 3977 DQual = UD->getTargetNestedNameDecl(); 3978 } else if (UnresolvedUsingValueDecl *UD 3979 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3980 DTypename = false; 3981 DQual = UD->getTargetNestedNameSpecifier(); 3982 } else if (UnresolvedUsingTypenameDecl *UD 3983 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3984 DTypename = true; 3985 DQual = UD->getTargetNestedNameSpecifier(); 3986 } else continue; 3987 3988 // using decls differ if one says 'typename' and the other doesn't. 3989 // FIXME: non-dependent using decls? 3990 if (isTypeName != DTypename) continue; 3991 3992 // using decls differ if they name different scopes (but note that 3993 // template instantiation can cause this check to trigger when it 3994 // didn't before instantiation). 3995 if (Context.getCanonicalNestedNameSpecifier(Qual) != 3996 Context.getCanonicalNestedNameSpecifier(DQual)) 3997 continue; 3998 3999 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 4000 Diag(D->getLocation(), diag::note_using_decl) << 1; 4001 return true; 4002 } 4003 4004 return false; 4005} 4006 4007 4008/// Checks that the given nested-name qualifier used in a using decl 4009/// in the current context is appropriately related to the current 4010/// scope. If an error is found, diagnoses it and returns true. 4011bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 4012 const CXXScopeSpec &SS, 4013 SourceLocation NameLoc) { 4014 DeclContext *NamedContext = computeDeclContext(SS); 4015 4016 if (!CurContext->isRecord()) { 4017 // C++03 [namespace.udecl]p3: 4018 // C++0x [namespace.udecl]p8: 4019 // A using-declaration for a class member shall be a member-declaration. 4020 4021 // If we weren't able to compute a valid scope, it must be a 4022 // dependent class scope. 4023 if (!NamedContext || NamedContext->isRecord()) { 4024 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4025 << SS.getRange(); 4026 return true; 4027 } 4028 4029 // Otherwise, everything is known to be fine. 4030 return false; 4031 } 4032 4033 // The current scope is a record. 4034 4035 // If the named context is dependent, we can't decide much. 4036 if (!NamedContext) { 4037 // FIXME: in C++0x, we can diagnose if we can prove that the 4038 // nested-name-specifier does not refer to a base class, which is 4039 // still possible in some cases. 4040 4041 // Otherwise we have to conservatively report that things might be 4042 // okay. 4043 return false; 4044 } 4045 4046 if (!NamedContext->isRecord()) { 4047 // Ideally this would point at the last name in the specifier, 4048 // but we don't have that level of source info. 4049 Diag(SS.getRange().getBegin(), 4050 diag::err_using_decl_nested_name_specifier_is_not_class) 4051 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4052 return true; 4053 } 4054 4055 if (getLangOptions().CPlusPlus0x) { 4056 // C++0x [namespace.udecl]p3: 4057 // In a using-declaration used as a member-declaration, the 4058 // nested-name-specifier shall name a base class of the class 4059 // being defined. 4060 4061 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4062 cast<CXXRecordDecl>(NamedContext))) { 4063 if (CurContext == NamedContext) { 4064 Diag(NameLoc, 4065 diag::err_using_decl_nested_name_specifier_is_current_class) 4066 << SS.getRange(); 4067 return true; 4068 } 4069 4070 Diag(SS.getRange().getBegin(), 4071 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4072 << (NestedNameSpecifier*) SS.getScopeRep() 4073 << cast<CXXRecordDecl>(CurContext) 4074 << SS.getRange(); 4075 return true; 4076 } 4077 4078 return false; 4079 } 4080 4081 // C++03 [namespace.udecl]p4: 4082 // A using-declaration used as a member-declaration shall refer 4083 // to a member of a base class of the class being defined [etc.]. 4084 4085 // Salient point: SS doesn't have to name a base class as long as 4086 // lookup only finds members from base classes. Therefore we can 4087 // diagnose here only if we can prove that that can't happen, 4088 // i.e. if the class hierarchies provably don't intersect. 4089 4090 // TODO: it would be nice if "definitely valid" results were cached 4091 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4092 // need to be repeated. 4093 4094 struct UserData { 4095 llvm::DenseSet<const CXXRecordDecl*> Bases; 4096 4097 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4098 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4099 Data->Bases.insert(Base); 4100 return true; 4101 } 4102 4103 bool hasDependentBases(const CXXRecordDecl *Class) { 4104 return !Class->forallBases(collect, this); 4105 } 4106 4107 /// Returns true if the base is dependent or is one of the 4108 /// accumulated base classes. 4109 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4110 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4111 return !Data->Bases.count(Base); 4112 } 4113 4114 bool mightShareBases(const CXXRecordDecl *Class) { 4115 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4116 } 4117 }; 4118 4119 UserData Data; 4120 4121 // Returns false if we find a dependent base. 4122 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4123 return false; 4124 4125 // Returns false if the class has a dependent base or if it or one 4126 // of its bases is present in the base set of the current context. 4127 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4128 return false; 4129 4130 Diag(SS.getRange().getBegin(), 4131 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4132 << (NestedNameSpecifier*) SS.getScopeRep() 4133 << cast<CXXRecordDecl>(CurContext) 4134 << SS.getRange(); 4135 4136 return true; 4137} 4138 4139Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 4140 SourceLocation NamespaceLoc, 4141 SourceLocation AliasLoc, 4142 IdentifierInfo *Alias, 4143 CXXScopeSpec &SS, 4144 SourceLocation IdentLoc, 4145 IdentifierInfo *Ident) { 4146 4147 // Lookup the namespace name. 4148 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4149 LookupParsedName(R, S, &SS); 4150 4151 // Check if we have a previous declaration with the same name. 4152 NamedDecl *PrevDecl 4153 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4154 ForRedeclaration); 4155 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4156 PrevDecl = 0; 4157 4158 if (PrevDecl) { 4159 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4160 // We already have an alias with the same name that points to the same 4161 // namespace, so don't create a new one. 4162 // FIXME: At some point, we'll want to create the (redundant) 4163 // declaration to maintain better source information. 4164 if (!R.isAmbiguous() && !R.empty() && 4165 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4166 return 0; 4167 } 4168 4169 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4170 diag::err_redefinition_different_kind; 4171 Diag(AliasLoc, DiagID) << Alias; 4172 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4173 return 0; 4174 } 4175 4176 if (R.isAmbiguous()) 4177 return 0; 4178 4179 if (R.empty()) { 4180 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4181 CTC_NoKeywords, 0)) { 4182 if (R.getAsSingle<NamespaceDecl>() || 4183 R.getAsSingle<NamespaceAliasDecl>()) { 4184 if (DeclContext *DC = computeDeclContext(SS, false)) 4185 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4186 << Ident << DC << Corrected << SS.getRange() 4187 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4188 else 4189 Diag(IdentLoc, diag::err_using_directive_suggest) 4190 << Ident << Corrected 4191 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4192 4193 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4194 << Corrected; 4195 4196 Ident = Corrected.getAsIdentifierInfo(); 4197 } else { 4198 R.clear(); 4199 R.setLookupName(Ident); 4200 } 4201 } 4202 4203 if (R.empty()) { 4204 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4205 return 0; 4206 } 4207 } 4208 4209 NamespaceAliasDecl *AliasDecl = 4210 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4211 Alias, SS.getRange(), 4212 (NestedNameSpecifier *)SS.getScopeRep(), 4213 IdentLoc, R.getFoundDecl()); 4214 4215 PushOnScopeChains(AliasDecl, S); 4216 return AliasDecl; 4217} 4218 4219namespace { 4220 /// \brief Scoped object used to handle the state changes required in Sema 4221 /// to implicitly define the body of a C++ member function; 4222 class ImplicitlyDefinedFunctionScope { 4223 Sema &S; 4224 DeclContext *PreviousContext; 4225 4226 public: 4227 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4228 : S(S), PreviousContext(S.CurContext) 4229 { 4230 S.CurContext = Method; 4231 S.PushFunctionScope(); 4232 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4233 } 4234 4235 ~ImplicitlyDefinedFunctionScope() { 4236 S.PopExpressionEvaluationContext(); 4237 S.PopFunctionOrBlockScope(); 4238 S.CurContext = PreviousContext; 4239 } 4240 }; 4241} 4242 4243static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 4244 CXXRecordDecl *D) { 4245 ASTContext &Context = Self.Context; 4246 QualType ClassType = Context.getTypeDeclType(D); 4247 DeclarationName ConstructorName 4248 = Context.DeclarationNames.getCXXConstructorName( 4249 Context.getCanonicalType(ClassType.getUnqualifiedType())); 4250 4251 DeclContext::lookup_const_iterator Con, ConEnd; 4252 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 4253 Con != ConEnd; ++Con) { 4254 // FIXME: In C++0x, a constructor template can be a default constructor. 4255 if (isa<FunctionTemplateDecl>(*Con)) 4256 continue; 4257 4258 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 4259 if (Constructor->isDefaultConstructor()) 4260 return Constructor; 4261 } 4262 return 0; 4263} 4264 4265CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 4266 CXXRecordDecl *ClassDecl) { 4267 // C++ [class.ctor]p5: 4268 // A default constructor for a class X is a constructor of class X 4269 // that can be called without an argument. If there is no 4270 // user-declared constructor for class X, a default constructor is 4271 // implicitly declared. An implicitly-declared default constructor 4272 // is an inline public member of its class. 4273 assert(!ClassDecl->hasUserDeclaredConstructor() && 4274 "Should not build implicit default constructor!"); 4275 4276 // C++ [except.spec]p14: 4277 // An implicitly declared special member function (Clause 12) shall have an 4278 // exception-specification. [...] 4279 ImplicitExceptionSpecification ExceptSpec(Context); 4280 4281 // Direct base-class destructors. 4282 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4283 BEnd = ClassDecl->bases_end(); 4284 B != BEnd; ++B) { 4285 if (B->isVirtual()) // Handled below. 4286 continue; 4287 4288 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4289 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4290 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4291 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4292 else if (CXXConstructorDecl *Constructor 4293 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4294 ExceptSpec.CalledDecl(Constructor); 4295 } 4296 } 4297 4298 // Virtual base-class destructors. 4299 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4300 BEnd = ClassDecl->vbases_end(); 4301 B != BEnd; ++B) { 4302 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4303 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4304 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4305 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4306 else if (CXXConstructorDecl *Constructor 4307 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4308 ExceptSpec.CalledDecl(Constructor); 4309 } 4310 } 4311 4312 // Field destructors. 4313 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4314 FEnd = ClassDecl->field_end(); 4315 F != FEnd; ++F) { 4316 if (const RecordType *RecordTy 4317 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4318 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4319 if (!FieldClassDecl->hasDeclaredDefaultConstructor()) 4320 ExceptSpec.CalledDecl( 4321 DeclareImplicitDefaultConstructor(FieldClassDecl)); 4322 else if (CXXConstructorDecl *Constructor 4323 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 4324 ExceptSpec.CalledDecl(Constructor); 4325 } 4326 } 4327 4328 FunctionProtoType::ExtProtoInfo EPI; 4329 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification(); 4330 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification(); 4331 EPI.NumExceptions = ExceptSpec.size(); 4332 EPI.Exceptions = ExceptSpec.data(); 4333 4334 // Create the actual constructor declaration. 4335 CanQualType ClassType 4336 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4337 DeclarationName Name 4338 = Context.DeclarationNames.getCXXConstructorName(ClassType); 4339 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4340 CXXConstructorDecl *DefaultCon 4341 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo, 4342 Context.getFunctionType(Context.VoidTy, 4343 0, 0, EPI), 4344 /*TInfo=*/0, 4345 /*isExplicit=*/false, 4346 /*isInline=*/true, 4347 /*isImplicitlyDeclared=*/true); 4348 DefaultCon->setAccess(AS_public); 4349 DefaultCon->setImplicit(); 4350 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 4351 4352 // Note that we have declared this constructor. 4353 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 4354 4355 if (Scope *S = getScopeForContext(ClassDecl)) 4356 PushOnScopeChains(DefaultCon, S, false); 4357 ClassDecl->addDecl(DefaultCon); 4358 4359 return DefaultCon; 4360} 4361 4362void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4363 CXXConstructorDecl *Constructor) { 4364 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4365 !Constructor->isUsed(false)) && 4366 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4367 4368 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4369 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4370 4371 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4372 DiagnosticErrorTrap Trap(Diags); 4373 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4374 Trap.hasErrorOccurred()) { 4375 Diag(CurrentLocation, diag::note_member_synthesized_at) 4376 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4377 Constructor->setInvalidDecl(); 4378 return; 4379 } 4380 4381 SourceLocation Loc = Constructor->getLocation(); 4382 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4383 4384 Constructor->setUsed(); 4385 MarkVTableUsed(CurrentLocation, ClassDecl); 4386} 4387 4388CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 4389 // C++ [class.dtor]p2: 4390 // If a class has no user-declared destructor, a destructor is 4391 // declared implicitly. An implicitly-declared destructor is an 4392 // inline public member of its class. 4393 4394 // C++ [except.spec]p14: 4395 // An implicitly declared special member function (Clause 12) shall have 4396 // an exception-specification. 4397 ImplicitExceptionSpecification ExceptSpec(Context); 4398 4399 // Direct base-class destructors. 4400 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4401 BEnd = ClassDecl->bases_end(); 4402 B != BEnd; ++B) { 4403 if (B->isVirtual()) // Handled below. 4404 continue; 4405 4406 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 4407 ExceptSpec.CalledDecl( 4408 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 4409 } 4410 4411 // Virtual base-class destructors. 4412 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4413 BEnd = ClassDecl->vbases_end(); 4414 B != BEnd; ++B) { 4415 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 4416 ExceptSpec.CalledDecl( 4417 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 4418 } 4419 4420 // Field destructors. 4421 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4422 FEnd = ClassDecl->field_end(); 4423 F != FEnd; ++F) { 4424 if (const RecordType *RecordTy 4425 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 4426 ExceptSpec.CalledDecl( 4427 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 4428 } 4429 4430 // Create the actual destructor declaration. 4431 FunctionProtoType::ExtProtoInfo EPI; 4432 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification(); 4433 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification(); 4434 EPI.NumExceptions = ExceptSpec.size(); 4435 EPI.Exceptions = ExceptSpec.data(); 4436 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 4437 4438 CanQualType ClassType 4439 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4440 DeclarationName Name 4441 = Context.DeclarationNames.getCXXDestructorName(ClassType); 4442 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4443 CXXDestructorDecl *Destructor 4444 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0, 4445 /*isInline=*/true, 4446 /*isImplicitlyDeclared=*/true); 4447 Destructor->setAccess(AS_public); 4448 Destructor->setImplicit(); 4449 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 4450 4451 // Note that we have declared this destructor. 4452 ++ASTContext::NumImplicitDestructorsDeclared; 4453 4454 // Introduce this destructor into its scope. 4455 if (Scope *S = getScopeForContext(ClassDecl)) 4456 PushOnScopeChains(Destructor, S, false); 4457 ClassDecl->addDecl(Destructor); 4458 4459 // This could be uniqued if it ever proves significant. 4460 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 4461 4462 AddOverriddenMethods(ClassDecl, Destructor); 4463 4464 return Destructor; 4465} 4466 4467void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 4468 CXXDestructorDecl *Destructor) { 4469 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) && 4470 "DefineImplicitDestructor - call it for implicit default dtor"); 4471 CXXRecordDecl *ClassDecl = Destructor->getParent(); 4472 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 4473 4474 if (Destructor->isInvalidDecl()) 4475 return; 4476 4477 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 4478 4479 DiagnosticErrorTrap Trap(Diags); 4480 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4481 Destructor->getParent()); 4482 4483 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 4484 Diag(CurrentLocation, diag::note_member_synthesized_at) 4485 << CXXDestructor << Context.getTagDeclType(ClassDecl); 4486 4487 Destructor->setInvalidDecl(); 4488 return; 4489 } 4490 4491 SourceLocation Loc = Destructor->getLocation(); 4492 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4493 4494 Destructor->setUsed(); 4495 MarkVTableUsed(CurrentLocation, ClassDecl); 4496} 4497 4498/// \brief Builds a statement that copies the given entity from \p From to 4499/// \c To. 4500/// 4501/// This routine is used to copy the members of a class with an 4502/// implicitly-declared copy assignment operator. When the entities being 4503/// copied are arrays, this routine builds for loops to copy them. 4504/// 4505/// \param S The Sema object used for type-checking. 4506/// 4507/// \param Loc The location where the implicit copy is being generated. 4508/// 4509/// \param T The type of the expressions being copied. Both expressions must 4510/// have this type. 4511/// 4512/// \param To The expression we are copying to. 4513/// 4514/// \param From The expression we are copying from. 4515/// 4516/// \param CopyingBaseSubobject Whether we're copying a base subobject. 4517/// Otherwise, it's a non-static member subobject. 4518/// 4519/// \param Depth Internal parameter recording the depth of the recursion. 4520/// 4521/// \returns A statement or a loop that copies the expressions. 4522static StmtResult 4523BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 4524 Expr *To, Expr *From, 4525 bool CopyingBaseSubobject, unsigned Depth = 0) { 4526 // C++0x [class.copy]p30: 4527 // Each subobject is assigned in the manner appropriate to its type: 4528 // 4529 // - if the subobject is of class type, the copy assignment operator 4530 // for the class is used (as if by explicit qualification; that is, 4531 // ignoring any possible virtual overriding functions in more derived 4532 // classes); 4533 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 4534 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4535 4536 // Look for operator=. 4537 DeclarationName Name 4538 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4539 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 4540 S.LookupQualifiedName(OpLookup, ClassDecl, false); 4541 4542 // Filter out any result that isn't a copy-assignment operator. 4543 LookupResult::Filter F = OpLookup.makeFilter(); 4544 while (F.hasNext()) { 4545 NamedDecl *D = F.next(); 4546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 4547 if (Method->isCopyAssignmentOperator()) 4548 continue; 4549 4550 F.erase(); 4551 } 4552 F.done(); 4553 4554 // Suppress the protected check (C++ [class.protected]) for each of the 4555 // assignment operators we found. This strange dance is required when 4556 // we're assigning via a base classes's copy-assignment operator. To 4557 // ensure that we're getting the right base class subobject (without 4558 // ambiguities), we need to cast "this" to that subobject type; to 4559 // ensure that we don't go through the virtual call mechanism, we need 4560 // to qualify the operator= name with the base class (see below). However, 4561 // this means that if the base class has a protected copy assignment 4562 // operator, the protected member access check will fail. So, we 4563 // rewrite "protected" access to "public" access in this case, since we 4564 // know by construction that we're calling from a derived class. 4565 if (CopyingBaseSubobject) { 4566 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 4567 L != LEnd; ++L) { 4568 if (L.getAccess() == AS_protected) 4569 L.setAccess(AS_public); 4570 } 4571 } 4572 4573 // Create the nested-name-specifier that will be used to qualify the 4574 // reference to operator=; this is required to suppress the virtual 4575 // call mechanism. 4576 CXXScopeSpec SS; 4577 SS.setRange(Loc); 4578 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false, 4579 T.getTypePtr())); 4580 4581 // Create the reference to operator=. 4582 ExprResult OpEqualRef 4583 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 4584 /*FirstQualifierInScope=*/0, OpLookup, 4585 /*TemplateArgs=*/0, 4586 /*SuppressQualifierCheck=*/true); 4587 if (OpEqualRef.isInvalid()) 4588 return StmtError(); 4589 4590 // Build the call to the assignment operator. 4591 4592 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 4593 OpEqualRef.takeAs<Expr>(), 4594 Loc, &From, 1, Loc); 4595 if (Call.isInvalid()) 4596 return StmtError(); 4597 4598 return S.Owned(Call.takeAs<Stmt>()); 4599 } 4600 4601 // - if the subobject is of scalar type, the built-in assignment 4602 // operator is used. 4603 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 4604 if (!ArrayTy) { 4605 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 4606 if (Assignment.isInvalid()) 4607 return StmtError(); 4608 4609 return S.Owned(Assignment.takeAs<Stmt>()); 4610 } 4611 4612 // - if the subobject is an array, each element is assigned, in the 4613 // manner appropriate to the element type; 4614 4615 // Construct a loop over the array bounds, e.g., 4616 // 4617 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 4618 // 4619 // that will copy each of the array elements. 4620 QualType SizeType = S.Context.getSizeType(); 4621 4622 // Create the iteration variable. 4623 IdentifierInfo *IterationVarName = 0; 4624 { 4625 llvm::SmallString<8> Str; 4626 llvm::raw_svector_ostream OS(Str); 4627 OS << "__i" << Depth; 4628 IterationVarName = &S.Context.Idents.get(OS.str()); 4629 } 4630 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, 4631 IterationVarName, SizeType, 4632 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 4633 SC_None, SC_None); 4634 4635 // Initialize the iteration variable to zero. 4636 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 4637 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 4638 4639 // Create a reference to the iteration variable; we'll use this several 4640 // times throughout. 4641 Expr *IterationVarRef 4642 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 4643 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 4644 4645 // Create the DeclStmt that holds the iteration variable. 4646 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 4647 4648 // Create the comparison against the array bound. 4649 llvm::APInt Upper 4650 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 4651 Expr *Comparison 4652 = new (S.Context) BinaryOperator(IterationVarRef, 4653 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 4654 BO_NE, S.Context.BoolTy, 4655 VK_RValue, OK_Ordinary, Loc); 4656 4657 // Create the pre-increment of the iteration variable. 4658 Expr *Increment 4659 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 4660 VK_LValue, OK_Ordinary, Loc); 4661 4662 // Subscript the "from" and "to" expressions with the iteration variable. 4663 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 4664 IterationVarRef, Loc)); 4665 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 4666 IterationVarRef, Loc)); 4667 4668 // Build the copy for an individual element of the array. 4669 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 4670 To, From, CopyingBaseSubobject, 4671 Depth + 1); 4672 if (Copy.isInvalid()) 4673 return StmtError(); 4674 4675 // Construct the loop that copies all elements of this array. 4676 return S.ActOnForStmt(Loc, Loc, InitStmt, 4677 S.MakeFullExpr(Comparison), 4678 0, S.MakeFullExpr(Increment), 4679 Loc, Copy.take()); 4680} 4681 4682/// \brief Determine whether the given class has a copy assignment operator 4683/// that accepts a const-qualified argument. 4684static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 4685 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 4686 4687 if (!Class->hasDeclaredCopyAssignment()) 4688 S.DeclareImplicitCopyAssignment(Class); 4689 4690 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 4691 DeclarationName OpName 4692 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4693 4694 DeclContext::lookup_const_iterator Op, OpEnd; 4695 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 4696 // C++ [class.copy]p9: 4697 // A user-declared copy assignment operator is a non-static non-template 4698 // member function of class X with exactly one parameter of type X, X&, 4699 // const X&, volatile X& or const volatile X&. 4700 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 4701 if (!Method) 4702 continue; 4703 4704 if (Method->isStatic()) 4705 continue; 4706 if (Method->getPrimaryTemplate()) 4707 continue; 4708 const FunctionProtoType *FnType = 4709 Method->getType()->getAs<FunctionProtoType>(); 4710 assert(FnType && "Overloaded operator has no prototype."); 4711 // Don't assert on this; an invalid decl might have been left in the AST. 4712 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 4713 continue; 4714 bool AcceptsConst = true; 4715 QualType ArgType = FnType->getArgType(0); 4716 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 4717 ArgType = Ref->getPointeeType(); 4718 // Is it a non-const lvalue reference? 4719 if (!ArgType.isConstQualified()) 4720 AcceptsConst = false; 4721 } 4722 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 4723 continue; 4724 4725 // We have a single argument of type cv X or cv X&, i.e. we've found the 4726 // copy assignment operator. Return whether it accepts const arguments. 4727 return AcceptsConst; 4728 } 4729 assert(Class->isInvalidDecl() && 4730 "No copy assignment operator declared in valid code."); 4731 return false; 4732} 4733 4734CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 4735 // Note: The following rules are largely analoguous to the copy 4736 // constructor rules. Note that virtual bases are not taken into account 4737 // for determining the argument type of the operator. Note also that 4738 // operators taking an object instead of a reference are allowed. 4739 4740 4741 // C++ [class.copy]p10: 4742 // If the class definition does not explicitly declare a copy 4743 // assignment operator, one is declared implicitly. 4744 // The implicitly-defined copy assignment operator for a class X 4745 // will have the form 4746 // 4747 // X& X::operator=(const X&) 4748 // 4749 // if 4750 bool HasConstCopyAssignment = true; 4751 4752 // -- each direct base class B of X has a copy assignment operator 4753 // whose parameter is of type const B&, const volatile B& or B, 4754 // and 4755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4756 BaseEnd = ClassDecl->bases_end(); 4757 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 4758 assert(!Base->getType()->isDependentType() && 4759 "Cannot generate implicit members for class with dependent bases."); 4760 const CXXRecordDecl *BaseClassDecl 4761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4762 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 4763 } 4764 4765 // -- for all the nonstatic data members of X that are of a class 4766 // type M (or array thereof), each such class type has a copy 4767 // assignment operator whose parameter is of type const M&, 4768 // const volatile M& or M. 4769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4770 FieldEnd = ClassDecl->field_end(); 4771 HasConstCopyAssignment && Field != FieldEnd; 4772 ++Field) { 4773 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 4774 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4775 const CXXRecordDecl *FieldClassDecl 4776 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4777 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 4778 } 4779 } 4780 4781 // Otherwise, the implicitly declared copy assignment operator will 4782 // have the form 4783 // 4784 // X& X::operator=(X&) 4785 QualType ArgType = Context.getTypeDeclType(ClassDecl); 4786 QualType RetType = Context.getLValueReferenceType(ArgType); 4787 if (HasConstCopyAssignment) 4788 ArgType = ArgType.withConst(); 4789 ArgType = Context.getLValueReferenceType(ArgType); 4790 4791 // C++ [except.spec]p14: 4792 // An implicitly declared special member function (Clause 12) shall have an 4793 // exception-specification. [...] 4794 ImplicitExceptionSpecification ExceptSpec(Context); 4795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4796 BaseEnd = ClassDecl->bases_end(); 4797 Base != BaseEnd; ++Base) { 4798 CXXRecordDecl *BaseClassDecl 4799 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4800 4801 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 4802 DeclareImplicitCopyAssignment(BaseClassDecl); 4803 4804 if (CXXMethodDecl *CopyAssign 4805 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 4806 ExceptSpec.CalledDecl(CopyAssign); 4807 } 4808 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4809 FieldEnd = ClassDecl->field_end(); 4810 Field != FieldEnd; 4811 ++Field) { 4812 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 4813 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4814 CXXRecordDecl *FieldClassDecl 4815 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4816 4817 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 4818 DeclareImplicitCopyAssignment(FieldClassDecl); 4819 4820 if (CXXMethodDecl *CopyAssign 4821 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 4822 ExceptSpec.CalledDecl(CopyAssign); 4823 } 4824 } 4825 4826 // An implicitly-declared copy assignment operator is an inline public 4827 // member of its class. 4828 FunctionProtoType::ExtProtoInfo EPI; 4829 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification(); 4830 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification(); 4831 EPI.NumExceptions = ExceptSpec.size(); 4832 EPI.Exceptions = ExceptSpec.data(); 4833 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4834 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4835 CXXMethodDecl *CopyAssignment 4836 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo, 4837 Context.getFunctionType(RetType, &ArgType, 1, EPI), 4838 /*TInfo=*/0, /*isStatic=*/false, 4839 /*StorageClassAsWritten=*/SC_None, 4840 /*isInline=*/true); 4841 CopyAssignment->setAccess(AS_public); 4842 CopyAssignment->setImplicit(); 4843 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 4844 4845 // Add the parameter to the operator. 4846 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 4847 ClassDecl->getLocation(), 4848 /*Id=*/0, 4849 ArgType, /*TInfo=*/0, 4850 SC_None, 4851 SC_None, 0); 4852 CopyAssignment->setParams(&FromParam, 1); 4853 4854 // Note that we have added this copy-assignment operator. 4855 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 4856 4857 if (Scope *S = getScopeForContext(ClassDecl)) 4858 PushOnScopeChains(CopyAssignment, S, false); 4859 ClassDecl->addDecl(CopyAssignment); 4860 4861 AddOverriddenMethods(ClassDecl, CopyAssignment); 4862 return CopyAssignment; 4863} 4864 4865void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 4866 CXXMethodDecl *CopyAssignOperator) { 4867 assert((CopyAssignOperator->isImplicit() && 4868 CopyAssignOperator->isOverloadedOperator() && 4869 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 4870 !CopyAssignOperator->isUsed(false)) && 4871 "DefineImplicitCopyAssignment called for wrong function"); 4872 4873 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 4874 4875 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 4876 CopyAssignOperator->setInvalidDecl(); 4877 return; 4878 } 4879 4880 CopyAssignOperator->setUsed(); 4881 4882 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 4883 DiagnosticErrorTrap Trap(Diags); 4884 4885 // C++0x [class.copy]p30: 4886 // The implicitly-defined or explicitly-defaulted copy assignment operator 4887 // for a non-union class X performs memberwise copy assignment of its 4888 // subobjects. The direct base classes of X are assigned first, in the 4889 // order of their declaration in the base-specifier-list, and then the 4890 // immediate non-static data members of X are assigned, in the order in 4891 // which they were declared in the class definition. 4892 4893 // The statements that form the synthesized function body. 4894 ASTOwningVector<Stmt*> Statements(*this); 4895 4896 // The parameter for the "other" object, which we are copying from. 4897 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 4898 Qualifiers OtherQuals = Other->getType().getQualifiers(); 4899 QualType OtherRefType = Other->getType(); 4900 if (const LValueReferenceType *OtherRef 4901 = OtherRefType->getAs<LValueReferenceType>()) { 4902 OtherRefType = OtherRef->getPointeeType(); 4903 OtherQuals = OtherRefType.getQualifiers(); 4904 } 4905 4906 // Our location for everything implicitly-generated. 4907 SourceLocation Loc = CopyAssignOperator->getLocation(); 4908 4909 // Construct a reference to the "other" object. We'll be using this 4910 // throughout the generated ASTs. 4911 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 4912 assert(OtherRef && "Reference to parameter cannot fail!"); 4913 4914 // Construct the "this" pointer. We'll be using this throughout the generated 4915 // ASTs. 4916 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 4917 assert(This && "Reference to this cannot fail!"); 4918 4919 // Assign base classes. 4920 bool Invalid = false; 4921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4922 E = ClassDecl->bases_end(); Base != E; ++Base) { 4923 // Form the assignment: 4924 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 4925 QualType BaseType = Base->getType().getUnqualifiedType(); 4926 CXXRecordDecl *BaseClassDecl = 0; 4927 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>()) 4928 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl()); 4929 else { 4930 Invalid = true; 4931 continue; 4932 } 4933 4934 CXXCastPath BasePath; 4935 BasePath.push_back(Base); 4936 4937 // Construct the "from" expression, which is an implicit cast to the 4938 // appropriately-qualified base type. 4939 Expr *From = OtherRef; 4940 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 4941 CK_UncheckedDerivedToBase, 4942 VK_LValue, &BasePath); 4943 4944 // Dereference "this". 4945 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 4946 4947 // Implicitly cast "this" to the appropriately-qualified base type. 4948 Expr *ToE = To.takeAs<Expr>(); 4949 ImpCastExprToType(ToE, 4950 Context.getCVRQualifiedType(BaseType, 4951 CopyAssignOperator->getTypeQualifiers()), 4952 CK_UncheckedDerivedToBase, 4953 VK_LValue, &BasePath); 4954 To = Owned(ToE); 4955 4956 // Build the copy. 4957 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 4958 To.get(), From, 4959 /*CopyingBaseSubobject=*/true); 4960 if (Copy.isInvalid()) { 4961 Diag(CurrentLocation, diag::note_member_synthesized_at) 4962 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4963 CopyAssignOperator->setInvalidDecl(); 4964 return; 4965 } 4966 4967 // Success! Record the copy. 4968 Statements.push_back(Copy.takeAs<Expr>()); 4969 } 4970 4971 // \brief Reference to the __builtin_memcpy function. 4972 Expr *BuiltinMemCpyRef = 0; 4973 // \brief Reference to the __builtin_objc_memmove_collectable function. 4974 Expr *CollectableMemCpyRef = 0; 4975 4976 // Assign non-static members. 4977 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4978 FieldEnd = ClassDecl->field_end(); 4979 Field != FieldEnd; ++Field) { 4980 // Check for members of reference type; we can't copy those. 4981 if (Field->getType()->isReferenceType()) { 4982 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4983 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 4984 Diag(Field->getLocation(), diag::note_declared_at); 4985 Diag(CurrentLocation, diag::note_member_synthesized_at) 4986 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4987 Invalid = true; 4988 continue; 4989 } 4990 4991 // Check for members of const-qualified, non-class type. 4992 QualType BaseType = Context.getBaseElementType(Field->getType()); 4993 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 4994 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4995 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 4996 Diag(Field->getLocation(), diag::note_declared_at); 4997 Diag(CurrentLocation, diag::note_member_synthesized_at) 4998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4999 Invalid = true; 5000 continue; 5001 } 5002 5003 QualType FieldType = Field->getType().getNonReferenceType(); 5004 if (FieldType->isIncompleteArrayType()) { 5005 assert(ClassDecl->hasFlexibleArrayMember() && 5006 "Incomplete array type is not valid"); 5007 continue; 5008 } 5009 5010 // Build references to the field in the object we're copying from and to. 5011 CXXScopeSpec SS; // Intentionally empty 5012 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 5013 LookupMemberName); 5014 MemberLookup.addDecl(*Field); 5015 MemberLookup.resolveKind(); 5016 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 5017 Loc, /*IsArrow=*/false, 5018 SS, 0, MemberLookup, 0); 5019 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 5020 Loc, /*IsArrow=*/true, 5021 SS, 0, MemberLookup, 0); 5022 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 5023 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 5024 5025 // If the field should be copied with __builtin_memcpy rather than via 5026 // explicit assignments, do so. This optimization only applies for arrays 5027 // of scalars and arrays of class type with trivial copy-assignment 5028 // operators. 5029 if (FieldType->isArrayType() && 5030 (!BaseType->isRecordType() || 5031 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 5032 ->hasTrivialCopyAssignment())) { 5033 // Compute the size of the memory buffer to be copied. 5034 QualType SizeType = Context.getSizeType(); 5035 llvm::APInt Size(Context.getTypeSize(SizeType), 5036 Context.getTypeSizeInChars(BaseType).getQuantity()); 5037 for (const ConstantArrayType *Array 5038 = Context.getAsConstantArrayType(FieldType); 5039 Array; 5040 Array = Context.getAsConstantArrayType(Array->getElementType())) { 5041 llvm::APInt ArraySize 5042 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 5043 Size *= ArraySize; 5044 } 5045 5046 // Take the address of the field references for "from" and "to". 5047 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 5048 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 5049 5050 bool NeedsCollectableMemCpy = 5051 (BaseType->isRecordType() && 5052 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 5053 5054 if (NeedsCollectableMemCpy) { 5055 if (!CollectableMemCpyRef) { 5056 // Create a reference to the __builtin_objc_memmove_collectable function. 5057 LookupResult R(*this, 5058 &Context.Idents.get("__builtin_objc_memmove_collectable"), 5059 Loc, LookupOrdinaryName); 5060 LookupName(R, TUScope, true); 5061 5062 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 5063 if (!CollectableMemCpy) { 5064 // Something went horribly wrong earlier, and we will have 5065 // complained about it. 5066 Invalid = true; 5067 continue; 5068 } 5069 5070 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 5071 CollectableMemCpy->getType(), 5072 VK_LValue, Loc, 0).take(); 5073 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 5074 } 5075 } 5076 // Create a reference to the __builtin_memcpy builtin function. 5077 else if (!BuiltinMemCpyRef) { 5078 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 5079 LookupOrdinaryName); 5080 LookupName(R, TUScope, true); 5081 5082 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 5083 if (!BuiltinMemCpy) { 5084 // Something went horribly wrong earlier, and we will have complained 5085 // about it. 5086 Invalid = true; 5087 continue; 5088 } 5089 5090 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 5091 BuiltinMemCpy->getType(), 5092 VK_LValue, Loc, 0).take(); 5093 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 5094 } 5095 5096 ASTOwningVector<Expr*> CallArgs(*this); 5097 CallArgs.push_back(To.takeAs<Expr>()); 5098 CallArgs.push_back(From.takeAs<Expr>()); 5099 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 5100 ExprResult Call = ExprError(); 5101 if (NeedsCollectableMemCpy) 5102 Call = ActOnCallExpr(/*Scope=*/0, 5103 CollectableMemCpyRef, 5104 Loc, move_arg(CallArgs), 5105 Loc); 5106 else 5107 Call = ActOnCallExpr(/*Scope=*/0, 5108 BuiltinMemCpyRef, 5109 Loc, move_arg(CallArgs), 5110 Loc); 5111 5112 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 5113 Statements.push_back(Call.takeAs<Expr>()); 5114 continue; 5115 } 5116 5117 // Build the copy of this field. 5118 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 5119 To.get(), From.get(), 5120 /*CopyingBaseSubobject=*/false); 5121 if (Copy.isInvalid()) { 5122 Diag(CurrentLocation, diag::note_member_synthesized_at) 5123 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5124 CopyAssignOperator->setInvalidDecl(); 5125 return; 5126 } 5127 5128 // Success! Record the copy. 5129 Statements.push_back(Copy.takeAs<Stmt>()); 5130 } 5131 5132 if (!Invalid) { 5133 // Add a "return *this;" 5134 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5135 5136 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 5137 if (Return.isInvalid()) 5138 Invalid = true; 5139 else { 5140 Statements.push_back(Return.takeAs<Stmt>()); 5141 5142 if (Trap.hasErrorOccurred()) { 5143 Diag(CurrentLocation, diag::note_member_synthesized_at) 5144 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5145 Invalid = true; 5146 } 5147 } 5148 } 5149 5150 if (Invalid) { 5151 CopyAssignOperator->setInvalidDecl(); 5152 return; 5153 } 5154 5155 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 5156 /*isStmtExpr=*/false); 5157 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 5158 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 5159} 5160 5161CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 5162 CXXRecordDecl *ClassDecl) { 5163 // C++ [class.copy]p4: 5164 // If the class definition does not explicitly declare a copy 5165 // constructor, one is declared implicitly. 5166 5167 // C++ [class.copy]p5: 5168 // The implicitly-declared copy constructor for a class X will 5169 // have the form 5170 // 5171 // X::X(const X&) 5172 // 5173 // if 5174 bool HasConstCopyConstructor = true; 5175 5176 // -- each direct or virtual base class B of X has a copy 5177 // constructor whose first parameter is of type const B& or 5178 // const volatile B&, and 5179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5180 BaseEnd = ClassDecl->bases_end(); 5181 HasConstCopyConstructor && Base != BaseEnd; 5182 ++Base) { 5183 // Virtual bases are handled below. 5184 if (Base->isVirtual()) 5185 continue; 5186 5187 CXXRecordDecl *BaseClassDecl 5188 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5189 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5190 DeclareImplicitCopyConstructor(BaseClassDecl); 5191 5192 HasConstCopyConstructor 5193 = BaseClassDecl->hasConstCopyConstructor(Context); 5194 } 5195 5196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5197 BaseEnd = ClassDecl->vbases_end(); 5198 HasConstCopyConstructor && Base != BaseEnd; 5199 ++Base) { 5200 CXXRecordDecl *BaseClassDecl 5201 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5202 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5203 DeclareImplicitCopyConstructor(BaseClassDecl); 5204 5205 HasConstCopyConstructor 5206 = BaseClassDecl->hasConstCopyConstructor(Context); 5207 } 5208 5209 // -- for all the nonstatic data members of X that are of a 5210 // class type M (or array thereof), each such class type 5211 // has a copy constructor whose first parameter is of type 5212 // const M& or const volatile M&. 5213 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5214 FieldEnd = ClassDecl->field_end(); 5215 HasConstCopyConstructor && Field != FieldEnd; 5216 ++Field) { 5217 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5218 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5219 CXXRecordDecl *FieldClassDecl 5220 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5221 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5222 DeclareImplicitCopyConstructor(FieldClassDecl); 5223 5224 HasConstCopyConstructor 5225 = FieldClassDecl->hasConstCopyConstructor(Context); 5226 } 5227 } 5228 5229 // Otherwise, the implicitly declared copy constructor will have 5230 // the form 5231 // 5232 // X::X(X&) 5233 QualType ClassType = Context.getTypeDeclType(ClassDecl); 5234 QualType ArgType = ClassType; 5235 if (HasConstCopyConstructor) 5236 ArgType = ArgType.withConst(); 5237 ArgType = Context.getLValueReferenceType(ArgType); 5238 5239 // C++ [except.spec]p14: 5240 // An implicitly declared special member function (Clause 12) shall have an 5241 // exception-specification. [...] 5242 ImplicitExceptionSpecification ExceptSpec(Context); 5243 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 5244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5245 BaseEnd = ClassDecl->bases_end(); 5246 Base != BaseEnd; 5247 ++Base) { 5248 // Virtual bases are handled below. 5249 if (Base->isVirtual()) 5250 continue; 5251 5252 CXXRecordDecl *BaseClassDecl 5253 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5254 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5255 DeclareImplicitCopyConstructor(BaseClassDecl); 5256 5257 if (CXXConstructorDecl *CopyConstructor 5258 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5259 ExceptSpec.CalledDecl(CopyConstructor); 5260 } 5261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5262 BaseEnd = ClassDecl->vbases_end(); 5263 Base != BaseEnd; 5264 ++Base) { 5265 CXXRecordDecl *BaseClassDecl 5266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5267 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5268 DeclareImplicitCopyConstructor(BaseClassDecl); 5269 5270 if (CXXConstructorDecl *CopyConstructor 5271 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5272 ExceptSpec.CalledDecl(CopyConstructor); 5273 } 5274 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5275 FieldEnd = ClassDecl->field_end(); 5276 Field != FieldEnd; 5277 ++Field) { 5278 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5279 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5280 CXXRecordDecl *FieldClassDecl 5281 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5282 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5283 DeclareImplicitCopyConstructor(FieldClassDecl); 5284 5285 if (CXXConstructorDecl *CopyConstructor 5286 = FieldClassDecl->getCopyConstructor(Context, Quals)) 5287 ExceptSpec.CalledDecl(CopyConstructor); 5288 } 5289 } 5290 5291 // An implicitly-declared copy constructor is an inline public 5292 // member of its class. 5293 FunctionProtoType::ExtProtoInfo EPI; 5294 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification(); 5295 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification(); 5296 EPI.NumExceptions = ExceptSpec.size(); 5297 EPI.Exceptions = ExceptSpec.data(); 5298 DeclarationName Name 5299 = Context.DeclarationNames.getCXXConstructorName( 5300 Context.getCanonicalType(ClassType)); 5301 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 5302 CXXConstructorDecl *CopyConstructor 5303 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo, 5304 Context.getFunctionType(Context.VoidTy, 5305 &ArgType, 1, EPI), 5306 /*TInfo=*/0, 5307 /*isExplicit=*/false, 5308 /*isInline=*/true, 5309 /*isImplicitlyDeclared=*/true); 5310 CopyConstructor->setAccess(AS_public); 5311 CopyConstructor->setImplicit(); 5312 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 5313 5314 // Note that we have declared this constructor. 5315 ++ASTContext::NumImplicitCopyConstructorsDeclared; 5316 5317 // Add the parameter to the constructor. 5318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 5319 ClassDecl->getLocation(), 5320 /*IdentifierInfo=*/0, 5321 ArgType, /*TInfo=*/0, 5322 SC_None, 5323 SC_None, 0); 5324 CopyConstructor->setParams(&FromParam, 1); 5325 if (Scope *S = getScopeForContext(ClassDecl)) 5326 PushOnScopeChains(CopyConstructor, S, false); 5327 ClassDecl->addDecl(CopyConstructor); 5328 5329 return CopyConstructor; 5330} 5331 5332void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5333 CXXConstructorDecl *CopyConstructor, 5334 unsigned TypeQuals) { 5335 assert((CopyConstructor->isImplicit() && 5336 CopyConstructor->isCopyConstructor(TypeQuals) && 5337 !CopyConstructor->isUsed(false)) && 5338 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 5339 5340 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 5341 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 5342 5343 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 5344 DiagnosticErrorTrap Trap(Diags); 5345 5346 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 5347 Trap.hasErrorOccurred()) { 5348 Diag(CurrentLocation, diag::note_member_synthesized_at) 5349 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 5350 CopyConstructor->setInvalidDecl(); 5351 } else { 5352 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 5353 CopyConstructor->getLocation(), 5354 MultiStmtArg(*this, 0, 0), 5355 /*isStmtExpr=*/false) 5356 .takeAs<Stmt>()); 5357 } 5358 5359 CopyConstructor->setUsed(); 5360} 5361 5362ExprResult 5363Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5364 CXXConstructorDecl *Constructor, 5365 MultiExprArg ExprArgs, 5366 bool RequiresZeroInit, 5367 unsigned ConstructKind, 5368 SourceRange ParenRange) { 5369 bool Elidable = false; 5370 5371 // C++0x [class.copy]p34: 5372 // When certain criteria are met, an implementation is allowed to 5373 // omit the copy/move construction of a class object, even if the 5374 // copy/move constructor and/or destructor for the object have 5375 // side effects. [...] 5376 // - when a temporary class object that has not been bound to a 5377 // reference (12.2) would be copied/moved to a class object 5378 // with the same cv-unqualified type, the copy/move operation 5379 // can be omitted by constructing the temporary object 5380 // directly into the target of the omitted copy/move 5381 if (ConstructKind == CXXConstructExpr::CK_Complete && 5382 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 5383 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 5384 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 5385 } 5386 5387 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 5388 Elidable, move(ExprArgs), RequiresZeroInit, 5389 ConstructKind, ParenRange); 5390} 5391 5392/// BuildCXXConstructExpr - Creates a complete call to a constructor, 5393/// including handling of its default argument expressions. 5394ExprResult 5395Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5396 CXXConstructorDecl *Constructor, bool Elidable, 5397 MultiExprArg ExprArgs, 5398 bool RequiresZeroInit, 5399 unsigned ConstructKind, 5400 SourceRange ParenRange) { 5401 unsigned NumExprs = ExprArgs.size(); 5402 Expr **Exprs = (Expr **)ExprArgs.release(); 5403 5404 MarkDeclarationReferenced(ConstructLoc, Constructor); 5405 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 5406 Constructor, Elidable, Exprs, NumExprs, 5407 RequiresZeroInit, 5408 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 5409 ParenRange)); 5410} 5411 5412bool Sema::InitializeVarWithConstructor(VarDecl *VD, 5413 CXXConstructorDecl *Constructor, 5414 MultiExprArg Exprs) { 5415 // FIXME: Provide the correct paren SourceRange when available. 5416 ExprResult TempResult = 5417 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 5418 move(Exprs), false, CXXConstructExpr::CK_Complete, 5419 SourceRange()); 5420 if (TempResult.isInvalid()) 5421 return true; 5422 5423 Expr *Temp = TempResult.takeAs<Expr>(); 5424 CheckImplicitConversions(Temp, VD->getLocation()); 5425 MarkDeclarationReferenced(VD->getLocation(), Constructor); 5426 Temp = MaybeCreateExprWithCleanups(Temp); 5427 VD->setInit(Temp); 5428 5429 return false; 5430} 5431 5432void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 5433 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 5434 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 5435 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) { 5436 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 5437 MarkDeclarationReferenced(VD->getLocation(), Destructor); 5438 CheckDestructorAccess(VD->getLocation(), Destructor, 5439 PDiag(diag::err_access_dtor_var) 5440 << VD->getDeclName() 5441 << VD->getType()); 5442 5443 // TODO: this should be re-enabled for static locals by !CXAAtExit 5444 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal()) 5445 Diag(VD->getLocation(), diag::warn_global_destructor); 5446 } 5447} 5448 5449/// AddCXXDirectInitializerToDecl - This action is called immediately after 5450/// ActOnDeclarator, when a C++ direct initializer is present. 5451/// e.g: "int x(1);" 5452void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 5453 SourceLocation LParenLoc, 5454 MultiExprArg Exprs, 5455 SourceLocation RParenLoc) { 5456 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 5457 5458 // If there is no declaration, there was an error parsing it. Just ignore 5459 // the initializer. 5460 if (RealDecl == 0) 5461 return; 5462 5463 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5464 if (!VDecl) { 5465 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5466 RealDecl->setInvalidDecl(); 5467 return; 5468 } 5469 5470 // We will represent direct-initialization similarly to copy-initialization: 5471 // int x(1); -as-> int x = 1; 5472 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 5473 // 5474 // Clients that want to distinguish between the two forms, can check for 5475 // direct initializer using VarDecl::hasCXXDirectInitializer(). 5476 // A major benefit is that clients that don't particularly care about which 5477 // exactly form was it (like the CodeGen) can handle both cases without 5478 // special case code. 5479 5480 // C++ 8.5p11: 5481 // The form of initialization (using parentheses or '=') is generally 5482 // insignificant, but does matter when the entity being initialized has a 5483 // class type. 5484 5485 if (!VDecl->getType()->isDependentType() && 5486 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 5487 diag::err_typecheck_decl_incomplete_type)) { 5488 VDecl->setInvalidDecl(); 5489 return; 5490 } 5491 5492 // The variable can not have an abstract class type. 5493 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5494 diag::err_abstract_type_in_decl, 5495 AbstractVariableType)) 5496 VDecl->setInvalidDecl(); 5497 5498 const VarDecl *Def; 5499 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5500 Diag(VDecl->getLocation(), diag::err_redefinition) 5501 << VDecl->getDeclName(); 5502 Diag(Def->getLocation(), diag::note_previous_definition); 5503 VDecl->setInvalidDecl(); 5504 return; 5505 } 5506 5507 // C++ [class.static.data]p4 5508 // If a static data member is of const integral or const 5509 // enumeration type, its declaration in the class definition can 5510 // specify a constant-initializer which shall be an integral 5511 // constant expression (5.19). In that case, the member can appear 5512 // in integral constant expressions. The member shall still be 5513 // defined in a namespace scope if it is used in the program and the 5514 // namespace scope definition shall not contain an initializer. 5515 // 5516 // We already performed a redefinition check above, but for static 5517 // data members we also need to check whether there was an in-class 5518 // declaration with an initializer. 5519 const VarDecl* PrevInit = 0; 5520 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5521 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 5522 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5523 return; 5524 } 5525 5526 bool IsDependent = false; 5527 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 5528 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 5529 VDecl->setInvalidDecl(); 5530 return; 5531 } 5532 5533 if (Exprs.get()[I]->isTypeDependent()) 5534 IsDependent = true; 5535 } 5536 5537 // If either the declaration has a dependent type or if any of the 5538 // expressions is type-dependent, we represent the initialization 5539 // via a ParenListExpr for later use during template instantiation. 5540 if (VDecl->getType()->isDependentType() || IsDependent) { 5541 // Let clients know that initialization was done with a direct initializer. 5542 VDecl->setCXXDirectInitializer(true); 5543 5544 // Store the initialization expressions as a ParenListExpr. 5545 unsigned NumExprs = Exprs.size(); 5546 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 5547 (Expr **)Exprs.release(), 5548 NumExprs, RParenLoc)); 5549 return; 5550 } 5551 5552 // Capture the variable that is being initialized and the style of 5553 // initialization. 5554 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5555 5556 // FIXME: Poor source location information. 5557 InitializationKind Kind 5558 = InitializationKind::CreateDirect(VDecl->getLocation(), 5559 LParenLoc, RParenLoc); 5560 5561 InitializationSequence InitSeq(*this, Entity, Kind, 5562 Exprs.get(), Exprs.size()); 5563 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 5564 if (Result.isInvalid()) { 5565 VDecl->setInvalidDecl(); 5566 return; 5567 } 5568 5569 CheckImplicitConversions(Result.get(), LParenLoc); 5570 5571 Result = MaybeCreateExprWithCleanups(Result); 5572 VDecl->setInit(Result.takeAs<Expr>()); 5573 VDecl->setCXXDirectInitializer(true); 5574 5575 if (!VDecl->isInvalidDecl() && 5576 !VDecl->getDeclContext()->isDependentContext() && 5577 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() && 5578 !VDecl->getInit()->isConstantInitializer(Context, 5579 VDecl->getType()->isReferenceType())) 5580 Diag(VDecl->getLocation(), diag::warn_global_constructor) 5581 << VDecl->getInit()->getSourceRange(); 5582 5583 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 5584 FinalizeVarWithDestructor(VDecl, Record); 5585} 5586 5587/// \brief Given a constructor and the set of arguments provided for the 5588/// constructor, convert the arguments and add any required default arguments 5589/// to form a proper call to this constructor. 5590/// 5591/// \returns true if an error occurred, false otherwise. 5592bool 5593Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 5594 MultiExprArg ArgsPtr, 5595 SourceLocation Loc, 5596 ASTOwningVector<Expr*> &ConvertedArgs) { 5597 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 5598 unsigned NumArgs = ArgsPtr.size(); 5599 Expr **Args = (Expr **)ArgsPtr.get(); 5600 5601 const FunctionProtoType *Proto 5602 = Constructor->getType()->getAs<FunctionProtoType>(); 5603 assert(Proto && "Constructor without a prototype?"); 5604 unsigned NumArgsInProto = Proto->getNumArgs(); 5605 5606 // If too few arguments are available, we'll fill in the rest with defaults. 5607 if (NumArgs < NumArgsInProto) 5608 ConvertedArgs.reserve(NumArgsInProto); 5609 else 5610 ConvertedArgs.reserve(NumArgs); 5611 5612 VariadicCallType CallType = 5613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5614 llvm::SmallVector<Expr *, 8> AllArgs; 5615 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 5616 Proto, 0, Args, NumArgs, AllArgs, 5617 CallType); 5618 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 5619 ConvertedArgs.push_back(AllArgs[i]); 5620 return Invalid; 5621} 5622 5623static inline bool 5624CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 5625 const FunctionDecl *FnDecl) { 5626 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 5627 if (isa<NamespaceDecl>(DC)) { 5628 return SemaRef.Diag(FnDecl->getLocation(), 5629 diag::err_operator_new_delete_declared_in_namespace) 5630 << FnDecl->getDeclName(); 5631 } 5632 5633 if (isa<TranslationUnitDecl>(DC) && 5634 FnDecl->getStorageClass() == SC_Static) { 5635 return SemaRef.Diag(FnDecl->getLocation(), 5636 diag::err_operator_new_delete_declared_static) 5637 << FnDecl->getDeclName(); 5638 } 5639 5640 return false; 5641} 5642 5643static inline bool 5644CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 5645 CanQualType ExpectedResultType, 5646 CanQualType ExpectedFirstParamType, 5647 unsigned DependentParamTypeDiag, 5648 unsigned InvalidParamTypeDiag) { 5649 QualType ResultType = 5650 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 5651 5652 // Check that the result type is not dependent. 5653 if (ResultType->isDependentType()) 5654 return SemaRef.Diag(FnDecl->getLocation(), 5655 diag::err_operator_new_delete_dependent_result_type) 5656 << FnDecl->getDeclName() << ExpectedResultType; 5657 5658 // Check that the result type is what we expect. 5659 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 5660 return SemaRef.Diag(FnDecl->getLocation(), 5661 diag::err_operator_new_delete_invalid_result_type) 5662 << FnDecl->getDeclName() << ExpectedResultType; 5663 5664 // A function template must have at least 2 parameters. 5665 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 5666 return SemaRef.Diag(FnDecl->getLocation(), 5667 diag::err_operator_new_delete_template_too_few_parameters) 5668 << FnDecl->getDeclName(); 5669 5670 // The function decl must have at least 1 parameter. 5671 if (FnDecl->getNumParams() == 0) 5672 return SemaRef.Diag(FnDecl->getLocation(), 5673 diag::err_operator_new_delete_too_few_parameters) 5674 << FnDecl->getDeclName(); 5675 5676 // Check the the first parameter type is not dependent. 5677 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 5678 if (FirstParamType->isDependentType()) 5679 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 5680 << FnDecl->getDeclName() << ExpectedFirstParamType; 5681 5682 // Check that the first parameter type is what we expect. 5683 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 5684 ExpectedFirstParamType) 5685 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 5686 << FnDecl->getDeclName() << ExpectedFirstParamType; 5687 5688 return false; 5689} 5690 5691static bool 5692CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5693 // C++ [basic.stc.dynamic.allocation]p1: 5694 // A program is ill-formed if an allocation function is declared in a 5695 // namespace scope other than global scope or declared static in global 5696 // scope. 5697 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5698 return true; 5699 5700 CanQualType SizeTy = 5701 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 5702 5703 // C++ [basic.stc.dynamic.allocation]p1: 5704 // The return type shall be void*. The first parameter shall have type 5705 // std::size_t. 5706 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 5707 SizeTy, 5708 diag::err_operator_new_dependent_param_type, 5709 diag::err_operator_new_param_type)) 5710 return true; 5711 5712 // C++ [basic.stc.dynamic.allocation]p1: 5713 // The first parameter shall not have an associated default argument. 5714 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 5715 return SemaRef.Diag(FnDecl->getLocation(), 5716 diag::err_operator_new_default_arg) 5717 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 5718 5719 return false; 5720} 5721 5722static bool 5723CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5724 // C++ [basic.stc.dynamic.deallocation]p1: 5725 // A program is ill-formed if deallocation functions are declared in a 5726 // namespace scope other than global scope or declared static in global 5727 // scope. 5728 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5729 return true; 5730 5731 // C++ [basic.stc.dynamic.deallocation]p2: 5732 // Each deallocation function shall return void and its first parameter 5733 // shall be void*. 5734 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 5735 SemaRef.Context.VoidPtrTy, 5736 diag::err_operator_delete_dependent_param_type, 5737 diag::err_operator_delete_param_type)) 5738 return true; 5739 5740 return false; 5741} 5742 5743/// CheckOverloadedOperatorDeclaration - Check whether the declaration 5744/// of this overloaded operator is well-formed. If so, returns false; 5745/// otherwise, emits appropriate diagnostics and returns true. 5746bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 5747 assert(FnDecl && FnDecl->isOverloadedOperator() && 5748 "Expected an overloaded operator declaration"); 5749 5750 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 5751 5752 // C++ [over.oper]p5: 5753 // The allocation and deallocation functions, operator new, 5754 // operator new[], operator delete and operator delete[], are 5755 // described completely in 3.7.3. The attributes and restrictions 5756 // found in the rest of this subclause do not apply to them unless 5757 // explicitly stated in 3.7.3. 5758 if (Op == OO_Delete || Op == OO_Array_Delete) 5759 return CheckOperatorDeleteDeclaration(*this, FnDecl); 5760 5761 if (Op == OO_New || Op == OO_Array_New) 5762 return CheckOperatorNewDeclaration(*this, FnDecl); 5763 5764 // C++ [over.oper]p6: 5765 // An operator function shall either be a non-static member 5766 // function or be a non-member function and have at least one 5767 // parameter whose type is a class, a reference to a class, an 5768 // enumeration, or a reference to an enumeration. 5769 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 5770 if (MethodDecl->isStatic()) 5771 return Diag(FnDecl->getLocation(), 5772 diag::err_operator_overload_static) << FnDecl->getDeclName(); 5773 } else { 5774 bool ClassOrEnumParam = false; 5775 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 5776 ParamEnd = FnDecl->param_end(); 5777 Param != ParamEnd; ++Param) { 5778 QualType ParamType = (*Param)->getType().getNonReferenceType(); 5779 if (ParamType->isDependentType() || ParamType->isRecordType() || 5780 ParamType->isEnumeralType()) { 5781 ClassOrEnumParam = true; 5782 break; 5783 } 5784 } 5785 5786 if (!ClassOrEnumParam) 5787 return Diag(FnDecl->getLocation(), 5788 diag::err_operator_overload_needs_class_or_enum) 5789 << FnDecl->getDeclName(); 5790 } 5791 5792 // C++ [over.oper]p8: 5793 // An operator function cannot have default arguments (8.3.6), 5794 // except where explicitly stated below. 5795 // 5796 // Only the function-call operator allows default arguments 5797 // (C++ [over.call]p1). 5798 if (Op != OO_Call) { 5799 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5800 Param != FnDecl->param_end(); ++Param) { 5801 if ((*Param)->hasDefaultArg()) 5802 return Diag((*Param)->getLocation(), 5803 diag::err_operator_overload_default_arg) 5804 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 5805 } 5806 } 5807 5808 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 5809 { false, false, false } 5810#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5811 , { Unary, Binary, MemberOnly } 5812#include "clang/Basic/OperatorKinds.def" 5813 }; 5814 5815 bool CanBeUnaryOperator = OperatorUses[Op][0]; 5816 bool CanBeBinaryOperator = OperatorUses[Op][1]; 5817 bool MustBeMemberOperator = OperatorUses[Op][2]; 5818 5819 // C++ [over.oper]p8: 5820 // [...] Operator functions cannot have more or fewer parameters 5821 // than the number required for the corresponding operator, as 5822 // described in the rest of this subclause. 5823 unsigned NumParams = FnDecl->getNumParams() 5824 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 5825 if (Op != OO_Call && 5826 ((NumParams == 1 && !CanBeUnaryOperator) || 5827 (NumParams == 2 && !CanBeBinaryOperator) || 5828 (NumParams < 1) || (NumParams > 2))) { 5829 // We have the wrong number of parameters. 5830 unsigned ErrorKind; 5831 if (CanBeUnaryOperator && CanBeBinaryOperator) { 5832 ErrorKind = 2; // 2 -> unary or binary. 5833 } else if (CanBeUnaryOperator) { 5834 ErrorKind = 0; // 0 -> unary 5835 } else { 5836 assert(CanBeBinaryOperator && 5837 "All non-call overloaded operators are unary or binary!"); 5838 ErrorKind = 1; // 1 -> binary 5839 } 5840 5841 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 5842 << FnDecl->getDeclName() << NumParams << ErrorKind; 5843 } 5844 5845 // Overloaded operators other than operator() cannot be variadic. 5846 if (Op != OO_Call && 5847 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 5848 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 5849 << FnDecl->getDeclName(); 5850 } 5851 5852 // Some operators must be non-static member functions. 5853 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 5854 return Diag(FnDecl->getLocation(), 5855 diag::err_operator_overload_must_be_member) 5856 << FnDecl->getDeclName(); 5857 } 5858 5859 // C++ [over.inc]p1: 5860 // The user-defined function called operator++ implements the 5861 // prefix and postfix ++ operator. If this function is a member 5862 // function with no parameters, or a non-member function with one 5863 // parameter of class or enumeration type, it defines the prefix 5864 // increment operator ++ for objects of that type. If the function 5865 // is a member function with one parameter (which shall be of type 5866 // int) or a non-member function with two parameters (the second 5867 // of which shall be of type int), it defines the postfix 5868 // increment operator ++ for objects of that type. 5869 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 5870 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 5871 bool ParamIsInt = false; 5872 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 5873 ParamIsInt = BT->getKind() == BuiltinType::Int; 5874 5875 if (!ParamIsInt) 5876 return Diag(LastParam->getLocation(), 5877 diag::err_operator_overload_post_incdec_must_be_int) 5878 << LastParam->getType() << (Op == OO_MinusMinus); 5879 } 5880 5881 return false; 5882} 5883 5884/// CheckLiteralOperatorDeclaration - Check whether the declaration 5885/// of this literal operator function is well-formed. If so, returns 5886/// false; otherwise, emits appropriate diagnostics and returns true. 5887bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 5888 DeclContext *DC = FnDecl->getDeclContext(); 5889 Decl::Kind Kind = DC->getDeclKind(); 5890 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 5891 Kind != Decl::LinkageSpec) { 5892 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 5893 << FnDecl->getDeclName(); 5894 return true; 5895 } 5896 5897 bool Valid = false; 5898 5899 // template <char...> type operator "" name() is the only valid template 5900 // signature, and the only valid signature with no parameters. 5901 if (FnDecl->param_size() == 0) { 5902 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 5903 // Must have only one template parameter 5904 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 5905 if (Params->size() == 1) { 5906 NonTypeTemplateParmDecl *PmDecl = 5907 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 5908 5909 // The template parameter must be a char parameter pack. 5910 // FIXME: This test will always fail because non-type parameter packs 5911 // have not been implemented. 5912 if (PmDecl && PmDecl->isTemplateParameterPack() && 5913 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 5914 Valid = true; 5915 } 5916 } 5917 } else { 5918 // Check the first parameter 5919 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5920 5921 QualType T = (*Param)->getType(); 5922 5923 // unsigned long long int, long double, and any character type are allowed 5924 // as the only parameters. 5925 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 5926 Context.hasSameType(T, Context.LongDoubleTy) || 5927 Context.hasSameType(T, Context.CharTy) || 5928 Context.hasSameType(T, Context.WCharTy) || 5929 Context.hasSameType(T, Context.Char16Ty) || 5930 Context.hasSameType(T, Context.Char32Ty)) { 5931 if (++Param == FnDecl->param_end()) 5932 Valid = true; 5933 goto FinishedParams; 5934 } 5935 5936 // Otherwise it must be a pointer to const; let's strip those qualifiers. 5937 const PointerType *PT = T->getAs<PointerType>(); 5938 if (!PT) 5939 goto FinishedParams; 5940 T = PT->getPointeeType(); 5941 if (!T.isConstQualified()) 5942 goto FinishedParams; 5943 T = T.getUnqualifiedType(); 5944 5945 // Move on to the second parameter; 5946 ++Param; 5947 5948 // If there is no second parameter, the first must be a const char * 5949 if (Param == FnDecl->param_end()) { 5950 if (Context.hasSameType(T, Context.CharTy)) 5951 Valid = true; 5952 goto FinishedParams; 5953 } 5954 5955 // const char *, const wchar_t*, const char16_t*, and const char32_t* 5956 // are allowed as the first parameter to a two-parameter function 5957 if (!(Context.hasSameType(T, Context.CharTy) || 5958 Context.hasSameType(T, Context.WCharTy) || 5959 Context.hasSameType(T, Context.Char16Ty) || 5960 Context.hasSameType(T, Context.Char32Ty))) 5961 goto FinishedParams; 5962 5963 // The second and final parameter must be an std::size_t 5964 T = (*Param)->getType().getUnqualifiedType(); 5965 if (Context.hasSameType(T, Context.getSizeType()) && 5966 ++Param == FnDecl->param_end()) 5967 Valid = true; 5968 } 5969 5970 // FIXME: This diagnostic is absolutely terrible. 5971FinishedParams: 5972 if (!Valid) { 5973 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 5974 << FnDecl->getDeclName(); 5975 return true; 5976 } 5977 5978 return false; 5979} 5980 5981/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5982/// linkage specification, including the language and (if present) 5983/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 5984/// the location of the language string literal, which is provided 5985/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 5986/// the '{' brace. Otherwise, this linkage specification does not 5987/// have any braces. 5988Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 5989 SourceLocation LangLoc, 5990 llvm::StringRef Lang, 5991 SourceLocation LBraceLoc) { 5992 LinkageSpecDecl::LanguageIDs Language; 5993 if (Lang == "\"C\"") 5994 Language = LinkageSpecDecl::lang_c; 5995 else if (Lang == "\"C++\"") 5996 Language = LinkageSpecDecl::lang_cxx; 5997 else { 5998 Diag(LangLoc, diag::err_bad_language); 5999 return 0; 6000 } 6001 6002 // FIXME: Add all the various semantics of linkage specifications 6003 6004 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 6005 LangLoc, Language, 6006 LBraceLoc.isValid()); 6007 CurContext->addDecl(D); 6008 PushDeclContext(S, D); 6009 return D; 6010} 6011 6012/// ActOnFinishLinkageSpecification - Complete the definition of 6013/// the C++ linkage specification LinkageSpec. If RBraceLoc is 6014/// valid, it's the position of the closing '}' brace in a linkage 6015/// specification that uses braces. 6016Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 6017 Decl *LinkageSpec, 6018 SourceLocation RBraceLoc) { 6019 if (LinkageSpec) 6020 PopDeclContext(); 6021 return LinkageSpec; 6022} 6023 6024/// \brief Perform semantic analysis for the variable declaration that 6025/// occurs within a C++ catch clause, returning the newly-created 6026/// variable. 6027VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 6028 TypeSourceInfo *TInfo, 6029 IdentifierInfo *Name, 6030 SourceLocation Loc) { 6031 bool Invalid = false; 6032 QualType ExDeclType = TInfo->getType(); 6033 6034 // Arrays and functions decay. 6035 if (ExDeclType->isArrayType()) 6036 ExDeclType = Context.getArrayDecayedType(ExDeclType); 6037 else if (ExDeclType->isFunctionType()) 6038 ExDeclType = Context.getPointerType(ExDeclType); 6039 6040 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 6041 // The exception-declaration shall not denote a pointer or reference to an 6042 // incomplete type, other than [cv] void*. 6043 // N2844 forbids rvalue references. 6044 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 6045 Diag(Loc, diag::err_catch_rvalue_ref); 6046 Invalid = true; 6047 } 6048 6049 // GCC allows catching pointers and references to incomplete types 6050 // as an extension; so do we, but we warn by default. 6051 6052 QualType BaseType = ExDeclType; 6053 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 6054 unsigned DK = diag::err_catch_incomplete; 6055 bool IncompleteCatchIsInvalid = true; 6056 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 6057 BaseType = Ptr->getPointeeType(); 6058 Mode = 1; 6059 DK = diag::ext_catch_incomplete_ptr; 6060 IncompleteCatchIsInvalid = false; 6061 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 6062 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 6063 BaseType = Ref->getPointeeType(); 6064 Mode = 2; 6065 DK = diag::ext_catch_incomplete_ref; 6066 IncompleteCatchIsInvalid = false; 6067 } 6068 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 6069 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 6070 IncompleteCatchIsInvalid) 6071 Invalid = true; 6072 6073 if (!Invalid && !ExDeclType->isDependentType() && 6074 RequireNonAbstractType(Loc, ExDeclType, 6075 diag::err_abstract_type_in_decl, 6076 AbstractVariableType)) 6077 Invalid = true; 6078 6079 // Only the non-fragile NeXT runtime currently supports C++ catches 6080 // of ObjC types, and no runtime supports catching ObjC types by value. 6081 if (!Invalid && getLangOptions().ObjC1) { 6082 QualType T = ExDeclType; 6083 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 6084 T = RT->getPointeeType(); 6085 6086 if (T->isObjCObjectType()) { 6087 Diag(Loc, diag::err_objc_object_catch); 6088 Invalid = true; 6089 } else if (T->isObjCObjectPointerType()) { 6090 if (!getLangOptions().NeXTRuntime) { 6091 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu); 6092 Invalid = true; 6093 } else if (!getLangOptions().ObjCNonFragileABI) { 6094 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 6095 Invalid = true; 6096 } 6097 } 6098 } 6099 6100 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 6101 Name, ExDeclType, TInfo, SC_None, 6102 SC_None); 6103 ExDecl->setExceptionVariable(true); 6104 6105 if (!Invalid) { 6106 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 6107 // C++ [except.handle]p16: 6108 // The object declared in an exception-declaration or, if the 6109 // exception-declaration does not specify a name, a temporary (12.2) is 6110 // copy-initialized (8.5) from the exception object. [...] 6111 // The object is destroyed when the handler exits, after the destruction 6112 // of any automatic objects initialized within the handler. 6113 // 6114 // We just pretend to initialize the object with itself, then make sure 6115 // it can be destroyed later. 6116 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 6117 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 6118 Loc, ExDeclType, VK_LValue, 0); 6119 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 6120 SourceLocation()); 6121 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 6122 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6123 MultiExprArg(*this, &ExDeclRef, 1)); 6124 if (Result.isInvalid()) 6125 Invalid = true; 6126 else 6127 FinalizeVarWithDestructor(ExDecl, RecordTy); 6128 } 6129 } 6130 6131 if (Invalid) 6132 ExDecl->setInvalidDecl(); 6133 6134 return ExDecl; 6135} 6136 6137/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 6138/// handler. 6139Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 6140 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6141 QualType ExDeclType = TInfo->getType(); 6142 6143 bool Invalid = D.isInvalidType(); 6144 IdentifierInfo *II = D.getIdentifier(); 6145 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 6146 LookupOrdinaryName, 6147 ForRedeclaration)) { 6148 // The scope should be freshly made just for us. There is just no way 6149 // it contains any previous declaration. 6150 assert(!S->isDeclScope(PrevDecl)); 6151 if (PrevDecl->isTemplateParameter()) { 6152 // Maybe we will complain about the shadowed template parameter. 6153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6154 } 6155 } 6156 6157 if (D.getCXXScopeSpec().isSet() && !Invalid) { 6158 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 6159 << D.getCXXScopeSpec().getRange(); 6160 Invalid = true; 6161 } 6162 6163 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 6164 D.getIdentifier(), 6165 D.getIdentifierLoc()); 6166 6167 if (Invalid) 6168 ExDecl->setInvalidDecl(); 6169 6170 // Add the exception declaration into this scope. 6171 if (II) 6172 PushOnScopeChains(ExDecl, S); 6173 else 6174 CurContext->addDecl(ExDecl); 6175 6176 ProcessDeclAttributes(S, ExDecl, D); 6177 return ExDecl; 6178} 6179 6180Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 6181 Expr *AssertExpr, 6182 Expr *AssertMessageExpr_) { 6183 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 6184 6185 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 6186 llvm::APSInt Value(32); 6187 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 6188 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 6189 AssertExpr->getSourceRange(); 6190 return 0; 6191 } 6192 6193 if (Value == 0) { 6194 Diag(AssertLoc, diag::err_static_assert_failed) 6195 << AssertMessage->getString() << AssertExpr->getSourceRange(); 6196 } 6197 } 6198 6199 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 6200 return 0; 6201 6202 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 6203 AssertExpr, AssertMessage); 6204 6205 CurContext->addDecl(Decl); 6206 return Decl; 6207} 6208 6209/// \brief Perform semantic analysis of the given friend type declaration. 6210/// 6211/// \returns A friend declaration that. 6212FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 6213 TypeSourceInfo *TSInfo) { 6214 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 6215 6216 QualType T = TSInfo->getType(); 6217 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 6218 6219 if (!getLangOptions().CPlusPlus0x) { 6220 // C++03 [class.friend]p2: 6221 // An elaborated-type-specifier shall be used in a friend declaration 6222 // for a class.* 6223 // 6224 // * The class-key of the elaborated-type-specifier is required. 6225 if (!ActiveTemplateInstantiations.empty()) { 6226 // Do not complain about the form of friend template types during 6227 // template instantiation; we will already have complained when the 6228 // template was declared. 6229 } else if (!T->isElaboratedTypeSpecifier()) { 6230 // If we evaluated the type to a record type, suggest putting 6231 // a tag in front. 6232 if (const RecordType *RT = T->getAs<RecordType>()) { 6233 RecordDecl *RD = RT->getDecl(); 6234 6235 std::string InsertionText = std::string(" ") + RD->getKindName(); 6236 6237 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 6238 << (unsigned) RD->getTagKind() 6239 << T 6240 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 6241 InsertionText); 6242 } else { 6243 Diag(FriendLoc, diag::ext_nonclass_type_friend) 6244 << T 6245 << SourceRange(FriendLoc, TypeRange.getEnd()); 6246 } 6247 } else if (T->getAs<EnumType>()) { 6248 Diag(FriendLoc, diag::ext_enum_friend) 6249 << T 6250 << SourceRange(FriendLoc, TypeRange.getEnd()); 6251 } 6252 } 6253 6254 // C++0x [class.friend]p3: 6255 // If the type specifier in a friend declaration designates a (possibly 6256 // cv-qualified) class type, that class is declared as a friend; otherwise, 6257 // the friend declaration is ignored. 6258 6259 // FIXME: C++0x has some syntactic restrictions on friend type declarations 6260 // in [class.friend]p3 that we do not implement. 6261 6262 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 6263} 6264 6265/// Handle a friend tag declaration where the scope specifier was 6266/// templated. 6267Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 6268 unsigned TagSpec, SourceLocation TagLoc, 6269 CXXScopeSpec &SS, 6270 IdentifierInfo *Name, SourceLocation NameLoc, 6271 AttributeList *Attr, 6272 MultiTemplateParamsArg TempParamLists) { 6273 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6274 6275 bool isExplicitSpecialization = false; 6276 unsigned NumMatchedTemplateParamLists = TempParamLists.size(); 6277 bool Invalid = false; 6278 6279 if (TemplateParameterList *TemplateParams 6280 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS, 6281 TempParamLists.get(), 6282 TempParamLists.size(), 6283 /*friend*/ true, 6284 isExplicitSpecialization, 6285 Invalid)) { 6286 --NumMatchedTemplateParamLists; 6287 6288 if (TemplateParams->size() > 0) { 6289 // This is a declaration of a class template. 6290 if (Invalid) 6291 return 0; 6292 6293 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 6294 SS, Name, NameLoc, Attr, 6295 TemplateParams, AS_public).take(); 6296 } else { 6297 // The "template<>" header is extraneous. 6298 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 6299 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 6300 isExplicitSpecialization = true; 6301 } 6302 } 6303 6304 if (Invalid) return 0; 6305 6306 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 6307 6308 bool isAllExplicitSpecializations = true; 6309 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) { 6310 if (TempParamLists.get()[I]->size()) { 6311 isAllExplicitSpecializations = false; 6312 break; 6313 } 6314 } 6315 6316 // FIXME: don't ignore attributes. 6317 6318 // If it's explicit specializations all the way down, just forget 6319 // about the template header and build an appropriate non-templated 6320 // friend. TODO: for source fidelity, remember the headers. 6321 if (isAllExplicitSpecializations) { 6322 ElaboratedTypeKeyword Keyword 6323 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6324 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name, 6325 TagLoc, SS.getRange(), NameLoc); 6326 if (T.isNull()) 6327 return 0; 6328 6329 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6330 if (isa<DependentNameType>(T)) { 6331 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6332 TL.setKeywordLoc(TagLoc); 6333 TL.setQualifierRange(SS.getRange()); 6334 TL.setNameLoc(NameLoc); 6335 } else { 6336 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 6337 TL.setKeywordLoc(TagLoc); 6338 TL.setQualifierRange(SS.getRange()); 6339 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 6340 } 6341 6342 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 6343 TSI, FriendLoc); 6344 Friend->setAccess(AS_public); 6345 CurContext->addDecl(Friend); 6346 return Friend; 6347 } 6348 6349 // Handle the case of a templated-scope friend class. e.g. 6350 // template <class T> class A<T>::B; 6351 // FIXME: we don't support these right now. 6352 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6353 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 6354 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6355 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6356 TL.setKeywordLoc(TagLoc); 6357 TL.setQualifierRange(SS.getRange()); 6358 TL.setNameLoc(NameLoc); 6359 6360 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 6361 TSI, FriendLoc); 6362 Friend->setAccess(AS_public); 6363 Friend->setUnsupportedFriend(true); 6364 CurContext->addDecl(Friend); 6365 return Friend; 6366} 6367 6368 6369/// Handle a friend type declaration. This works in tandem with 6370/// ActOnTag. 6371/// 6372/// Notes on friend class templates: 6373/// 6374/// We generally treat friend class declarations as if they were 6375/// declaring a class. So, for example, the elaborated type specifier 6376/// in a friend declaration is required to obey the restrictions of a 6377/// class-head (i.e. no typedefs in the scope chain), template 6378/// parameters are required to match up with simple template-ids, &c. 6379/// However, unlike when declaring a template specialization, it's 6380/// okay to refer to a template specialization without an empty 6381/// template parameter declaration, e.g. 6382/// friend class A<T>::B<unsigned>; 6383/// We permit this as a special case; if there are any template 6384/// parameters present at all, require proper matching, i.e. 6385/// template <> template <class T> friend class A<int>::B; 6386Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 6387 MultiTemplateParamsArg TempParams) { 6388 SourceLocation Loc = DS.getSourceRange().getBegin(); 6389 6390 assert(DS.isFriendSpecified()); 6391 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 6392 6393 // Try to convert the decl specifier to a type. This works for 6394 // friend templates because ActOnTag never produces a ClassTemplateDecl 6395 // for a TUK_Friend. 6396 Declarator TheDeclarator(DS, Declarator::MemberContext); 6397 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 6398 QualType T = TSI->getType(); 6399 if (TheDeclarator.isInvalidType()) 6400 return 0; 6401 6402 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 6403 return 0; 6404 6405 // This is definitely an error in C++98. It's probably meant to 6406 // be forbidden in C++0x, too, but the specification is just 6407 // poorly written. 6408 // 6409 // The problem is with declarations like the following: 6410 // template <T> friend A<T>::foo; 6411 // where deciding whether a class C is a friend or not now hinges 6412 // on whether there exists an instantiation of A that causes 6413 // 'foo' to equal C. There are restrictions on class-heads 6414 // (which we declare (by fiat) elaborated friend declarations to 6415 // be) that makes this tractable. 6416 // 6417 // FIXME: handle "template <> friend class A<T>;", which 6418 // is possibly well-formed? Who even knows? 6419 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 6420 Diag(Loc, diag::err_tagless_friend_type_template) 6421 << DS.getSourceRange(); 6422 return 0; 6423 } 6424 6425 // C++98 [class.friend]p1: A friend of a class is a function 6426 // or class that is not a member of the class . . . 6427 // This is fixed in DR77, which just barely didn't make the C++03 6428 // deadline. It's also a very silly restriction that seriously 6429 // affects inner classes and which nobody else seems to implement; 6430 // thus we never diagnose it, not even in -pedantic. 6431 // 6432 // But note that we could warn about it: it's always useless to 6433 // friend one of your own members (it's not, however, worthless to 6434 // friend a member of an arbitrary specialization of your template). 6435 6436 Decl *D; 6437 if (unsigned NumTempParamLists = TempParams.size()) 6438 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 6439 NumTempParamLists, 6440 TempParams.release(), 6441 TSI, 6442 DS.getFriendSpecLoc()); 6443 else 6444 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 6445 6446 if (!D) 6447 return 0; 6448 6449 D->setAccess(AS_public); 6450 CurContext->addDecl(D); 6451 6452 return D; 6453} 6454 6455Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 6456 MultiTemplateParamsArg TemplateParams) { 6457 const DeclSpec &DS = D.getDeclSpec(); 6458 6459 assert(DS.isFriendSpecified()); 6460 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 6461 6462 SourceLocation Loc = D.getIdentifierLoc(); 6463 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6464 QualType T = TInfo->getType(); 6465 6466 // C++ [class.friend]p1 6467 // A friend of a class is a function or class.... 6468 // Note that this sees through typedefs, which is intended. 6469 // It *doesn't* see through dependent types, which is correct 6470 // according to [temp.arg.type]p3: 6471 // If a declaration acquires a function type through a 6472 // type dependent on a template-parameter and this causes 6473 // a declaration that does not use the syntactic form of a 6474 // function declarator to have a function type, the program 6475 // is ill-formed. 6476 if (!T->isFunctionType()) { 6477 Diag(Loc, diag::err_unexpected_friend); 6478 6479 // It might be worthwhile to try to recover by creating an 6480 // appropriate declaration. 6481 return 0; 6482 } 6483 6484 // C++ [namespace.memdef]p3 6485 // - If a friend declaration in a non-local class first declares a 6486 // class or function, the friend class or function is a member 6487 // of the innermost enclosing namespace. 6488 // - The name of the friend is not found by simple name lookup 6489 // until a matching declaration is provided in that namespace 6490 // scope (either before or after the class declaration granting 6491 // friendship). 6492 // - If a friend function is called, its name may be found by the 6493 // name lookup that considers functions from namespaces and 6494 // classes associated with the types of the function arguments. 6495 // - When looking for a prior declaration of a class or a function 6496 // declared as a friend, scopes outside the innermost enclosing 6497 // namespace scope are not considered. 6498 6499 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6500 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6501 DeclarationName Name = NameInfo.getName(); 6502 assert(Name); 6503 6504 // Check for unexpanded parameter packs. 6505 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 6506 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 6507 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 6508 return 0; 6509 6510 // The context we found the declaration in, or in which we should 6511 // create the declaration. 6512 DeclContext *DC; 6513 Scope *DCScope = S; 6514 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6515 ForRedeclaration); 6516 6517 // FIXME: there are different rules in local classes 6518 6519 // There are four cases here. 6520 // - There's no scope specifier, in which case we just go to the 6521 // appropriate scope and look for a function or function template 6522 // there as appropriate. 6523 // Recover from invalid scope qualifiers as if they just weren't there. 6524 if (SS.isInvalid() || !SS.isSet()) { 6525 // C++0x [namespace.memdef]p3: 6526 // If the name in a friend declaration is neither qualified nor 6527 // a template-id and the declaration is a function or an 6528 // elaborated-type-specifier, the lookup to determine whether 6529 // the entity has been previously declared shall not consider 6530 // any scopes outside the innermost enclosing namespace. 6531 // C++0x [class.friend]p11: 6532 // If a friend declaration appears in a local class and the name 6533 // specified is an unqualified name, a prior declaration is 6534 // looked up without considering scopes that are outside the 6535 // innermost enclosing non-class scope. For a friend function 6536 // declaration, if there is no prior declaration, the program is 6537 // ill-formed. 6538 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 6539 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 6540 6541 // Find the appropriate context according to the above. 6542 DC = CurContext; 6543 while (true) { 6544 // Skip class contexts. If someone can cite chapter and verse 6545 // for this behavior, that would be nice --- it's what GCC and 6546 // EDG do, and it seems like a reasonable intent, but the spec 6547 // really only says that checks for unqualified existing 6548 // declarations should stop at the nearest enclosing namespace, 6549 // not that they should only consider the nearest enclosing 6550 // namespace. 6551 while (DC->isRecord()) 6552 DC = DC->getParent(); 6553 6554 LookupQualifiedName(Previous, DC); 6555 6556 // TODO: decide what we think about using declarations. 6557 if (isLocal || !Previous.empty()) 6558 break; 6559 6560 if (isTemplateId) { 6561 if (isa<TranslationUnitDecl>(DC)) break; 6562 } else { 6563 if (DC->isFileContext()) break; 6564 } 6565 DC = DC->getParent(); 6566 } 6567 6568 // C++ [class.friend]p1: A friend of a class is a function or 6569 // class that is not a member of the class . . . 6570 // C++0x changes this for both friend types and functions. 6571 // Most C++ 98 compilers do seem to give an error here, so 6572 // we do, too. 6573 if (!Previous.empty() && DC->Equals(CurContext) 6574 && !getLangOptions().CPlusPlus0x) 6575 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 6576 6577 DCScope = getScopeForDeclContext(S, DC); 6578 6579 // - There's a non-dependent scope specifier, in which case we 6580 // compute it and do a previous lookup there for a function 6581 // or function template. 6582 } else if (!SS.getScopeRep()->isDependent()) { 6583 DC = computeDeclContext(SS); 6584 if (!DC) return 0; 6585 6586 if (RequireCompleteDeclContext(SS, DC)) return 0; 6587 6588 LookupQualifiedName(Previous, DC); 6589 6590 // Ignore things found implicitly in the wrong scope. 6591 // TODO: better diagnostics for this case. Suggesting the right 6592 // qualified scope would be nice... 6593 LookupResult::Filter F = Previous.makeFilter(); 6594 while (F.hasNext()) { 6595 NamedDecl *D = F.next(); 6596 if (!DC->InEnclosingNamespaceSetOf( 6597 D->getDeclContext()->getRedeclContext())) 6598 F.erase(); 6599 } 6600 F.done(); 6601 6602 if (Previous.empty()) { 6603 D.setInvalidType(); 6604 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 6605 return 0; 6606 } 6607 6608 // C++ [class.friend]p1: A friend of a class is a function or 6609 // class that is not a member of the class . . . 6610 if (DC->Equals(CurContext)) 6611 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 6612 6613 // - There's a scope specifier that does not match any template 6614 // parameter lists, in which case we use some arbitrary context, 6615 // create a method or method template, and wait for instantiation. 6616 // - There's a scope specifier that does match some template 6617 // parameter lists, which we don't handle right now. 6618 } else { 6619 DC = CurContext; 6620 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 6621 } 6622 6623 if (!DC->isRecord()) { 6624 // This implies that it has to be an operator or function. 6625 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 6626 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 6627 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 6628 Diag(Loc, diag::err_introducing_special_friend) << 6629 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 6630 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 6631 return 0; 6632 } 6633 } 6634 6635 bool Redeclaration = false; 6636 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 6637 move(TemplateParams), 6638 IsDefinition, 6639 Redeclaration); 6640 if (!ND) return 0; 6641 6642 assert(ND->getDeclContext() == DC); 6643 assert(ND->getLexicalDeclContext() == CurContext); 6644 6645 // Add the function declaration to the appropriate lookup tables, 6646 // adjusting the redeclarations list as necessary. We don't 6647 // want to do this yet if the friending class is dependent. 6648 // 6649 // Also update the scope-based lookup if the target context's 6650 // lookup context is in lexical scope. 6651 if (!CurContext->isDependentContext()) { 6652 DC = DC->getRedeclContext(); 6653 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 6654 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 6655 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 6656 } 6657 6658 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 6659 D.getIdentifierLoc(), ND, 6660 DS.getFriendSpecLoc()); 6661 FrD->setAccess(AS_public); 6662 CurContext->addDecl(FrD); 6663 6664 if (ND->isInvalidDecl()) 6665 FrD->setInvalidDecl(); 6666 else { 6667 FunctionDecl *FD; 6668 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 6669 FD = FTD->getTemplatedDecl(); 6670 else 6671 FD = cast<FunctionDecl>(ND); 6672 6673 // Mark templated-scope function declarations as unsupported. 6674 if (FD->getNumTemplateParameterLists()) 6675 FrD->setUnsupportedFriend(true); 6676 } 6677 6678 return ND; 6679} 6680 6681void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 6682 AdjustDeclIfTemplate(Dcl); 6683 6684 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 6685 if (!Fn) { 6686 Diag(DelLoc, diag::err_deleted_non_function); 6687 return; 6688 } 6689 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 6690 Diag(DelLoc, diag::err_deleted_decl_not_first); 6691 Diag(Prev->getLocation(), diag::note_previous_declaration); 6692 // If the declaration wasn't the first, we delete the function anyway for 6693 // recovery. 6694 } 6695 Fn->setDeleted(); 6696} 6697 6698static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 6699 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 6700 ++CI) { 6701 Stmt *SubStmt = *CI; 6702 if (!SubStmt) 6703 continue; 6704 if (isa<ReturnStmt>(SubStmt)) 6705 Self.Diag(SubStmt->getSourceRange().getBegin(), 6706 diag::err_return_in_constructor_handler); 6707 if (!isa<Expr>(SubStmt)) 6708 SearchForReturnInStmt(Self, SubStmt); 6709 } 6710} 6711 6712void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 6713 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 6714 CXXCatchStmt *Handler = TryBlock->getHandler(I); 6715 SearchForReturnInStmt(*this, Handler); 6716 } 6717} 6718 6719bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 6720 const CXXMethodDecl *Old) { 6721 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 6722 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 6723 6724 if (Context.hasSameType(NewTy, OldTy) || 6725 NewTy->isDependentType() || OldTy->isDependentType()) 6726 return false; 6727 6728 // Check if the return types are covariant 6729 QualType NewClassTy, OldClassTy; 6730 6731 /// Both types must be pointers or references to classes. 6732 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 6733 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 6734 NewClassTy = NewPT->getPointeeType(); 6735 OldClassTy = OldPT->getPointeeType(); 6736 } 6737 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 6738 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 6739 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 6740 NewClassTy = NewRT->getPointeeType(); 6741 OldClassTy = OldRT->getPointeeType(); 6742 } 6743 } 6744 } 6745 6746 // The return types aren't either both pointers or references to a class type. 6747 if (NewClassTy.isNull()) { 6748 Diag(New->getLocation(), 6749 diag::err_different_return_type_for_overriding_virtual_function) 6750 << New->getDeclName() << NewTy << OldTy; 6751 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6752 6753 return true; 6754 } 6755 6756 // C++ [class.virtual]p6: 6757 // If the return type of D::f differs from the return type of B::f, the 6758 // class type in the return type of D::f shall be complete at the point of 6759 // declaration of D::f or shall be the class type D. 6760 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 6761 if (!RT->isBeingDefined() && 6762 RequireCompleteType(New->getLocation(), NewClassTy, 6763 PDiag(diag::err_covariant_return_incomplete) 6764 << New->getDeclName())) 6765 return true; 6766 } 6767 6768 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 6769 // Check if the new class derives from the old class. 6770 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 6771 Diag(New->getLocation(), 6772 diag::err_covariant_return_not_derived) 6773 << New->getDeclName() << NewTy << OldTy; 6774 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6775 return true; 6776 } 6777 6778 // Check if we the conversion from derived to base is valid. 6779 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 6780 diag::err_covariant_return_inaccessible_base, 6781 diag::err_covariant_return_ambiguous_derived_to_base_conv, 6782 // FIXME: Should this point to the return type? 6783 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 6784 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6785 return true; 6786 } 6787 } 6788 6789 // The qualifiers of the return types must be the same. 6790 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 6791 Diag(New->getLocation(), 6792 diag::err_covariant_return_type_different_qualifications) 6793 << New->getDeclName() << NewTy << OldTy; 6794 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6795 return true; 6796 }; 6797 6798 6799 // The new class type must have the same or less qualifiers as the old type. 6800 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 6801 Diag(New->getLocation(), 6802 diag::err_covariant_return_type_class_type_more_qualified) 6803 << New->getDeclName() << NewTy << OldTy; 6804 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6805 return true; 6806 }; 6807 6808 return false; 6809} 6810 6811bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 6812 const CXXMethodDecl *Old) 6813{ 6814 if (Old->hasAttr<FinalAttr>()) { 6815 Diag(New->getLocation(), diag::err_final_function_overridden) 6816 << New->getDeclName(); 6817 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6818 return true; 6819 } 6820 6821 return false; 6822} 6823 6824/// \brief Mark the given method pure. 6825/// 6826/// \param Method the method to be marked pure. 6827/// 6828/// \param InitRange the source range that covers the "0" initializer. 6829bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 6830 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 6831 Method->setPure(); 6832 return false; 6833 } 6834 6835 if (!Method->isInvalidDecl()) 6836 Diag(Method->getLocation(), diag::err_non_virtual_pure) 6837 << Method->getDeclName() << InitRange; 6838 return true; 6839} 6840 6841/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 6842/// an initializer for the out-of-line declaration 'Dcl'. The scope 6843/// is a fresh scope pushed for just this purpose. 6844/// 6845/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6846/// static data member of class X, names should be looked up in the scope of 6847/// class X. 6848void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 6849 // If there is no declaration, there was an error parsing it. 6850 if (D == 0) return; 6851 6852 // We should only get called for declarations with scope specifiers, like: 6853 // int foo::bar; 6854 assert(D->isOutOfLine()); 6855 EnterDeclaratorContext(S, D->getDeclContext()); 6856} 6857 6858/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6859/// initializer for the out-of-line declaration 'D'. 6860void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 6861 // If there is no declaration, there was an error parsing it. 6862 if (D == 0) return; 6863 6864 assert(D->isOutOfLine()); 6865 ExitDeclaratorContext(S); 6866} 6867 6868/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 6869/// C++ if/switch/while/for statement. 6870/// e.g: "if (int x = f()) {...}" 6871DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 6872 // C++ 6.4p2: 6873 // The declarator shall not specify a function or an array. 6874 // The type-specifier-seq shall not contain typedef and shall not declare a 6875 // new class or enumeration. 6876 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6877 "Parser allowed 'typedef' as storage class of condition decl."); 6878 6879 TagDecl *OwnedTag = 0; 6880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 6881 QualType Ty = TInfo->getType(); 6882 6883 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 6884 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 6885 // would be created and CXXConditionDeclExpr wants a VarDecl. 6886 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 6887 << D.getSourceRange(); 6888 return DeclResult(); 6889 } else if (OwnedTag && OwnedTag->isDefinition()) { 6890 // The type-specifier-seq shall not declare a new class or enumeration. 6891 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 6892 } 6893 6894 Decl *Dcl = ActOnDeclarator(S, D); 6895 if (!Dcl) 6896 return DeclResult(); 6897 6898 return Dcl; 6899} 6900 6901void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6902 bool DefinitionRequired) { 6903 // Ignore any vtable uses in unevaluated operands or for classes that do 6904 // not have a vtable. 6905 if (!Class->isDynamicClass() || Class->isDependentContext() || 6906 CurContext->isDependentContext() || 6907 ExprEvalContexts.back().Context == Unevaluated) 6908 return; 6909 6910 // Try to insert this class into the map. 6911 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6912 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 6913 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 6914 if (!Pos.second) { 6915 // If we already had an entry, check to see if we are promoting this vtable 6916 // to required a definition. If so, we need to reappend to the VTableUses 6917 // list, since we may have already processed the first entry. 6918 if (DefinitionRequired && !Pos.first->second) { 6919 Pos.first->second = true; 6920 } else { 6921 // Otherwise, we can early exit. 6922 return; 6923 } 6924 } 6925 6926 // Local classes need to have their virtual members marked 6927 // immediately. For all other classes, we mark their virtual members 6928 // at the end of the translation unit. 6929 if (Class->isLocalClass()) 6930 MarkVirtualMembersReferenced(Loc, Class); 6931 else 6932 VTableUses.push_back(std::make_pair(Class, Loc)); 6933} 6934 6935bool Sema::DefineUsedVTables() { 6936 if (VTableUses.empty()) 6937 return false; 6938 6939 // Note: The VTableUses vector could grow as a result of marking 6940 // the members of a class as "used", so we check the size each 6941 // time through the loop and prefer indices (with are stable) to 6942 // iterators (which are not). 6943 for (unsigned I = 0; I != VTableUses.size(); ++I) { 6944 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 6945 if (!Class) 6946 continue; 6947 6948 SourceLocation Loc = VTableUses[I].second; 6949 6950 // If this class has a key function, but that key function is 6951 // defined in another translation unit, we don't need to emit the 6952 // vtable even though we're using it. 6953 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 6954 if (KeyFunction && !KeyFunction->hasBody()) { 6955 switch (KeyFunction->getTemplateSpecializationKind()) { 6956 case TSK_Undeclared: 6957 case TSK_ExplicitSpecialization: 6958 case TSK_ExplicitInstantiationDeclaration: 6959 // The key function is in another translation unit. 6960 continue; 6961 6962 case TSK_ExplicitInstantiationDefinition: 6963 case TSK_ImplicitInstantiation: 6964 // We will be instantiating the key function. 6965 break; 6966 } 6967 } else if (!KeyFunction) { 6968 // If we have a class with no key function that is the subject 6969 // of an explicit instantiation declaration, suppress the 6970 // vtable; it will live with the explicit instantiation 6971 // definition. 6972 bool IsExplicitInstantiationDeclaration 6973 = Class->getTemplateSpecializationKind() 6974 == TSK_ExplicitInstantiationDeclaration; 6975 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 6976 REnd = Class->redecls_end(); 6977 R != REnd; ++R) { 6978 TemplateSpecializationKind TSK 6979 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 6980 if (TSK == TSK_ExplicitInstantiationDeclaration) 6981 IsExplicitInstantiationDeclaration = true; 6982 else if (TSK == TSK_ExplicitInstantiationDefinition) { 6983 IsExplicitInstantiationDeclaration = false; 6984 break; 6985 } 6986 } 6987 6988 if (IsExplicitInstantiationDeclaration) 6989 continue; 6990 } 6991 6992 // Mark all of the virtual members of this class as referenced, so 6993 // that we can build a vtable. Then, tell the AST consumer that a 6994 // vtable for this class is required. 6995 MarkVirtualMembersReferenced(Loc, Class); 6996 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6997 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 6998 6999 // Optionally warn if we're emitting a weak vtable. 7000 if (Class->getLinkage() == ExternalLinkage && 7001 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 7002 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 7003 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 7004 } 7005 } 7006 VTableUses.clear(); 7007 7008 return true; 7009} 7010 7011void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 7012 const CXXRecordDecl *RD) { 7013 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 7014 e = RD->method_end(); i != e; ++i) { 7015 CXXMethodDecl *MD = *i; 7016 7017 // C++ [basic.def.odr]p2: 7018 // [...] A virtual member function is used if it is not pure. [...] 7019 if (MD->isVirtual() && !MD->isPure()) 7020 MarkDeclarationReferenced(Loc, MD); 7021 } 7022 7023 // Only classes that have virtual bases need a VTT. 7024 if (RD->getNumVBases() == 0) 7025 return; 7026 7027 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 7028 e = RD->bases_end(); i != e; ++i) { 7029 const CXXRecordDecl *Base = 7030 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 7031 if (Base->getNumVBases() == 0) 7032 continue; 7033 MarkVirtualMembersReferenced(Loc, Base); 7034 } 7035} 7036 7037/// SetIvarInitializers - This routine builds initialization ASTs for the 7038/// Objective-C implementation whose ivars need be initialized. 7039void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 7040 if (!getLangOptions().CPlusPlus) 7041 return; 7042 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 7043 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 7044 CollectIvarsToConstructOrDestruct(OID, ivars); 7045 if (ivars.empty()) 7046 return; 7047 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 7048 for (unsigned i = 0; i < ivars.size(); i++) { 7049 FieldDecl *Field = ivars[i]; 7050 if (Field->isInvalidDecl()) 7051 continue; 7052 7053 CXXBaseOrMemberInitializer *Member; 7054 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 7055 InitializationKind InitKind = 7056 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 7057 7058 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 7059 ExprResult MemberInit = 7060 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 7061 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 7062 // Note, MemberInit could actually come back empty if no initialization 7063 // is required (e.g., because it would call a trivial default constructor) 7064 if (!MemberInit.get() || MemberInit.isInvalid()) 7065 continue; 7066 7067 Member = 7068 new (Context) CXXBaseOrMemberInitializer(Context, 7069 Field, SourceLocation(), 7070 SourceLocation(), 7071 MemberInit.takeAs<Expr>(), 7072 SourceLocation()); 7073 AllToInit.push_back(Member); 7074 7075 // Be sure that the destructor is accessible and is marked as referenced. 7076 if (const RecordType *RecordTy 7077 = Context.getBaseElementType(Field->getType()) 7078 ->getAs<RecordType>()) { 7079 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 7080 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 7081 MarkDeclarationReferenced(Field->getLocation(), Destructor); 7082 CheckDestructorAccess(Field->getLocation(), Destructor, 7083 PDiag(diag::err_access_dtor_ivar) 7084 << Context.getBaseElementType(Field->getType())); 7085 } 7086 } 7087 } 7088 ObjCImplementation->setIvarInitializers(Context, 7089 AllToInit.data(), AllToInit.size()); 7090 } 7091} 7092