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