clang API Documentation
00001 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for C++ declarations. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "Sema.h" 00015 #include "SemaInit.h" 00016 #include "Lookup.h" 00017 #include "clang/AST/ASTConsumer.h" 00018 #include "clang/AST/ASTContext.h" 00019 #include "clang/AST/CharUnits.h" 00020 #include "clang/AST/CXXInheritance.h" 00021 #include "clang/AST/DeclVisitor.h" 00022 #include "clang/AST/RecordLayout.h" 00023 #include "clang/AST/StmtVisitor.h" 00024 #include "clang/AST/TypeLoc.h" 00025 #include "clang/AST/TypeOrdering.h" 00026 #include "clang/Parse/DeclSpec.h" 00027 #include "clang/Parse/Template.h" 00028 #include "clang/Basic/PartialDiagnostic.h" 00029 #include "clang/Lex/Preprocessor.h" 00030 #include "llvm/ADT/STLExtras.h" 00031 #include <map> 00032 #include <set> 00033 00034 using namespace clang; 00035 00036 //===----------------------------------------------------------------------===// 00037 // CheckDefaultArgumentVisitor 00038 //===----------------------------------------------------------------------===// 00039 00040 namespace { 00041 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 00042 /// the default argument of a parameter to determine whether it 00043 /// contains any ill-formed subexpressions. For example, this will 00044 /// diagnose the use of local variables or parameters within the 00045 /// default argument expression. 00046 class CheckDefaultArgumentVisitor 00047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 00048 Expr *DefaultArg; 00049 Sema *S; 00050 00051 public: 00052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 00053 : DefaultArg(defarg), S(s) {} 00054 00055 bool VisitExpr(Expr *Node); 00056 bool VisitDeclRefExpr(DeclRefExpr *DRE); 00057 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 00058 }; 00059 00060 /// VisitExpr - Visit all of the children of this expression. 00061 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 00062 bool IsInvalid = false; 00063 for (Stmt::child_iterator I = Node->child_begin(), 00064 E = Node->child_end(); I != E; ++I) 00065 IsInvalid |= Visit(*I); 00066 return IsInvalid; 00067 } 00068 00069 /// VisitDeclRefExpr - Visit a reference to a declaration, to 00070 /// determine whether this declaration can be used in the default 00071 /// argument expression. 00072 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 00073 NamedDecl *Decl = DRE->getDecl(); 00074 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 00075 // C++ [dcl.fct.default]p9 00076 // Default arguments are evaluated each time the function is 00077 // called. The order of evaluation of function arguments is 00078 // unspecified. Consequently, parameters of a function shall not 00079 // be used in default argument expressions, even if they are not 00080 // evaluated. Parameters of a function declared before a default 00081 // argument expression are in scope and can hide namespace and 00082 // class member names. 00083 return S->Diag(DRE->getSourceRange().getBegin(), 00084 diag::err_param_default_argument_references_param) 00085 << Param->getDeclName() << DefaultArg->getSourceRange(); 00086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 00087 // C++ [dcl.fct.default]p7 00088 // Local variables shall not be used in default argument 00089 // expressions. 00090 if (VDecl->isBlockVarDecl()) 00091 return S->Diag(DRE->getSourceRange().getBegin(), 00092 diag::err_param_default_argument_references_local) 00093 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 00094 } 00095 00096 return false; 00097 } 00098 00099 /// VisitCXXThisExpr - Visit a C++ "this" expression. 00100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 00101 // C++ [dcl.fct.default]p8: 00102 // The keyword this shall not be used in a default argument of a 00103 // member function. 00104 return S->Diag(ThisE->getSourceRange().getBegin(), 00105 diag::err_param_default_argument_references_this) 00106 << ThisE->getSourceRange(); 00107 } 00108 } 00109 00110 bool 00111 Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 00112 SourceLocation EqualLoc) { 00113 if (RequireCompleteType(Param->getLocation(), Param->getType(), 00114 diag::err_typecheck_decl_incomplete_type)) { 00115 Param->setInvalidDecl(); 00116 return true; 00117 } 00118 00119 Expr *Arg = (Expr *)DefaultArg.get(); 00120 00121 // C++ [dcl.fct.default]p5 00122 // A default argument expression is implicitly converted (clause 00123 // 4) to the parameter type. The default argument expression has 00124 // the same semantic constraints as the initializer expression in 00125 // a declaration of a variable of the parameter type, using the 00126 // copy-initialization semantics (8.5). 00127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 00128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 00129 EqualLoc); 00130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 00131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 00132 MultiExprArg(*this, (void**)&Arg, 1)); 00133 if (Result.isInvalid()) 00134 return true; 00135 Arg = Result.takeAs<Expr>(); 00136 00137 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 00138 00139 // Okay: add the default argument to the parameter 00140 Param->setDefaultArg(Arg); 00141 00142 DefaultArg.release(); 00143 00144 return false; 00145 } 00146 00147 /// ActOnParamDefaultArgument - Check whether the default argument 00148 /// provided for a function parameter is well-formed. If so, attach it 00149 /// to the parameter declaration. 00150 void 00151 Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 00152 ExprArg defarg) { 00153 if (!param || !defarg.get()) 00154 return; 00155 00156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00157 UnparsedDefaultArgLocs.erase(Param); 00158 00159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 00160 00161 // Default arguments are only permitted in C++ 00162 if (!getLangOptions().CPlusPlus) { 00163 Diag(EqualLoc, diag::err_param_default_argument) 00164 << DefaultArg->getSourceRange(); 00165 Param->setInvalidDecl(); 00166 return; 00167 } 00168 00169 // Check that the default argument is well-formed 00170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 00171 if (DefaultArgChecker.Visit(DefaultArg.get())) { 00172 Param->setInvalidDecl(); 00173 return; 00174 } 00175 00176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 00177 } 00178 00179 /// ActOnParamUnparsedDefaultArgument - We've seen a default 00180 /// argument for a function parameter, but we can't parse it yet 00181 /// because we're inside a class definition. Note that this default 00182 /// argument will be parsed later. 00183 void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 00184 SourceLocation EqualLoc, 00185 SourceLocation ArgLoc) { 00186 if (!param) 00187 return; 00188 00189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00190 if (Param) 00191 Param->setUnparsedDefaultArg(); 00192 00193 UnparsedDefaultArgLocs[Param] = ArgLoc; 00194 } 00195 00196 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 00197 /// the default argument for the parameter param failed. 00198 void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 00199 if (!param) 00200 return; 00201 00202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 00203 00204 Param->setInvalidDecl(); 00205 00206 UnparsedDefaultArgLocs.erase(Param); 00207 } 00208 00209 /// CheckExtraCXXDefaultArguments - Check for any extra default 00210 /// arguments in the declarator, which is not a function declaration 00211 /// or definition and therefore is not permitted to have default 00212 /// arguments. This routine should be invoked for every declarator 00213 /// that is not a function declaration or definition. 00214 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 00215 // C++ [dcl.fct.default]p3 00216 // A default argument expression shall be specified only in the 00217 // parameter-declaration-clause of a function declaration or in a 00218 // template-parameter (14.1). It shall not be specified for a 00219 // parameter pack. If it is specified in a 00220 // parameter-declaration-clause, it shall not occur within a 00221 // declarator or abstract-declarator of a parameter-declaration. 00222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 00223 DeclaratorChunk &chunk = D.getTypeObject(i); 00224 if (chunk.Kind == DeclaratorChunk::Function) { 00225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 00226 ParmVarDecl *Param = 00227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 00228 if (Param->hasUnparsedDefaultArg()) { 00229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 00230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 00231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 00232 delete Toks; 00233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 00234 } else if (Param->getDefaultArg()) { 00235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 00236 << Param->getDefaultArg()->getSourceRange(); 00237 Param->setDefaultArg(0); 00238 } 00239 } 00240 } 00241 } 00242 } 00243 00244 // MergeCXXFunctionDecl - Merge two declarations of the same C++ 00245 // function, once we already know that they have the same 00246 // type. Subroutine of MergeFunctionDecl. Returns true if there was an 00247 // error, false otherwise. 00248 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 00249 bool Invalid = false; 00250 00251 // C++ [dcl.fct.default]p4: 00252 // For non-template functions, default arguments can be added in 00253 // later declarations of a function in the same 00254 // scope. Declarations in different scopes have completely 00255 // distinct sets of default arguments. That is, declarations in 00256 // inner scopes do not acquire default arguments from 00257 // declarations in outer scopes, and vice versa. In a given 00258 // function declaration, all parameters subsequent to a 00259 // parameter with a default argument shall have default 00260 // arguments supplied in this or previous declarations. A 00261 // default argument shall not be redefined by a later 00262 // declaration (not even to the same value). 00263 // 00264 // C++ [dcl.fct.default]p6: 00265 // Except for member functions of class templates, the default arguments 00266 // in a member function definition that appears outside of the class 00267 // definition are added to the set of default arguments provided by the 00268 // member function declaration in the class definition. 00269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 00270 ParmVarDecl *OldParam = Old->getParamDecl(p); 00271 ParmVarDecl *NewParam = New->getParamDecl(p); 00272 00273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 00274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 00275 // hint here. Alternatively, we could walk the type-source information 00276 // for NewParam to find the last source location in the type... but it 00277 // isn't worth the effort right now. This is the kind of test case that 00278 // is hard to get right: 00279 00280 // int f(int); 00281 // void g(int (*fp)(int) = f); 00282 // void g(int (*fp)(int) = &f); 00283 Diag(NewParam->getLocation(), 00284 diag::err_param_default_argument_redefinition) 00285 << NewParam->getDefaultArgRange(); 00286 00287 // Look for the function declaration where the default argument was 00288 // actually written, which may be a declaration prior to Old. 00289 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 00290 Older; Older = Older->getPreviousDeclaration()) { 00291 if (!Older->getParamDecl(p)->hasDefaultArg()) 00292 break; 00293 00294 OldParam = Older->getParamDecl(p); 00295 } 00296 00297 Diag(OldParam->getLocation(), diag::note_previous_definition) 00298 << OldParam->getDefaultArgRange(); 00299 Invalid = true; 00300 } else if (OldParam->hasDefaultArg()) { 00301 // Merge the old default argument into the new parameter. 00302 // It's important to use getInit() here; getDefaultArg() 00303 // strips off any top-level CXXExprWithTemporaries. 00304 NewParam->setHasInheritedDefaultArg(); 00305 if (OldParam->hasUninstantiatedDefaultArg()) 00306 NewParam->setUninstantiatedDefaultArg( 00307 OldParam->getUninstantiatedDefaultArg()); 00308 else 00309 NewParam->setDefaultArg(OldParam->getInit()); 00310 } else if (NewParam->hasDefaultArg()) { 00311 if (New->getDescribedFunctionTemplate()) { 00312 // Paragraph 4, quoted above, only applies to non-template functions. 00313 Diag(NewParam->getLocation(), 00314 diag::err_param_default_argument_template_redecl) 00315 << NewParam->getDefaultArgRange(); 00316 Diag(Old->getLocation(), diag::note_template_prev_declaration) 00317 << false; 00318 } else if (New->getTemplateSpecializationKind() 00319 != TSK_ImplicitInstantiation && 00320 New->getTemplateSpecializationKind() != TSK_Undeclared) { 00321 // C++ [temp.expr.spec]p21: 00322 // Default function arguments shall not be specified in a declaration 00323 // or a definition for one of the following explicit specializations: 00324 // - the explicit specialization of a function template; 00325 // - the explicit specialization of a member function template; 00326 // - the explicit specialization of a member function of a class 00327 // template where the class template specialization to which the 00328 // member function specialization belongs is implicitly 00329 // instantiated. 00330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 00331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 00332 << New->getDeclName() 00333 << NewParam->getDefaultArgRange(); 00334 } else if (New->getDeclContext()->isDependentContext()) { 00335 // C++ [dcl.fct.default]p6 (DR217): 00336 // Default arguments for a member function of a class template shall 00337 // be specified on the initial declaration of the member function 00338 // within the class template. 00339 // 00340 // Reading the tea leaves a bit in DR217 and its reference to DR205 00341 // leads me to the conclusion that one cannot add default function 00342 // arguments for an out-of-line definition of a member function of a 00343 // dependent type. 00344 int WhichKind = 2; 00345 if (CXXRecordDecl *Record 00346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 00347 if (Record->getDescribedClassTemplate()) 00348 WhichKind = 0; 00349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 00350 WhichKind = 1; 00351 else 00352 WhichKind = 2; 00353 } 00354 00355 Diag(NewParam->getLocation(), 00356 diag::err_param_default_argument_member_template_redecl) 00357 << WhichKind 00358 << NewParam->getDefaultArgRange(); 00359 } 00360 } 00361 } 00362 00363 if (CheckEquivalentExceptionSpec(Old, New)) 00364 Invalid = true; 00365 00366 return Invalid; 00367 } 00368 00369 /// CheckCXXDefaultArguments - Verify that the default arguments for a 00370 /// function declaration are well-formed according to C++ 00371 /// [dcl.fct.default]. 00372 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 00373 unsigned NumParams = FD->getNumParams(); 00374 unsigned p; 00375 00376 // Find first parameter with a default argument 00377 for (p = 0; p < NumParams; ++p) { 00378 ParmVarDecl *Param = FD->getParamDecl(p); 00379 if (Param->hasDefaultArg()) 00380 break; 00381 } 00382 00383 // C++ [dcl.fct.default]p4: 00384 // In a given function declaration, all parameters 00385 // subsequent to a parameter with a default argument shall 00386 // have default arguments supplied in this or previous 00387 // declarations. A default argument shall not be redefined 00388 // by a later declaration (not even to the same value). 00389 unsigned LastMissingDefaultArg = 0; 00390 for (; p < NumParams; ++p) { 00391 ParmVarDecl *Param = FD->getParamDecl(p); 00392 if (!Param->hasDefaultArg()) { 00393 if (Param->isInvalidDecl()) 00394 /* We already complained about this parameter. */; 00395 else if (Param->getIdentifier()) 00396 Diag(Param->getLocation(), 00397 diag::err_param_default_argument_missing_name) 00398 << Param->getIdentifier(); 00399 else 00400 Diag(Param->getLocation(), 00401 diag::err_param_default_argument_missing); 00402 00403 LastMissingDefaultArg = p; 00404 } 00405 } 00406 00407 if (LastMissingDefaultArg > 0) { 00408 // Some default arguments were missing. Clear out all of the 00409 // default arguments up to (and including) the last missing 00410 // default argument, so that we leave the function parameters 00411 // in a semantically valid state. 00412 for (p = 0; p <= LastMissingDefaultArg; ++p) { 00413 ParmVarDecl *Param = FD->getParamDecl(p); 00414 if (Param->hasDefaultArg()) { 00415 if (!Param->hasUnparsedDefaultArg()) 00416 Param->getDefaultArg()->Destroy(Context); 00417 Param->setDefaultArg(0); 00418 } 00419 } 00420 } 00421 } 00422 00423 /// isCurrentClassName - Determine whether the identifier II is the 00424 /// name of the class type currently being defined. In the case of 00425 /// nested classes, this will only return true if II is the name of 00426 /// the innermost class. 00427 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 00428 const CXXScopeSpec *SS) { 00429 assert(getLangOptions().CPlusPlus && "No class names in C!"); 00430 00431 CXXRecordDecl *CurDecl; 00432 if (SS && SS->isSet() && !SS->isInvalid()) { 00433 DeclContext *DC = computeDeclContext(*SS, true); 00434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 00435 } else 00436 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 00437 00438 if (CurDecl && CurDecl->getIdentifier()) 00439 return &II == CurDecl->getIdentifier(); 00440 else 00441 return false; 00442 } 00443 00444 /// \brief Check the validity of a C++ base class specifier. 00445 /// 00446 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 00447 /// and returns NULL otherwise. 00448 CXXBaseSpecifier * 00449 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 00450 SourceRange SpecifierRange, 00451 bool Virtual, AccessSpecifier Access, 00452 QualType BaseType, 00453 SourceLocation BaseLoc) { 00454 // C++ [class.union]p1: 00455 // A union shall not have base classes. 00456 if (Class->isUnion()) { 00457 Diag(Class->getLocation(), diag::err_base_clause_on_union) 00458 << SpecifierRange; 00459 return 0; 00460 } 00461 00462 if (BaseType->isDependentType()) 00463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 00464 Class->getTagKind() == RecordDecl::TK_class, 00465 Access, BaseType); 00466 00467 // Base specifiers must be record types. 00468 if (!BaseType->isRecordType()) { 00469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 00470 return 0; 00471 } 00472 00473 // C++ [class.union]p1: 00474 // A union shall not be used as a base class. 00475 if (BaseType->isUnionType()) { 00476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 00477 return 0; 00478 } 00479 00480 // C++ [class.derived]p2: 00481 // The class-name in a base-specifier shall not be an incompletely 00482 // defined class. 00483 if (RequireCompleteType(BaseLoc, BaseType, 00484 PDiag(diag::err_incomplete_base_class) 00485 << SpecifierRange)) 00486 return 0; 00487 00488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 00489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 00490 assert(BaseDecl && "Record type has no declaration"); 00491 BaseDecl = BaseDecl->getDefinition(); 00492 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 00493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 00494 assert(CXXBaseDecl && "Base type is not a C++ type"); 00495 00496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 00497 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 00498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 00499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 00500 << BaseType; 00501 return 0; 00502 } 00503 00504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 00505 00506 // Create the base specifier. 00507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 00508 Class->getTagKind() == RecordDecl::TK_class, 00509 Access, BaseType); 00510 } 00511 00512 void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 00513 const CXXRecordDecl *BaseClass, 00514 bool BaseIsVirtual) { 00515 // A class with a non-empty base class is not empty. 00516 // FIXME: Standard ref? 00517 if (!BaseClass->isEmpty()) 00518 Class->setEmpty(false); 00519 00520 // C++ [class.virtual]p1: 00521 // A class that [...] inherits a virtual function is called a polymorphic 00522 // class. 00523 if (BaseClass->isPolymorphic()) 00524 Class->setPolymorphic(true); 00525 00526 // C++ [dcl.init.aggr]p1: 00527 // An aggregate is [...] a class with [...] no base classes [...]. 00528 Class->setAggregate(false); 00529 00530 // C++ [class]p4: 00531 // A POD-struct is an aggregate class... 00532 Class->setPOD(false); 00533 00534 if (BaseIsVirtual) { 00535 // C++ [class.ctor]p5: 00536 // A constructor is trivial if its class has no virtual base classes. 00537 Class->setHasTrivialConstructor(false); 00538 00539 // C++ [class.copy]p6: 00540 // A copy constructor is trivial if its class has no virtual base classes. 00541 Class->setHasTrivialCopyConstructor(false); 00542 00543 // C++ [class.copy]p11: 00544 // A copy assignment operator is trivial if its class has no virtual 00545 // base classes. 00546 Class->setHasTrivialCopyAssignment(false); 00547 00548 // C++0x [meta.unary.prop] is_empty: 00549 // T is a class type, but not a union type, with ... no virtual base 00550 // classes 00551 Class->setEmpty(false); 00552 } else { 00553 // C++ [class.ctor]p5: 00554 // A constructor is trivial if all the direct base classes of its 00555 // class have trivial constructors. 00556 if (!BaseClass->hasTrivialConstructor()) 00557 Class->setHasTrivialConstructor(false); 00558 00559 // C++ [class.copy]p6: 00560 // A copy constructor is trivial if all the direct base classes of its 00561 // class have trivial copy constructors. 00562 if (!BaseClass->hasTrivialCopyConstructor()) 00563 Class->setHasTrivialCopyConstructor(false); 00564 00565 // C++ [class.copy]p11: 00566 // A copy assignment operator is trivial if all the direct base classes 00567 // of its class have trivial copy assignment operators. 00568 if (!BaseClass->hasTrivialCopyAssignment()) 00569 Class->setHasTrivialCopyAssignment(false); 00570 } 00571 00572 // C++ [class.ctor]p3: 00573 // A destructor is trivial if all the direct base classes of its class 00574 // have trivial destructors. 00575 if (!BaseClass->hasTrivialDestructor()) 00576 Class->setHasTrivialDestructor(false); 00577 } 00578 00579 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 00580 /// one entry in the base class list of a class specifier, for 00581 /// example: 00582 /// class foo : public bar, virtual private baz { 00583 /// 'public bar' and 'virtual private baz' are each base-specifiers. 00584 Sema::BaseResult 00585 Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 00586 bool Virtual, AccessSpecifier Access, 00587 TypeTy *basetype, SourceLocation BaseLoc) { 00588 if (!classdecl) 00589 return true; 00590 00591 AdjustDeclIfTemplate(classdecl); 00592 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 00593 if (!Class) 00594 return true; 00595 00596 QualType BaseType = GetTypeFromParser(basetype); 00597 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 00598 Virtual, Access, 00599 BaseType, BaseLoc)) 00600 return BaseSpec; 00601 00602 return true; 00603 } 00604 00605 /// \brief Performs the actual work of attaching the given base class 00606 /// specifiers to a C++ class. 00607 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 00608 unsigned NumBases) { 00609 if (NumBases == 0) 00610 return false; 00611 00612 // Used to keep track of which base types we have already seen, so 00613 // that we can properly diagnose redundant direct base types. Note 00614 // that the key is always the unqualified canonical type of the base 00615 // class. 00616 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 00617 00618 // Copy non-redundant base specifiers into permanent storage. 00619 unsigned NumGoodBases = 0; 00620 bool Invalid = false; 00621 for (unsigned idx = 0; idx < NumBases; ++idx) { 00622 QualType NewBaseType 00623 = Context.getCanonicalType(Bases[idx]->getType()); 00624 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 00625 00626 if (KnownBaseTypes[NewBaseType]) { 00627 // C++ [class.mi]p3: 00628 // A class shall not be specified as a direct base class of a 00629 // derived class more than once. 00630 Diag(Bases[idx]->getSourceRange().getBegin(), 00631 diag::err_duplicate_base_class) 00632 << KnownBaseTypes[NewBaseType]->getType() 00633 << Bases[idx]->getSourceRange(); 00634 00635 // Delete the duplicate base class specifier; we're going to 00636 // overwrite its pointer later. 00637 Context.Deallocate(Bases[idx]); 00638 00639 Invalid = true; 00640 } else { 00641 // Okay, add this new base class. 00642 KnownBaseTypes[NewBaseType] = Bases[idx]; 00643 Bases[NumGoodBases++] = Bases[idx]; 00644 } 00645 } 00646 00647 // Attach the remaining base class specifiers to the derived class. 00648 Class->setBases(Bases, NumGoodBases); 00649 00650 // Delete the remaining (good) base class specifiers, since their 00651 // data has been copied into the CXXRecordDecl. 00652 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 00653 Context.Deallocate(Bases[idx]); 00654 00655 return Invalid; 00656 } 00657 00658 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 00659 /// class, after checking whether there are any duplicate base 00660 /// classes. 00661 void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 00662 unsigned NumBases) { 00663 if (!ClassDecl || !Bases || !NumBases) 00664 return; 00665 00666 AdjustDeclIfTemplate(ClassDecl); 00667 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 00668 (CXXBaseSpecifier**)(Bases), NumBases); 00669 } 00670 00671 static CXXRecordDecl *GetClassForType(QualType T) { 00672 if (const RecordType *RT = T->getAs<RecordType>()) 00673 return cast<CXXRecordDecl>(RT->getDecl()); 00674 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 00675 return ICT->getDecl(); 00676 else 00677 return 0; 00678 } 00679 00680 /// \brief Determine whether the type \p Derived is a C++ class that is 00681 /// derived from the type \p Base. 00682 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 00683 if (!getLangOptions().CPlusPlus) 00684 return false; 00685 00686 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 00687 if (!DerivedRD) 00688 return false; 00689 00690 CXXRecordDecl *BaseRD = GetClassForType(Base); 00691 if (!BaseRD) 00692 return false; 00693 00694 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 00695 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 00696 } 00697 00698 /// \brief Determine whether the type \p Derived is a C++ class that is 00699 /// derived from the type \p Base. 00700 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 00701 if (!getLangOptions().CPlusPlus) 00702 return false; 00703 00704 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 00705 if (!DerivedRD) 00706 return false; 00707 00708 CXXRecordDecl *BaseRD = GetClassForType(Base); 00709 if (!BaseRD) 00710 return false; 00711 00712 return DerivedRD->isDerivedFrom(BaseRD, Paths); 00713 } 00714 00715 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 00716 CXXBaseSpecifierArray &BasePathArray) { 00717 assert(BasePathArray.empty() && "Base path array must be empty!"); 00718 assert(Paths.isRecordingPaths() && "Must record paths!"); 00719 00720 const CXXBasePath &Path = Paths.front(); 00721 00722 // We first go backward and check if we have a virtual base. 00723 // FIXME: It would be better if CXXBasePath had the base specifier for 00724 // the nearest virtual base. 00725 unsigned Start = 0; 00726 for (unsigned I = Path.size(); I != 0; --I) { 00727 if (Path[I - 1].Base->isVirtual()) { 00728 Start = I - 1; 00729 break; 00730 } 00731 } 00732 00733 // Now add all bases. 00734 for (unsigned I = Start, E = Path.size(); I != E; ++I) 00735 BasePathArray.push_back(Path[I].Base); 00736 } 00737 00738 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 00739 /// conversion (where Derived and Base are class types) is 00740 /// well-formed, meaning that the conversion is unambiguous (and 00741 /// that all of the base classes are accessible). Returns true 00742 /// and emits a diagnostic if the code is ill-formed, returns false 00743 /// otherwise. Loc is the location where this routine should point to 00744 /// if there is an error, and Range is the source range to highlight 00745 /// if there is an error. 00746 bool 00747 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 00748 unsigned InaccessibleBaseID, 00749 unsigned AmbigiousBaseConvID, 00750 SourceLocation Loc, SourceRange Range, 00751 DeclarationName Name, 00752 CXXBaseSpecifierArray *BasePath) { 00753 // First, determine whether the path from Derived to Base is 00754 // ambiguous. This is slightly more expensive than checking whether 00755 // the Derived to Base conversion exists, because here we need to 00756 // explore multiple paths to determine if there is an ambiguity. 00757 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 00758 /*DetectVirtual=*/false); 00759 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 00760 assert(DerivationOkay && 00761 "Can only be used with a derived-to-base conversion"); 00762 (void)DerivationOkay; 00763 00764 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 00765 if (InaccessibleBaseID) { 00766 // Check that the base class can be accessed. 00767 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 00768 InaccessibleBaseID)) { 00769 case AR_inaccessible: 00770 return true; 00771 case AR_accessible: 00772 case AR_dependent: 00773 case AR_delayed: 00774 break; 00775 } 00776 } 00777 00778 // Build a base path if necessary. 00779 if (BasePath) 00780 BuildBasePathArray(Paths, *BasePath); 00781 return false; 00782 } 00783 00784 // We know that the derived-to-base conversion is ambiguous, and 00785 // we're going to produce a diagnostic. Perform the derived-to-base 00786 // search just one more time to compute all of the possible paths so 00787 // that we can print them out. This is more expensive than any of 00788 // the previous derived-to-base checks we've done, but at this point 00789 // performance isn't as much of an issue. 00790 Paths.clear(); 00791 Paths.setRecordingPaths(true); 00792 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 00793 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 00794 (void)StillOkay; 00795 00796 // Build up a textual representation of the ambiguous paths, e.g., 00797 // D -> B -> A, that will be used to illustrate the ambiguous 00798 // conversions in the diagnostic. We only print one of the paths 00799 // to each base class subobject. 00800 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 00801 00802 Diag(Loc, AmbigiousBaseConvID) 00803 << Derived << Base << PathDisplayStr << Range << Name; 00804 return true; 00805 } 00806 00807 bool 00808 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 00809 SourceLocation Loc, SourceRange Range, 00810 CXXBaseSpecifierArray *BasePath, 00811 bool IgnoreAccess) { 00812 return CheckDerivedToBaseConversion(Derived, Base, 00813 IgnoreAccess ? 0 00814 : diag::err_upcast_to_inaccessible_base, 00815 diag::err_ambiguous_derived_to_base_conv, 00816 Loc, Range, DeclarationName(), 00817 BasePath); 00818 } 00819 00820 00821 /// @brief Builds a string representing ambiguous paths from a 00822 /// specific derived class to different subobjects of the same base 00823 /// class. 00824 /// 00825 /// This function builds a string that can be used in error messages 00826 /// to show the different paths that one can take through the 00827 /// inheritance hierarchy to go from the derived class to different 00828 /// subobjects of a base class. The result looks something like this: 00829 /// @code 00830 /// struct D -> struct B -> struct A 00831 /// struct D -> struct C -> struct A 00832 /// @endcode 00833 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 00834 std::string PathDisplayStr; 00835 std::set<unsigned> DisplayedPaths; 00836 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 00837 Path != Paths.end(); ++Path) { 00838 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 00839 // We haven't displayed a path to this particular base 00840 // class subobject yet. 00841 PathDisplayStr += "\n "; 00842 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 00843 for (CXXBasePath::const_iterator Element = Path->begin(); 00844 Element != Path->end(); ++Element) 00845 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 00846 } 00847 } 00848 00849 return PathDisplayStr; 00850 } 00851 00852 //===----------------------------------------------------------------------===// 00853 // C++ class member Handling 00854 //===----------------------------------------------------------------------===// 00855 00856 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 00857 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 00858 /// bitfield width if there is one and 'InitExpr' specifies the initializer if 00859 /// any. 00860 Sema::DeclPtrTy 00861 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 00862 MultiTemplateParamsArg TemplateParameterLists, 00863 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 00864 bool Deleted) { 00865 const DeclSpec &DS = D.getDeclSpec(); 00866 DeclarationName Name = GetNameForDeclarator(D); 00867 Expr *BitWidth = static_cast<Expr*>(BW); 00868 Expr *Init = static_cast<Expr*>(InitExpr); 00869 SourceLocation Loc = D.getIdentifierLoc(); 00870 00871 bool isFunc = D.isFunctionDeclarator(); 00872 00873 assert(!DS.isFriendSpecified()); 00874 00875 // C++ 9.2p6: A member shall not be declared to have automatic storage 00876 // duration (auto, register) or with the extern storage-class-specifier. 00877 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 00878 // data members and cannot be applied to names declared const or static, 00879 // and cannot be applied to reference members. 00880 switch (DS.getStorageClassSpec()) { 00881 case DeclSpec::SCS_unspecified: 00882 case DeclSpec::SCS_typedef: 00883 case DeclSpec::SCS_static: 00884 // FALL THROUGH. 00885 break; 00886 case DeclSpec::SCS_mutable: 00887 if (isFunc) { 00888 if (DS.getStorageClassSpecLoc().isValid()) 00889 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 00890 else 00891 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 00892 00893 // FIXME: It would be nicer if the keyword was ignored only for this 00894 // declarator. Otherwise we could get follow-up errors. 00895 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00896 } else { 00897 QualType T = GetTypeForDeclarator(D, S); 00898 diag::kind err = static_cast<diag::kind>(0); 00899 if (T->isReferenceType()) 00900 err = diag::err_mutable_reference; 00901 else if (T.isConstQualified()) 00902 err = diag::err_mutable_const; 00903 if (err != 0) { 00904 if (DS.getStorageClassSpecLoc().isValid()) 00905 Diag(DS.getStorageClassSpecLoc(), err); 00906 else 00907 Diag(DS.getThreadSpecLoc(), err); 00908 // FIXME: It would be nicer if the keyword was ignored only for this 00909 // declarator. Otherwise we could get follow-up errors. 00910 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00911 } 00912 } 00913 break; 00914 default: 00915 if (DS.getStorageClassSpecLoc().isValid()) 00916 Diag(DS.getStorageClassSpecLoc(), 00917 diag::err_storageclass_invalid_for_member); 00918 else 00919 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 00920 D.getMutableDeclSpec().ClearStorageClassSpecs(); 00921 } 00922 00923 if (!isFunc && 00924 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 00925 D.getNumTypeObjects() == 0) { 00926 // Check also for this case: 00927 // 00928 // typedef int f(); 00929 // f a; 00930 // 00931 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 00932 isFunc = TDType->isFunctionType(); 00933 } 00934 00935 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 00936 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 00937 !isFunc); 00938 00939 Decl *Member; 00940 if (isInstField) { 00941 // FIXME: Check for template parameters! 00942 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 00943 AS); 00944 assert(Member && "HandleField never returns null"); 00945 } else { 00946 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 00947 .getAs<Decl>(); 00948 if (!Member) { 00949 if (BitWidth) DeleteExpr(BitWidth); 00950 return DeclPtrTy(); 00951 } 00952 00953 // Non-instance-fields can't have a bitfield. 00954 if (BitWidth) { 00955 if (Member->isInvalidDecl()) { 00956 // don't emit another diagnostic. 00957 } else if (isa<VarDecl>(Member)) { 00958 // C++ 9.6p3: A bit-field shall not be a static member. 00959 // "static member 'A' cannot be a bit-field" 00960 Diag(Loc, diag::err_static_not_bitfield) 00961 << Name << BitWidth->getSourceRange(); 00962 } else if (isa<TypedefDecl>(Member)) { 00963 // "typedef member 'x' cannot be a bit-field" 00964 Diag(Loc, diag::err_typedef_not_bitfield) 00965 << Name << BitWidth->getSourceRange(); 00966 } else { 00967 // A function typedef ("typedef int f(); f a;"). 00968 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 00969 Diag(Loc, diag::err_not_integral_type_bitfield) 00970 << Name << cast<ValueDecl>(Member)->getType() 00971 << BitWidth->getSourceRange(); 00972 } 00973 00974 DeleteExpr(BitWidth); 00975 BitWidth = 0; 00976 Member->setInvalidDecl(); 00977 } 00978 00979 Member->setAccess(AS); 00980 00981 // If we have declared a member function template, set the access of the 00982 // templated declaration as well. 00983 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 00984 FunTmpl->getTemplatedDecl()->setAccess(AS); 00985 } 00986 00987 assert((Name || isInstField) && "No identifier for non-field ?"); 00988 00989 if (Init) 00990 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 00991 if (Deleted) // FIXME: Source location is not very good. 00992 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 00993 00994 if (isInstField) { 00995 FieldCollector->Add(cast<FieldDecl>(Member)); 00996 return DeclPtrTy(); 00997 } 00998 return DeclPtrTy::make(Member); 00999 } 01000 01001 /// \brief Find the direct and/or virtual base specifiers that 01002 /// correspond to the given base type, for use in base initialization 01003 /// within a constructor. 01004 static bool FindBaseInitializer(Sema &SemaRef, 01005 CXXRecordDecl *ClassDecl, 01006 QualType BaseType, 01007 const CXXBaseSpecifier *&DirectBaseSpec, 01008 const CXXBaseSpecifier *&VirtualBaseSpec) { 01009 // First, check for a direct base class. 01010 DirectBaseSpec = 0; 01011 for (CXXRecordDecl::base_class_const_iterator Base 01012 = ClassDecl->bases_begin(); 01013 Base != ClassDecl->bases_end(); ++Base) { 01014 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 01015 // We found a direct base of this type. That's what we're 01016 // initializing. 01017 DirectBaseSpec = &*Base; 01018 break; 01019 } 01020 } 01021 01022 // Check for a virtual base class. 01023 // FIXME: We might be able to short-circuit this if we know in advance that 01024 // there are no virtual bases. 01025 VirtualBaseSpec = 0; 01026 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 01027 // We haven't found a base yet; search the class hierarchy for a 01028 // virtual base class. 01029 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 01030 /*DetectVirtual=*/false); 01031 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 01032 BaseType, Paths)) { 01033 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 01034 Path != Paths.end(); ++Path) { 01035 if (Path->back().Base->isVirtual()) { 01036 VirtualBaseSpec = Path->back().Base; 01037 break; 01038 } 01039 } 01040 } 01041 } 01042 01043 return DirectBaseSpec || VirtualBaseSpec; 01044 } 01045 01046 /// ActOnMemInitializer - Handle a C++ member initializer. 01047 Sema::MemInitResult 01048 Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 01049 Scope *S, 01050 CXXScopeSpec &SS, 01051 IdentifierInfo *MemberOrBase, 01052 TypeTy *TemplateTypeTy, 01053 SourceLocation IdLoc, 01054 SourceLocation LParenLoc, 01055 ExprTy **Args, unsigned NumArgs, 01056 SourceLocation *CommaLocs, 01057 SourceLocation RParenLoc) { 01058 if (!ConstructorD) 01059 return true; 01060 01061 AdjustDeclIfTemplate(ConstructorD); 01062 01063 CXXConstructorDecl *Constructor 01064 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 01065 if (!Constructor) { 01066 // The user wrote a constructor initializer on a function that is 01067 // not a C++ constructor. Ignore the error for now, because we may 01068 // have more member initializers coming; we'll diagnose it just 01069 // once in ActOnMemInitializers. 01070 return true; 01071 } 01072 01073 CXXRecordDecl *ClassDecl = Constructor->getParent(); 01074 01075 // C++ [class.base.init]p2: 01076 // Names in a mem-initializer-id are looked up in the scope of the 01077 // constructor’s class and, if not found in that scope, are looked 01078 // up in the scope containing the constructor’s 01079 // definition. [Note: if the constructor’s class contains a member 01080 // with the same name as a direct or virtual base class of the 01081 // class, a mem-initializer-id naming the member or base class and 01082 // composed of a single identifier refers to the class member. A 01083 // mem-initializer-id for the hidden base class may be specified 01084 // using a qualified name. ] 01085 if (!SS.getScopeRep() && !TemplateTypeTy) { 01086 // Look for a member, first. 01087 FieldDecl *Member = 0; 01088 DeclContext::lookup_result Result 01089 = ClassDecl->lookup(MemberOrBase); 01090 if (Result.first != Result.second) 01091 Member = dyn_cast<FieldDecl>(*Result.first); 01092 01093 // FIXME: Handle members of an anonymous union. 01094 01095 if (Member) 01096 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 01097 LParenLoc, RParenLoc); 01098 } 01099 // It didn't name a member, so see if it names a class. 01100 QualType BaseType; 01101 TypeSourceInfo *TInfo = 0; 01102 01103 if (TemplateTypeTy) { 01104 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 01105 } else { 01106 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 01107 LookupParsedName(R, S, &SS); 01108 01109 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 01110 if (!TyD) { 01111 if (R.isAmbiguous()) return true; 01112 01113 // We don't want access-control diagnostics here. 01114 R.suppressDiagnostics(); 01115 01116 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 01117 bool NotUnknownSpecialization = false; 01118 DeclContext *DC = computeDeclContext(SS, false); 01119 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 01120 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 01121 01122 if (!NotUnknownSpecialization) { 01123 // When the scope specifier can refer to a member of an unknown 01124 // specialization, we take it as a type name. 01125 BaseType = CheckTypenameType(ETK_None, 01126 (NestedNameSpecifier *)SS.getScopeRep(), 01127 *MemberOrBase, SS.getRange()); 01128 if (BaseType.isNull()) 01129 return true; 01130 01131 R.clear(); 01132 } 01133 } 01134 01135 // If no results were found, try to correct typos. 01136 if (R.empty() && BaseType.isNull() && 01137 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 01138 R.isSingleResult()) { 01139 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 01140 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 01141 // We have found a non-static data member with a similar 01142 // name to what was typed; complain and initialize that 01143 // member. 01144 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 01145 << MemberOrBase << true << R.getLookupName() 01146 << FixItHint::CreateReplacement(R.getNameLoc(), 01147 R.getLookupName().getAsString()); 01148 Diag(Member->getLocation(), diag::note_previous_decl) 01149 << Member->getDeclName(); 01150 01151 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 01152 LParenLoc, RParenLoc); 01153 } 01154 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 01155 const CXXBaseSpecifier *DirectBaseSpec; 01156 const CXXBaseSpecifier *VirtualBaseSpec; 01157 if (FindBaseInitializer(*this, ClassDecl, 01158 Context.getTypeDeclType(Type), 01159 DirectBaseSpec, VirtualBaseSpec)) { 01160 // We have found a direct or virtual base class with a 01161 // similar name to what was typed; complain and initialize 01162 // that base class. 01163 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 01164 << MemberOrBase << false << R.getLookupName() 01165 << FixItHint::CreateReplacement(R.getNameLoc(), 01166 R.getLookupName().getAsString()); 01167 01168 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 01169 : VirtualBaseSpec; 01170 Diag(BaseSpec->getSourceRange().getBegin(), 01171 diag::note_base_class_specified_here) 01172 << BaseSpec->getType() 01173 << BaseSpec->getSourceRange(); 01174 01175 TyD = Type; 01176 } 01177 } 01178 } 01179 01180 if (!TyD && BaseType.isNull()) { 01181 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 01182 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 01183 return true; 01184 } 01185 } 01186 01187 if (BaseType.isNull()) { 01188 BaseType = Context.getTypeDeclType(TyD); 01189 if (SS.isSet()) { 01190 NestedNameSpecifier *Qualifier = 01191 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 01192 01193 // FIXME: preserve source range information 01194 BaseType = Context.getQualifiedNameType(Qualifier, BaseType); 01195 } 01196 } 01197 } 01198 01199 if (!TInfo) 01200 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 01201 01202 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 01203 LParenLoc, RParenLoc, ClassDecl); 01204 } 01205 01206 /// Checks an initializer expression for use of uninitialized fields, such as 01207 /// containing the field that is being initialized. Returns true if there is an 01208 /// uninitialized field was used an updates the SourceLocation parameter; false 01209 /// otherwise. 01210 static bool InitExprContainsUninitializedFields(const Stmt* S, 01211 const FieldDecl* LhsField, 01212 SourceLocation* L) { 01213 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 01214 if (ME) { 01215 const NamedDecl* RhsField = ME->getMemberDecl(); 01216 if (RhsField == LhsField) { 01217 // Initializing a field with itself. Throw a warning. 01218 // But wait; there are exceptions! 01219 // Exception #1: The field may not belong to this record. 01220 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 01221 const Expr* base = ME->getBase(); 01222 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 01223 // Even though the field matches, it does not belong to this record. 01224 return false; 01225 } 01226 // None of the exceptions triggered; return true to indicate an 01227 // uninitialized field was used. 01228 *L = ME->getMemberLoc(); 01229 return true; 01230 } 01231 } 01232 bool found = false; 01233 for (Stmt::const_child_iterator it = S->child_begin(); 01234 it != S->child_end() && found == false; 01235 ++it) { 01236 if (isa<CallExpr>(S)) { 01237 // Do not descend into function calls or constructors, as the use 01238 // of an uninitialized field may be valid. One would have to inspect 01239 // the contents of the function/ctor to determine if it is safe or not. 01240 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 01241 // may be safe, depending on what the function/ctor does. 01242 continue; 01243 } 01244 found = InitExprContainsUninitializedFields(*it, LhsField, L); 01245 } 01246 return found; 01247 } 01248 01249 Sema::MemInitResult 01250 Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 01251 unsigned NumArgs, SourceLocation IdLoc, 01252 SourceLocation LParenLoc, 01253 SourceLocation RParenLoc) { 01254 // Diagnose value-uses of fields to initialize themselves, e.g. 01255 // foo(foo) 01256 // where foo is not also a parameter to the constructor. 01257 // TODO: implement -Wuninitialized and fold this into that framework. 01258 for (unsigned i = 0; i < NumArgs; ++i) { 01259 SourceLocation L; 01260 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 01261 // FIXME: Return true in the case when other fields are used before being 01262 // uninitialized. For example, let this field be the i'th field. When 01263 // initializing the i'th field, throw a warning if any of the >= i'th 01264 // fields are used, as they are not yet initialized. 01265 // Right now we are only handling the case where the i'th field uses 01266 // itself in its initializer. 01267 Diag(L, diag::warn_field_is_uninit); 01268 } 01269 } 01270 01271 bool HasDependentArg = false; 01272 for (unsigned i = 0; i < NumArgs; i++) 01273 HasDependentArg |= Args[i]->isTypeDependent(); 01274 01275 QualType FieldType = Member->getType(); 01276 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 01277 FieldType = Array->getElementType(); 01278 if (FieldType->isDependentType() || HasDependentArg) { 01279 // Can't check initialization for a member of dependent type or when 01280 // any of the arguments are type-dependent expressions. 01281 OwningExprResult Init 01282 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01283 RParenLoc)); 01284 01285 // Erase any temporaries within this evaluation context; we're not 01286 // going to track them in the AST, since we'll be rebuilding the 01287 // ASTs during template instantiation. 01288 ExprTemporaries.erase( 01289 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 01290 ExprTemporaries.end()); 01291 01292 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01293 LParenLoc, 01294 Init.takeAs<Expr>(), 01295 RParenLoc); 01296 01297 } 01298 01299 if (Member->isInvalidDecl()) 01300 return true; 01301 01302 // Initialize the member. 01303 InitializedEntity MemberEntity = 01304 InitializedEntity::InitializeMember(Member, 0); 01305 InitializationKind Kind = 01306 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 01307 01308 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 01309 01310 OwningExprResult MemberInit = 01311 InitSeq.Perform(*this, MemberEntity, Kind, 01312 MultiExprArg(*this, (void**)Args, NumArgs), 0); 01313 if (MemberInit.isInvalid()) 01314 return true; 01315 01316 // C++0x [class.base.init]p7: 01317 // The initialization of each base and member constitutes a 01318 // full-expression. 01319 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 01320 if (MemberInit.isInvalid()) 01321 return true; 01322 01323 // If we are in a dependent context, template instantiation will 01324 // perform this type-checking again. Just save the arguments that we 01325 // received in a ParenListExpr. 01326 // FIXME: This isn't quite ideal, since our ASTs don't capture all 01327 // of the information that we have about the member 01328 // initializer. However, deconstructing the ASTs is a dicey process, 01329 // and this approach is far more likely to get the corner cases right. 01330 if (CurContext->isDependentContext()) { 01331 // Bump the reference count of all of the arguments. 01332 for (unsigned I = 0; I != NumArgs; ++I) 01333 Args[I]->Retain(); 01334 01335 OwningExprResult Init 01336 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01337 RParenLoc)); 01338 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01339 LParenLoc, 01340 Init.takeAs<Expr>(), 01341 RParenLoc); 01342 } 01343 01344 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 01345 LParenLoc, 01346 MemberInit.takeAs<Expr>(), 01347 RParenLoc); 01348 } 01349 01350 Sema::MemInitResult 01351 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 01352 Expr **Args, unsigned NumArgs, 01353 SourceLocation LParenLoc, SourceLocation RParenLoc, 01354 CXXRecordDecl *ClassDecl) { 01355 bool HasDependentArg = false; 01356 for (unsigned i = 0; i < NumArgs; i++) 01357 HasDependentArg |= Args[i]->isTypeDependent(); 01358 01359 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin(); 01360 if (BaseType->isDependentType() || HasDependentArg) { 01361 // Can't check initialization for a base of dependent type or when 01362 // any of the arguments are type-dependent expressions. 01363 OwningExprResult BaseInit 01364 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01365 RParenLoc)); 01366 01367 // Erase any temporaries within this evaluation context; we're not 01368 // going to track them in the AST, since we'll be rebuilding the 01369 // ASTs during template instantiation. 01370 ExprTemporaries.erase( 01371 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 01372 ExprTemporaries.end()); 01373 01374 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01375 /*IsVirtual=*/false, 01376 LParenLoc, 01377 BaseInit.takeAs<Expr>(), 01378 RParenLoc); 01379 } 01380 01381 if (!BaseType->isRecordType()) 01382 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 01383 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 01384 01385 // C++ [class.base.init]p2: 01386 // [...] Unless the mem-initializer-id names a nonstatic data 01387 // member of the constructor’s class or a direct or virtual base 01388 // of that class, the mem-initializer is ill-formed. A 01389 // mem-initializer-list can initialize a base class using any 01390 // name that denotes that base class type. 01391 01392 // Check for direct and virtual base classes. 01393 const CXXBaseSpecifier *DirectBaseSpec = 0; 01394 const CXXBaseSpecifier *VirtualBaseSpec = 0; 01395 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 01396 VirtualBaseSpec); 01397 01398 // C++ [base.class.init]p2: 01399 // If a mem-initializer-id is ambiguous because it designates both 01400 // a direct non-virtual base class and an inherited virtual base 01401 // class, the mem-initializer is ill-formed. 01402 if (DirectBaseSpec && VirtualBaseSpec) 01403 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 01404 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 01405 // C++ [base.class.init]p2: 01406 // Unless the mem-initializer-id names a nonstatic data membeer of the 01407 // constructor's class ot a direst or virtual base of that class, the 01408 // mem-initializer is ill-formed. 01409 if (!DirectBaseSpec && !VirtualBaseSpec) 01410 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 01411 << BaseType << Context.getTypeDeclType(ClassDecl) 01412 << BaseTInfo->getTypeLoc().getSourceRange(); 01413 01414 CXXBaseSpecifier *BaseSpec 01415 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 01416 if (!BaseSpec) 01417 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 01418 01419 // Initialize the base. 01420 InitializedEntity BaseEntity = 01421 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 01422 InitializationKind Kind = 01423 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 01424 01425 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 01426 01427 OwningExprResult BaseInit = 01428 InitSeq.Perform(*this, BaseEntity, Kind, 01429 MultiExprArg(*this, (void**)Args, NumArgs), 0); 01430 if (BaseInit.isInvalid()) 01431 return true; 01432 01433 // C++0x [class.base.init]p7: 01434 // The initialization of each base and member constitutes a 01435 // full-expression. 01436 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 01437 if (BaseInit.isInvalid()) 01438 return true; 01439 01440 // If we are in a dependent context, template instantiation will 01441 // perform this type-checking again. Just save the arguments that we 01442 // received in a ParenListExpr. 01443 // FIXME: This isn't quite ideal, since our ASTs don't capture all 01444 // of the information that we have about the base 01445 // initializer. However, deconstructing the ASTs is a dicey process, 01446 // and this approach is far more likely to get the corner cases right. 01447 if (CurContext->isDependentContext()) { 01448 // Bump the reference count of all of the arguments. 01449 for (unsigned I = 0; I != NumArgs; ++I) 01450 Args[I]->Retain(); 01451 01452 OwningExprResult Init 01453 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 01454 RParenLoc)); 01455 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01456 BaseSpec->isVirtual(), 01457 LParenLoc, 01458 Init.takeAs<Expr>(), 01459 RParenLoc); 01460 } 01461 01462 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 01463 BaseSpec->isVirtual(), 01464 LParenLoc, 01465 BaseInit.takeAs<Expr>(), 01466 RParenLoc); 01467 } 01468 01469 /// ImplicitInitializerKind - How an implicit base or member initializer should 01470 /// initialize its base or member. 01471 enum ImplicitInitializerKind { 01472 IIK_Default, 01473 IIK_Copy, 01474 IIK_Move 01475 }; 01476 01477 static bool 01478 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 01479 ImplicitInitializerKind ImplicitInitKind, 01480 CXXBaseSpecifier *BaseSpec, 01481 bool IsInheritedVirtualBase, 01482 CXXBaseOrMemberInitializer *&CXXBaseInit) { 01483 InitializedEntity InitEntity 01484 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 01485 IsInheritedVirtualBase); 01486 01487 Sema::OwningExprResult BaseInit(SemaRef); 01488 01489 switch (ImplicitInitKind) { 01490 case IIK_Default: { 01491 InitializationKind InitKind 01492 = InitializationKind::CreateDefault(Constructor->getLocation()); 01493 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 01494 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 01495 Sema::MultiExprArg(SemaRef, 0, 0)); 01496 break; 01497 } 01498 01499 case IIK_Copy: { 01500 ParmVarDecl *Param = Constructor->getParamDecl(0); 01501 QualType ParamType = Param->getType().getNonReferenceType(); 01502 01503 Expr *CopyCtorArg = 01504 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 01505 Constructor->getLocation(), ParamType, 0); 01506 01507 // Cast to the base class to avoid ambiguities. 01508 QualType ArgTy = 01509 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 01510 ParamType.getQualifiers()); 01511 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 01512 CastExpr::CK_UncheckedDerivedToBase, 01513 /*isLvalue=*/true, 01514 CXXBaseSpecifierArray(BaseSpec)); 01515 01516 InitializationKind InitKind 01517 = InitializationKind::CreateDirect(Constructor->getLocation(), 01518 SourceLocation(), SourceLocation()); 01519 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 01520 &CopyCtorArg, 1); 01521 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 01522 Sema::MultiExprArg(SemaRef, 01523 (void**)&CopyCtorArg, 1)); 01524 break; 01525 } 01526 01527 case IIK_Move: 01528 assert(false && "Unhandled initializer kind!"); 01529 } 01530 01531 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 01532 if (BaseInit.isInvalid()) 01533 return true; 01534 01535 CXXBaseInit = 01536 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 01537 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 01538 SourceLocation()), 01539 BaseSpec->isVirtual(), 01540 SourceLocation(), 01541 BaseInit.takeAs<Expr>(), 01542 SourceLocation()); 01543 01544 return false; 01545 } 01546 01547 static bool 01548 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 01549 ImplicitInitializerKind ImplicitInitKind, 01550 FieldDecl *Field, 01551 CXXBaseOrMemberInitializer *&CXXMemberInit) { 01552 if (ImplicitInitKind == IIK_Copy) { 01553 SourceLocation Loc = Constructor->getLocation(); 01554 ParmVarDecl *Param = Constructor->getParamDecl(0); 01555 QualType ParamType = Param->getType().getNonReferenceType(); 01556 01557 Expr *MemberExprBase = 01558 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 01559 Loc, ParamType, 0); 01560 01561 // Build a reference to this field within the parameter. 01562 CXXScopeSpec SS; 01563 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 01564 Sema::LookupMemberName); 01565 MemberLookup.addDecl(Field, AS_public); 01566 MemberLookup.resolveKind(); 01567 Sema::OwningExprResult CopyCtorArg 01568 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase), 01569 ParamType, Loc, 01570 /*IsArrow=*/false, 01571 SS, 01572 /*FirstQualifierInScope=*/0, 01573 MemberLookup, 01574 /*TemplateArgs=*/0); 01575 if (CopyCtorArg.isInvalid()) 01576 return true; 01577 01578 // When the field we are copying is an array, create index variables for 01579 // each dimension of the array. We use these index variables to subscript 01580 // the source array, and other clients (e.g., CodeGen) will perform the 01581 // necessary iteration with these index variables. 01582 llvm::SmallVector<VarDecl *, 4> IndexVariables; 01583 QualType BaseType = Field->getType(); 01584 QualType SizeType = SemaRef.Context.getSizeType(); 01585 while (const ConstantArrayType *Array 01586 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 01587 // Create the iteration variable for this array index. 01588 IdentifierInfo *IterationVarName = 0; 01589 { 01590 llvm::SmallString<8> Str; 01591 llvm::raw_svector_ostream OS(Str); 01592 OS << "__i" << IndexVariables.size(); 01593 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 01594 } 01595 VarDecl *IterationVar 01596 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, 01597 IterationVarName, SizeType, 01598 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 01599 VarDecl::None, VarDecl::None); 01600 IndexVariables.push_back(IterationVar); 01601 01602 // Create a reference to the iteration variable. 01603 Sema::OwningExprResult IterationVarRef 01604 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc); 01605 assert(!IterationVarRef.isInvalid() && 01606 "Reference to invented variable cannot fail!"); 01607 01608 // Subscript the array with this iteration variable. 01609 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg), 01610 Loc, 01611 move(IterationVarRef), 01612 Loc); 01613 if (CopyCtorArg.isInvalid()) 01614 return true; 01615 01616 BaseType = Array->getElementType(); 01617 } 01618 01619 // Construct the entity that we will be initializing. For an array, this 01620 // will be first element in the array, which may require several levels 01621 // of array-subscript entities. 01622 llvm::SmallVector<InitializedEntity, 4> Entities; 01623 Entities.reserve(1 + IndexVariables.size()); 01624 Entities.push_back(InitializedEntity::InitializeMember(Field)); 01625 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 01626 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 01627 0, 01628 Entities.back())); 01629 01630 // Direct-initialize to use the copy constructor. 01631 InitializationKind InitKind = 01632 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 01633 01634 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 01635 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 01636 &CopyCtorArgE, 1); 01637 01638 Sema::OwningExprResult MemberInit 01639 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 01640 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1)); 01641 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 01642 if (MemberInit.isInvalid()) 01643 return true; 01644 01645 CXXMemberInit 01646 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc, 01647 MemberInit.takeAs<Expr>(), Loc, 01648 IndexVariables.data(), 01649 IndexVariables.size()); 01650 return false; 01651 } 01652 01653 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 01654 01655 QualType FieldBaseElementType = 01656 SemaRef.Context.getBaseElementType(Field->getType()); 01657 01658 if (FieldBaseElementType->isRecordType()) { 01659 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 01660 InitializationKind InitKind = 01661 InitializationKind::CreateDefault(Constructor->getLocation()); 01662 01663 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 01664 Sema::OwningExprResult MemberInit = 01665 InitSeq.Perform(SemaRef, InitEntity, InitKind, 01666 Sema::MultiExprArg(SemaRef, 0, 0)); 01667 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 01668 if (MemberInit.isInvalid()) 01669 return true; 01670 01671 CXXMemberInit = 01672 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 01673 Field, SourceLocation(), 01674 SourceLocation(), 01675 MemberInit.takeAs<Expr>(), 01676 SourceLocation()); 01677 return false; 01678 } 01679 01680 if (FieldBaseElementType->isReferenceType()) { 01681 SemaRef.Diag(Constructor->getLocation(), 01682 diag::err_uninitialized_member_in_ctor) 01683 << (int)Constructor->isImplicit() 01684 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 01685 << 0 << Field->getDeclName(); 01686 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 01687 return true; 01688 } 01689 01690 if (FieldBaseElementType.isConstQualified()) { 01691 SemaRef.Diag(Constructor->getLocation(), 01692 diag::err_uninitialized_member_in_ctor) 01693 << (int)Constructor->isImplicit() 01694 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 01695 << 1 << Field->getDeclName(); 01696 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 01697 return true; 01698 } 01699 01700 // Nothing to initialize. 01701 CXXMemberInit = 0; 01702 return false; 01703 } 01704 01705 bool 01706 Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 01707 CXXBaseOrMemberInitializer **Initializers, 01708 unsigned NumInitializers, 01709 bool AnyErrors) { 01710 if (Constructor->getDeclContext()->isDependentContext()) { 01711 // Just store the initializers as written, they will be checked during 01712 // instantiation. 01713 if (NumInitializers > 0) { 01714 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 01715 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 01716 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 01717 memcpy(baseOrMemberInitializers, Initializers, 01718 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 01719 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 01720 } 01721 01722 return false; 01723 } 01724 01725 ImplicitInitializerKind ImplicitInitKind = IIK_Default; 01726 01727 // FIXME: Handle implicit move constructors. 01728 if (Constructor->isImplicit() && Constructor->isCopyConstructor()) 01729 ImplicitInitKind = IIK_Copy; 01730 01731 // We need to build the initializer AST according to order of construction 01732 // and not what user specified in the Initializers list. 01733 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 01734 if (!ClassDecl) 01735 return true; 01736 01737 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 01738 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 01739 bool HadError = false; 01740 01741 for (unsigned i = 0; i < NumInitializers; i++) { 01742 CXXBaseOrMemberInitializer *Member = Initializers[i]; 01743 01744 if (Member->isBaseInitializer()) 01745 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 01746 else 01747 AllBaseFields[Member->getMember()] = Member; 01748 } 01749 01750 // Keep track of the direct virtual bases. 01751 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 01752 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 01753 E = ClassDecl->bases_end(); I != E; ++I) { 01754 if (I->isVirtual()) 01755 DirectVBases.insert(I); 01756 } 01757 01758 // Push virtual bases before others. 01759 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 01760 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 01761 01762 if (CXXBaseOrMemberInitializer *Value 01763 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 01764 AllToInit.push_back(Value); 01765 } else if (!AnyErrors) { 01766 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 01767 CXXBaseOrMemberInitializer *CXXBaseInit; 01768 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind, 01769 VBase, IsInheritedVirtualBase, 01770 CXXBaseInit)) { 01771 HadError = true; 01772 continue; 01773 } 01774 01775 AllToInit.push_back(CXXBaseInit); 01776 } 01777 } 01778 01779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 01780 E = ClassDecl->bases_end(); Base != E; ++Base) { 01781 // Virtuals are in the virtual base list and already constructed. 01782 if (Base->isVirtual()) 01783 continue; 01784 01785 if (CXXBaseOrMemberInitializer *Value 01786 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 01787 AllToInit.push_back(Value); 01788 } else if (!AnyErrors) { 01789 CXXBaseOrMemberInitializer *CXXBaseInit; 01790 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind, 01791 Base, /*IsInheritedVirtualBase=*/false, 01792 CXXBaseInit)) { 01793 HadError = true; 01794 continue; 01795 } 01796 01797 AllToInit.push_back(CXXBaseInit); 01798 } 01799 } 01800 01801 // non-static data members. 01802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 01803 E = ClassDecl->field_end(); Field != E; ++Field) { 01804 if ((*Field)->isAnonymousStructOrUnion()) { 01805 if (const RecordType *FieldClassType = 01806 Field->getType()->getAs<RecordType>()) { 01807 CXXRecordDecl *FieldClassDecl 01808 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 01809 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 01810 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 01811 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 01812 // 'Member' is the anonymous union field and 'AnonUnionMember' is 01813 // set to the anonymous union data member used in the initializer 01814 // list. 01815 Value->setMember(*Field); 01816 Value->setAnonUnionMember(*FA); 01817 AllToInit.push_back(Value); 01818 break; 01819 } 01820 } 01821 } 01822 01823 if (ImplicitInitKind == IIK_Default) 01824 continue; 01825 } 01826 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 01827 AllToInit.push_back(Value); 01828 continue; 01829 } 01830 01831 if (AnyErrors) 01832 continue; 01833 01834 CXXBaseOrMemberInitializer *Member; 01835 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind, 01836 *Field, Member)) { 01837 HadError = true; 01838 continue; 01839 } 01840 01841 // If the member doesn't need to be initialized, it will be null. 01842 if (Member) 01843 AllToInit.push_back(Member); 01844 } 01845 01846 NumInitializers = AllToInit.size(); 01847 if (NumInitializers > 0) { 01848 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 01849 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 01850 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 01851 memcpy(baseOrMemberInitializers, AllToInit.data(), 01852 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 01853 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 01854 01855 // Constructors implicitly reference the base and member 01856 // destructors. 01857 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 01858 Constructor->getParent()); 01859 } 01860 01861 return HadError; 01862 } 01863 01864 static void *GetKeyForTopLevelField(FieldDecl *Field) { 01865 // For anonymous unions, use the class declaration as the key. 01866 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 01867 if (RT->getDecl()->isAnonymousStructOrUnion()) 01868 return static_cast<void *>(RT->getDecl()); 01869 } 01870 return static_cast<void *>(Field); 01871 } 01872 01873 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 01874 return Context.getCanonicalType(BaseType).getTypePtr(); 01875 } 01876 01877 static void *GetKeyForMember(ASTContext &Context, 01878 CXXBaseOrMemberInitializer *Member, 01879 bool MemberMaybeAnon = false) { 01880 if (!Member->isMemberInitializer()) 01881 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 01882 01883 // For fields injected into the class via declaration of an anonymous union, 01884 // use its anonymous union class declaration as the unique key. 01885 FieldDecl *Field = Member->getMember(); 01886 01887 // After SetBaseOrMemberInitializers call, Field is the anonymous union 01888 // data member of the class. Data member used in the initializer list is 01889 // in AnonUnionMember field. 01890 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 01891 Field = Member->getAnonUnionMember(); 01892 01893 // If the field is a member of an anonymous struct or union, our key 01894 // is the anonymous record decl that's a direct child of the class. 01895 RecordDecl *RD = Field->getParent(); 01896 if (RD->isAnonymousStructOrUnion()) { 01897 while (true) { 01898 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 01899 if (Parent->isAnonymousStructOrUnion()) 01900 RD = Parent; 01901 else 01902 break; 01903 } 01904 01905 return static_cast<void *>(RD); 01906 } 01907 01908 return static_cast<void *>(Field); 01909 } 01910 01911 static void 01912 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 01913 const CXXConstructorDecl *Constructor, 01914 CXXBaseOrMemberInitializer **Inits, 01915 unsigned NumInits) { 01916 if (Constructor->getDeclContext()->isDependentContext()) 01917 return; 01918 01919 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order) 01920 == Diagnostic::Ignored) 01921 return; 01922 01923 // Build the list of bases and members in the order that they'll 01924 // actually be initialized. The explicit initializers should be in 01925 // this same order but may be missing things. 01926 llvm::SmallVector<const void*, 32> IdealInitKeys; 01927 01928 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 01929 01930 // 1. Virtual bases. 01931 for (CXXRecordDecl::base_class_const_iterator VBase = 01932 ClassDecl->vbases_begin(), 01933 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 01934 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 01935 01936 // 2. Non-virtual bases. 01937 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 01938 E = ClassDecl->bases_end(); Base != E; ++Base) { 01939 if (Base->isVirtual()) 01940 continue; 01941 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 01942 } 01943 01944 // 3. Direct fields. 01945 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 01946 E = ClassDecl->field_end(); Field != E; ++Field) 01947 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 01948 01949 unsigned NumIdealInits = IdealInitKeys.size(); 01950 unsigned IdealIndex = 0; 01951 01952 CXXBaseOrMemberInitializer *PrevInit = 0; 01953 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 01954 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 01955 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true); 01956 01957 // Scan forward to try to find this initializer in the idealized 01958 // initializers list. 01959 for (; IdealIndex != NumIdealInits; ++IdealIndex) 01960 if (InitKey == IdealInitKeys[IdealIndex]) 01961 break; 01962 01963 // If we didn't find this initializer, it must be because we 01964 // scanned past it on a previous iteration. That can only 01965 // happen if we're out of order; emit a warning. 01966 if (IdealIndex == NumIdealInits) { 01967 assert(PrevInit && "initializer not found in initializer list"); 01968 01969 Sema::SemaDiagnosticBuilder D = 01970 SemaRef.Diag(PrevInit->getSourceLocation(), 01971 diag::warn_initializer_out_of_order); 01972 01973 if (PrevInit->isMemberInitializer()) 01974 D << 0 << PrevInit->getMember()->getDeclName(); 01975 else 01976 D << 1 << PrevInit->getBaseClassInfo()->getType(); 01977 01978 if (Init->isMemberInitializer()) 01979 D << 0 << Init->getMember()->getDeclName(); 01980 else 01981 D << 1 << Init->getBaseClassInfo()->getType(); 01982 01983 // Move back to the initializer's location in the ideal list. 01984 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 01985 if (InitKey == IdealInitKeys[IdealIndex]) 01986 break; 01987 01988 assert(IdealIndex != NumIdealInits && 01989 "initializer not found in initializer list"); 01990 } 01991 01992 PrevInit = Init; 01993 } 01994 } 01995 01996 namespace { 01997 bool CheckRedundantInit(Sema &S, 01998 CXXBaseOrMemberInitializer *Init, 01999 CXXBaseOrMemberInitializer *&PrevInit) { 02000 if (!PrevInit) { 02001 PrevInit = Init; 02002 return false; 02003 } 02004 02005 if (FieldDecl *Field = Init->getMember()) 02006 S.Diag(Init->getSourceLocation(), 02007 diag::err_multiple_mem_initialization) 02008 << Field->getDeclName() 02009 << Init->getSourceRange(); 02010 else { 02011 Type *BaseClass = Init->getBaseClass(); 02012 assert(BaseClass && "neither field nor base"); 02013 S.Diag(Init->getSourceLocation(), 02014 diag::err_multiple_base_initialization) 02015 << QualType(BaseClass, 0) 02016 << Init->getSourceRange(); 02017 } 02018 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 02019 << 0 << PrevInit->getSourceRange(); 02020 02021 return true; 02022 } 02023 02024 typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry; 02025 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 02026 02027 bool CheckRedundantUnionInit(Sema &S, 02028 CXXBaseOrMemberInitializer *Init, 02029 RedundantUnionMap &Unions) { 02030 FieldDecl *Field = Init->getMember(); 02031 RecordDecl *Parent = Field->getParent(); 02032 if (!Parent->isAnonymousStructOrUnion()) 02033 return false; 02034 02035 NamedDecl *Child = Field; 02036 do { 02037 if (Parent->isUnion()) { 02038 UnionEntry &En = Unions[Parent]; 02039 if (En.first && En.first != Child) { 02040 S.Diag(Init->getSourceLocation(), 02041 diag::err_multiple_mem_union_initialization) 02042 << Field->getDeclName() 02043 << Init->getSourceRange(); 02044 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 02045 << 0 << En.second->getSourceRange(); 02046 return true; 02047 } else if (!En.first) { 02048 En.first = Child; 02049 En.second = Init; 02050 } 02051 } 02052 02053 Child = Parent; 02054 Parent = cast<RecordDecl>(Parent->getDeclContext()); 02055 } while (Parent->isAnonymousStructOrUnion()); 02056 02057 return false; 02058 } 02059 } 02060 02061 /// ActOnMemInitializers - Handle the member initializers for a constructor. 02062 void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 02063 SourceLocation ColonLoc, 02064 MemInitTy **meminits, unsigned NumMemInits, 02065 bool AnyErrors) { 02066 if (!ConstructorDecl) 02067 return; 02068 02069 AdjustDeclIfTemplate(ConstructorDecl); 02070 02071 CXXConstructorDecl *Constructor 02072 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 02073 02074 if (!Constructor) { 02075 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 02076 return; 02077 } 02078 02079 CXXBaseOrMemberInitializer **MemInits = 02080 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 02081 02082 // Mapping for the duplicate initializers check. 02083 // For member initializers, this is keyed with a FieldDecl*. 02084 // For base initializers, this is keyed with a Type*. 02085 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 02086 02087 // Mapping for the inconsistent anonymous-union initializers check. 02088 RedundantUnionMap MemberUnions; 02089 02090 bool HadError = false; 02091 for (unsigned i = 0; i < NumMemInits; i++) { 02092 CXXBaseOrMemberInitializer *Init = MemInits[i]; 02093 02094 if (Init->isMemberInitializer()) { 02095 FieldDecl *Field = Init->getMember(); 02096 if (CheckRedundantInit(*this, Init, Members[Field]) || 02097 CheckRedundantUnionInit(*this, Init, MemberUnions)) 02098 HadError = true; 02099 } else { 02100 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 02101 if (CheckRedundantInit(*this, Init, Members[Key])) 02102 HadError = true; 02103 } 02104 } 02105 02106 if (HadError) 02107 return; 02108 02109 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 02110 02111 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 02112 } 02113 02114 void 02115 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 02116 CXXRecordDecl *ClassDecl) { 02117 // Ignore dependent contexts. 02118 if (ClassDecl->isDependentContext()) 02119 return; 02120 02121 // FIXME: all the access-control diagnostics are positioned on the 02122 // field/base declaration. That's probably good; that said, the 02123 // user might reasonably want to know why the destructor is being 02124 // emitted, and we currently don't say. 02125 02126 // Non-static data members. 02127 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 02128 E = ClassDecl->field_end(); I != E; ++I) { 02129 FieldDecl *Field = *I; 02130 02131 QualType FieldType = Context.getBaseElementType(Field->getType()); 02132 02133 const RecordType* RT = FieldType->getAs<RecordType>(); 02134 if (!RT) 02135 continue; 02136 02137 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 02138 if (FieldClassDecl->hasTrivialDestructor()) 02139 continue; 02140 02141 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 02142 CheckDestructorAccess(Field->getLocation(), Dtor, 02143 PDiag(diag::err_access_dtor_field) 02144 << Field->getDeclName() 02145 << FieldType); 02146 02147 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 02148 } 02149 02150 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 02151 02152 // Bases. 02153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 02154 E = ClassDecl->bases_end(); Base != E; ++Base) { 02155 // Bases are always records in a well-formed non-dependent class. 02156 const RecordType *RT = Base->getType()->getAs<RecordType>(); 02157 02158 // Remember direct virtual bases. 02159 if (Base->isVirtual()) 02160 DirectVirtualBases.insert(RT); 02161 02162 // Ignore trivial destructors. 02163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 02164 if (BaseClassDecl->hasTrivialDestructor()) 02165 continue; 02166 02167 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 02168 02169 // FIXME: caret should be on the start of the class name 02170 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 02171 PDiag(diag::err_access_dtor_base) 02172 << Base->getType() 02173 << Base->getSourceRange()); 02174 02175 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 02176 } 02177 02178 // Virtual bases. 02179 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 02180 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 02181 02182 // Bases are always records in a well-formed non-dependent class. 02183 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 02184 02185 // Ignore direct virtual bases. 02186 if (DirectVirtualBases.count(RT)) 02187 continue; 02188 02189 // Ignore trivial destructors. 02190 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 02191 if (BaseClassDecl->hasTrivialDestructor()) 02192 continue; 02193 02194 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 02195 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 02196 PDiag(diag::err_access_dtor_vbase) 02197 << VBase->getType()); 02198 02199 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 02200 } 02201 } 02202 02203 void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 02204 if (!CDtorDecl) 02205 return; 02206 02207 if (CXXConstructorDecl *Constructor 02208 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 02209 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 02210 } 02211 02212 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 02213 unsigned DiagID, AbstractDiagSelID SelID, 02214 const CXXRecordDecl *CurrentRD) { 02215 if (SelID == -1) 02216 return RequireNonAbstractType(Loc, T, 02217 PDiag(DiagID), CurrentRD); 02218 else 02219 return RequireNonAbstractType(Loc, T, 02220 PDiag(DiagID) << SelID, CurrentRD); 02221 } 02222 02223 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 02224 const PartialDiagnostic &PD, 02225 const CXXRecordDecl *CurrentRD) { 02226 if (!getLangOptions().CPlusPlus) 02227 return false; 02228 02229 if (const ArrayType *AT = Context.getAsArrayType(T)) 02230 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 02231 CurrentRD); 02232 02233 if (const PointerType *PT = T->getAs<PointerType>()) { 02234 // Find the innermost pointer type. 02235 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 02236 PT = T; 02237 02238 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 02239 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 02240 } 02241 02242 const RecordType *RT = T->getAs<RecordType>(); 02243 if (!RT) 02244 return false; 02245 02246 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 02247 02248 if (CurrentRD && CurrentRD != RD) 02249 return false; 02250 02251 // FIXME: is this reasonable? It matches current behavior, but.... 02252 if (!RD->getDefinition()) 02253 return false; 02254 02255 if (!RD->isAbstract()) 02256 return false; 02257 02258 Diag(Loc, PD) << RD->getDeclName(); 02259 02260 // Check if we've already emitted the list of pure virtual functions for this 02261 // class. 02262 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 02263 return true; 02264 02265 CXXFinalOverriderMap FinalOverriders; 02266 RD->getFinalOverriders(FinalOverriders); 02267 02268 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 02269 MEnd = FinalOverriders.end(); 02270 M != MEnd; 02271 ++M) { 02272 for (OverridingMethods::iterator SO = M->second.begin(), 02273 SOEnd = M->second.end(); 02274 SO != SOEnd; ++SO) { 02275 // C++ [class.abstract]p4: 02276 // A class is abstract if it contains or inherits at least one 02277 // pure virtual function for which the final overrider is pure 02278 // virtual. 02279 02280 // 02281 if (SO->second.size() != 1) 02282 continue; 02283 02284 if (!SO->second.front().Method->isPure()) 02285 continue; 02286 02287 Diag(SO->second.front().Method->getLocation(), 02288 diag::note_pure_virtual_function) 02289 << SO->second.front().Method->getDeclName(); 02290 } 02291 } 02292 02293 if (!PureVirtualClassDiagSet) 02294 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 02295 PureVirtualClassDiagSet->insert(RD); 02296 02297 return true; 02298 } 02299 02300 namespace { 02301 class AbstractClassUsageDiagnoser 02302 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 02303 Sema &SemaRef; 02304 CXXRecordDecl *AbstractClass; 02305 02306 bool VisitDeclContext(const DeclContext *DC) { 02307 bool Invalid = false; 02308 02309 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 02310 E = DC->decls_end(); I != E; ++I) 02311 Invalid |= Visit(*I); 02312 02313 return Invalid; 02314 } 02315 02316 public: 02317 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 02318 : SemaRef(SemaRef), AbstractClass(ac) { 02319 Visit(SemaRef.Context.getTranslationUnitDecl()); 02320 } 02321 02322 bool VisitFunctionDecl(const FunctionDecl *FD) { 02323 if (FD->isThisDeclarationADefinition()) { 02324 // No need to do the check if we're in a definition, because it requires 02325 // that the return/param types are complete. 02326 // because that requires 02327 return VisitDeclContext(FD); 02328 } 02329 02330 // Check the return type. 02331 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 02332 bool Invalid = 02333 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 02334 diag::err_abstract_type_in_decl, 02335 Sema::AbstractReturnType, 02336 AbstractClass); 02337 02338 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 02339 E = FD->param_end(); I != E; ++I) { 02340 const ParmVarDecl *VD = *I; 02341 Invalid |= 02342 SemaRef.RequireNonAbstractType(VD->getLocation(), 02343 VD->getOriginalType(), 02344 diag::err_abstract_type_in_decl, 02345 Sema::AbstractParamType, 02346 AbstractClass); 02347 } 02348 02349 return Invalid; 02350 } 02351 02352 bool VisitDecl(const Decl* D) { 02353 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 02354 return VisitDeclContext(DC); 02355 02356 return false; 02357 } 02358 }; 02359 } 02360 02361 /// \brief Perform semantic checks on a class definition that has been 02362 /// completing, introducing implicitly-declared members, checking for 02363 /// abstract types, etc. 02364 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 02365 if (!Record || Record->isInvalidDecl()) 02366 return; 02367 02368 if (!Record->isDependentType()) 02369 AddImplicitlyDeclaredMembersToClass(S, Record); 02370 02371 if (Record->isInvalidDecl()) 02372 return; 02373 02374 // Set access bits correctly on the directly-declared conversions. 02375 UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 02376 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 02377 Convs->setAccess(I, (*I)->getAccess()); 02378 02379 // Determine whether we need to check for final overriders. We do 02380 // this either when there are virtual base classes (in which case we 02381 // may end up finding multiple final overriders for a given virtual 02382 // function) or any of the base classes is abstract (in which case 02383 // we might detect that this class is abstract). 02384 bool CheckFinalOverriders = false; 02385 if (Record->isPolymorphic() && !Record->isInvalidDecl() && 02386 !Record->isDependentType()) { 02387 if (Record->getNumVBases()) 02388 CheckFinalOverriders = true; 02389 else if (!Record->isAbstract()) { 02390 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(), 02391 BEnd = Record->bases_end(); 02392 B != BEnd; ++B) { 02393 CXXRecordDecl *BaseDecl 02394 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl()); 02395 if (BaseDecl->isAbstract()) { 02396 CheckFinalOverriders = true; 02397 break; 02398 } 02399 } 02400 } 02401 } 02402 02403 if (CheckFinalOverriders) { 02404 CXXFinalOverriderMap FinalOverriders; 02405 Record->getFinalOverriders(FinalOverriders); 02406 02407 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 02408 MEnd = FinalOverriders.end(); 02409 M != MEnd; ++M) { 02410 for (OverridingMethods::iterator SO = M->second.begin(), 02411 SOEnd = M->second.end(); 02412 SO != SOEnd; ++SO) { 02413 assert(SO->second.size() > 0 && 02414 "All virtual functions have overridding virtual functions"); 02415 if (SO->second.size() == 1) { 02416 // C++ [class.abstract]p4: 02417 // A class is abstract if it contains or inherits at least one 02418 // pure virtual function for which the final overrider is pure 02419 // virtual. 02420 if (SO->second.front().Method->isPure()) 02421 Record->setAbstract(true); 02422 continue; 02423 } 02424 02425 // C++ [class.virtual]p2: 02426 // In a derived class, if a virtual member function of a base 02427 // class subobject has more than one final overrider the 02428 // program is ill-formed. 02429 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 02430 << (NamedDecl *)M->first << Record; 02431 Diag(M->first->getLocation(), diag::note_overridden_virtual_function); 02432 for (OverridingMethods::overriding_iterator OM = SO->second.begin(), 02433 OMEnd = SO->second.end(); 02434 OM != OMEnd; ++OM) 02435 Diag(OM->Method->getLocation(), diag::note_final_overrider) 02436 << (NamedDecl *)M->first << OM->Method->getParent(); 02437 02438 Record->setInvalidDecl(); 02439 } 02440 } 02441 } 02442 02443 if (Record->isAbstract() && !Record->isInvalidDecl()) 02444 (void)AbstractClassUsageDiagnoser(*this, Record); 02445 02446 // If this is not an aggregate type and has no user-declared constructor, 02447 // complain about any non-static data members of reference or const scalar 02448 // type, since they will never get initializers. 02449 if (!Record->isInvalidDecl() && !Record->isDependentType() && 02450 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 02451 bool Complained = false; 02452 for (RecordDecl::field_iterator F = Record->field_begin(), 02453 FEnd = Record->field_end(); 02454 F != FEnd; ++F) { 02455 if (F->getType()->isReferenceType() || 02456 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 02457 if (!Complained) { 02458 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 02459 << Record->getTagKind() << Record; 02460 Complained = true; 02461 } 02462 02463 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 02464 << F->getType()->isReferenceType() 02465 << F->getDeclName(); 02466 } 02467 } 02468 } 02469 } 02470 02471 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 02472 DeclPtrTy TagDecl, 02473 SourceLocation LBrac, 02474 SourceLocation RBrac, 02475 AttributeList *AttrList) { 02476 if (!TagDecl) 02477 return; 02478 02479 AdjustDeclIfTemplate(TagDecl); 02480 02481 ActOnFields(S, RLoc, TagDecl, 02482 (DeclPtrTy*)FieldCollector->getCurFields(), 02483 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 02484 02485 CheckCompletedCXXClass(S, 02486 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 02487 } 02488 02489 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 02490 /// special functions, such as the default constructor, copy 02491 /// constructor, or destructor, to the given C++ class (C++ 02492 /// [special]p1). This routine can only be executed just before the 02493 /// definition of the class is complete. 02494 /// 02495 /// The scope, if provided, is the class scope. 02496 void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S, 02497 CXXRecordDecl *ClassDecl) { 02498 CanQualType ClassType 02499 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 02500 02501 // FIXME: Implicit declarations have exception specifications, which are 02502 // the union of the specifications of the implicitly called functions. 02503 02504 if (!ClassDecl->hasUserDeclaredConstructor()) { 02505 // C++ [class.ctor]p5: 02506 // A default constructor for a class X is a constructor of class X 02507 // that can be called without an argument. If there is no 02508 // user-declared constructor for class X, a default constructor is 02509 // implicitly declared. An implicitly-declared default constructor 02510 // is an inline public member of its class. 02511 DeclarationName Name 02512 = Context.DeclarationNames.getCXXConstructorName(ClassType); 02513 CXXConstructorDecl *DefaultCon = 02514 CXXConstructorDecl::Create(Context, ClassDecl, 02515 ClassDecl->getLocation(), Name, 02516 Context.getFunctionType(Context.VoidTy, 02517 0, 0, false, 0, 02518 /*FIXME*/false, false, 02519 0, 0, 02520 FunctionType::ExtInfo()), 02521 /*TInfo=*/0, 02522 /*isExplicit=*/false, 02523 /*isInline=*/true, 02524 /*isImplicitlyDeclared=*/true); 02525 DefaultCon->setAccess(AS_public); 02526 DefaultCon->setImplicit(); 02527 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 02528 if (S) 02529 PushOnScopeChains(DefaultCon, S, true); 02530 else 02531 ClassDecl->addDecl(DefaultCon); 02532 } 02533 02534 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 02535 // C++ [class.copy]p4: 02536 // If the class definition does not explicitly declare a copy 02537 // constructor, one is declared implicitly. 02538 02539 // C++ [class.copy]p5: 02540 // The implicitly-declared copy constructor for a class X will 02541 // have the form 02542 // 02543 // X::X(const X&) 02544 // 02545 // if 02546 bool HasConstCopyConstructor = true; 02547 02548 // -- each direct or virtual base class B of X has a copy 02549 // constructor whose first parameter is of type const B& or 02550 // const volatile B&, and 02551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 02552 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 02553 const CXXRecordDecl *BaseClassDecl 02554 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 02555 HasConstCopyConstructor 02556 = BaseClassDecl->hasConstCopyConstructor(Context); 02557 } 02558 02559 // -- for all the nonstatic data members of X that are of a 02560 // class type M (or array thereof), each such class type 02561 // has a copy constructor whose first parameter is of type 02562 // const M& or const volatile M&. 02563 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 02564 HasConstCopyConstructor && Field != ClassDecl->field_end(); 02565 ++Field) { 02566 QualType FieldType = (*Field)->getType(); 02567 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 02568 FieldType = Array->getElementType(); 02569 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 02570 const CXXRecordDecl *FieldClassDecl 02571 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 02572 HasConstCopyConstructor 02573 = FieldClassDecl->hasConstCopyConstructor(Context); 02574 } 02575 } 02576 02577 // Otherwise, the implicitly declared copy constructor will have 02578 // the form 02579 // 02580 // X::X(X&) 02581 QualType ArgType = ClassType; 02582 if (HasConstCopyConstructor) 02583 ArgType = ArgType.withConst(); 02584 ArgType = Context.getLValueReferenceType(ArgType); 02585 02586 // An implicitly-declared copy constructor is an inline public 02587 // member of its class. 02588 DeclarationName Name 02589 = Context.DeclarationNames.getCXXConstructorName(ClassType); 02590 CXXConstructorDecl *CopyConstructor 02591 = CXXConstructorDecl::Create(Context, ClassDecl, 02592 ClassDecl->getLocation(), Name, 02593 Context.getFunctionType(Context.VoidTy, 02594 &ArgType, 1, 02595 false, 0, 02596 /*FIXME:*/false, 02597 false, 0, 0, 02598 FunctionType::ExtInfo()), 02599 /*TInfo=*/0, 02600 /*isExplicit=*/false, 02601 /*isInline=*/true, 02602 /*isImplicitlyDeclared=*/true); 02603 CopyConstructor->setAccess(AS_public); 02604 CopyConstructor->setImplicit(); 02605 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 02606 02607 // Add the parameter to the constructor. 02608 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 02609 ClassDecl->getLocation(), 02610 /*IdentifierInfo=*/0, 02611 ArgType, /*TInfo=*/0, 02612 VarDecl::None, 02613 VarDecl::None, 0); 02614 CopyConstructor->setParams(&FromParam, 1); 02615 if (S) 02616 PushOnScopeChains(CopyConstructor, S, true); 02617 else 02618 ClassDecl->addDecl(CopyConstructor); 02619 } 02620 02621 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 02622 // Note: The following rules are largely analoguous to the copy 02623 // constructor rules. Note that virtual bases are not taken into account 02624 // for determining the argument type of the operator. Note also that 02625 // operators taking an object instead of a reference are allowed. 02626 // 02627 // C++ [class.copy]p10: 02628 // If the class definition does not explicitly declare a copy 02629 // assignment operator, one is declared implicitly. 02630 // The implicitly-defined copy assignment operator for a class X 02631 // will have the form 02632 // 02633 // X& X::operator=(const X&) 02634 // 02635 // if 02636 bool HasConstCopyAssignment = true; 02637 02638 // -- each direct base class B of X has a copy assignment operator 02639 // whose parameter is of type const B&, const volatile B& or B, 02640 // and 02641 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 02642 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 02643 assert(!Base->getType()->isDependentType() && 02644 "Cannot generate implicit members for class with dependent bases."); 02645 const CXXRecordDecl *BaseClassDecl 02646 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 02647 const CXXMethodDecl *MD = 0; 02648 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 02649 MD); 02650 } 02651 02652 // -- for all the nonstatic data members of X that are of a class 02653 // type M (or array thereof), each such class type has a copy 02654 // assignment operator whose parameter is of type const M&, 02655 // const volatile M& or M. 02656 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 02657 HasConstCopyAssignment && Field != ClassDecl->field_end(); 02658 ++Field) { 02659 QualType FieldType = (*Field)->getType(); 02660 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 02661 FieldType = Array->getElementType(); 02662 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 02663 const CXXRecordDecl *FieldClassDecl 02664 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 02665 const CXXMethodDecl *MD = 0; 02666 HasConstCopyAssignment 02667 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 02668 } 02669 } 02670 02671 // Otherwise, the implicitly declared copy assignment operator will 02672 // have the form 02673 // 02674 // X& X::operator=(X&) 02675 QualType ArgType = ClassType; 02676 QualType RetType = Context.getLValueReferenceType(ArgType); 02677 if (HasConstCopyAssignment) 02678 ArgType = ArgType.withConst(); 02679 ArgType = Context.getLValueReferenceType(ArgType); 02680 02681 // An implicitly-declared copy assignment operator is an inline public 02682 // member of its class. 02683 DeclarationName Name = 02684 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 02685 CXXMethodDecl *CopyAssignment = 02686 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 02687 Context.getFunctionType(RetType, &ArgType, 1, 02688 false, 0, 02689 /*FIXME:*/false, 02690 false, 0, 0, 02691 FunctionType::ExtInfo()), 02692 /*TInfo=*/0, /*isStatic=*/false, 02693 /*StorageClassAsWritten=*/FunctionDecl::None, 02694 /*isInline=*/true); 02695 CopyAssignment->setAccess(AS_public); 02696 CopyAssignment->setImplicit(); 02697 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 02698 CopyAssignment->setCopyAssignment(true); 02699 02700 // Add the parameter to the operator. 02701 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 02702 ClassDecl->getLocation(), 02703 /*Id=*/0, 02704 ArgType, /*TInfo=*/0, 02705 VarDecl::None, 02706 VarDecl::None, 0); 02707 CopyAssignment->setParams(&FromParam, 1); 02708 02709 // Don't call addedAssignmentOperator. There is no way to distinguish an 02710 // implicit from an explicit assignment operator. 02711 if (S) 02712 PushOnScopeChains(CopyAssignment, S, true); 02713 else 02714 ClassDecl->addDecl(CopyAssignment); 02715 AddOverriddenMethods(ClassDecl, CopyAssignment); 02716 } 02717 02718 if (!ClassDecl->hasUserDeclaredDestructor()) { 02719 // C++ [class.dtor]p2: 02720 // If a class has no user-declared destructor, a destructor is 02721 // declared implicitly. An implicitly-declared destructor is an 02722 // inline public member of its class. 02723 QualType Ty = Context.getFunctionType(Context.VoidTy, 02724 0, 0, false, 0, 02725 /*FIXME:*/false, 02726 false, 0, 0, FunctionType::ExtInfo()); 02727 02728 DeclarationName Name 02729 = Context.DeclarationNames.getCXXDestructorName(ClassType); 02730 CXXDestructorDecl *Destructor 02731 = CXXDestructorDecl::Create(Context, ClassDecl, 02732 ClassDecl->getLocation(), Name, Ty, 02733 /*isInline=*/true, 02734 /*isImplicitlyDeclared=*/true); 02735 Destructor->setAccess(AS_public); 02736 Destructor->setImplicit(); 02737 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 02738 if (S) 02739 PushOnScopeChains(Destructor, S, true); 02740 else 02741 ClassDecl->addDecl(Destructor); 02742 02743 // This could be uniqued if it ever proves significant. 02744 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 02745 02746 AddOverriddenMethods(ClassDecl, Destructor); 02747 } 02748 } 02749 02750 void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 02751 Decl *D = TemplateD.getAs<Decl>(); 02752 if (!D) 02753 return; 02754 02755 TemplateParameterList *Params = 0; 02756 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 02757 Params = Template->getTemplateParameters(); 02758 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 02759 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 02760 Params = PartialSpec->getTemplateParameters(); 02761 else 02762 return; 02763 02764 for (TemplateParameterList::iterator Param = Params->begin(), 02765 ParamEnd = Params->end(); 02766 Param != ParamEnd; ++Param) { 02767 NamedDecl *Named = cast<NamedDecl>(*Param); 02768 if (Named->getDeclName()) { 02769 S->AddDecl(DeclPtrTy::make(Named)); 02770 IdResolver.AddDecl(Named); 02771 } 02772 } 02773 } 02774 02775 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 02776 if (!RecordD) return; 02777 AdjustDeclIfTemplate(RecordD); 02778 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 02779 PushDeclContext(S, Record); 02780 } 02781 02782 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 02783 if (!RecordD) return; 02784 PopDeclContext(); 02785 } 02786 02787 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 02788 /// parsing a top-level (non-nested) C++ class, and we are now 02789 /// parsing those parts of the given Method declaration that could 02790 /// not be parsed earlier (C++ [class.mem]p2), such as default 02791 /// arguments. This action should enter the scope of the given 02792 /// Method declaration as if we had just parsed the qualified method 02793 /// name. However, it should not bring the parameters into scope; 02794 /// that will be performed by ActOnDelayedCXXMethodParameter. 02795 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 02796 } 02797 02798 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 02799 /// C++ method declaration. We're (re-)introducing the given 02800 /// function parameter into scope for use in parsing later parts of 02801 /// the method declaration. For example, we could see an 02802 /// ActOnParamDefaultArgument event for this parameter. 02803 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 02804 if (!ParamD) 02805 return; 02806 02807 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 02808 02809 // If this parameter has an unparsed default argument, clear it out 02810 // to make way for the parsed default argument. 02811 if (Param->hasUnparsedDefaultArg()) 02812 Param->setDefaultArg(0); 02813 02814 S->AddDecl(DeclPtrTy::make(Param)); 02815 if (Param->getDeclName()) 02816 IdResolver.AddDecl(Param); 02817 } 02818 02819 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 02820 /// processing the delayed method declaration for Method. The method 02821 /// declaration is now considered finished. There may be a separate 02822 /// ActOnStartOfFunctionDef action later (not necessarily 02823 /// immediately!) for this method, if it was also defined inside the 02824 /// class body. 02825 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 02826 if (!MethodD) 02827 return; 02828 02829 AdjustDeclIfTemplate(MethodD); 02830 02831 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 02832 02833 // Now that we have our default arguments, check the constructor 02834 // again. It could produce additional diagnostics or affect whether 02835 // the class has implicitly-declared destructors, among other 02836 // things. 02837 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 02838 CheckConstructor(Constructor); 02839 02840 // Check the default arguments, which we may have added. 02841 if (!Method->isInvalidDecl()) 02842 CheckCXXDefaultArguments(Method); 02843 } 02844 02845 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 02846 /// the well-formedness of the constructor declarator @p D with type @p 02847 /// R. If there are any errors in the declarator, this routine will 02848 /// emit diagnostics and set the invalid bit to true. In any case, the type 02849 /// will be updated to reflect a well-formed type for the constructor and 02850 /// returned. 02851 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 02852 FunctionDecl::StorageClass &SC) { 02853 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 02854 02855 // C++ [class.ctor]p3: 02856 // A constructor shall not be virtual (10.3) or static (9.4). A 02857 // constructor can be invoked for a const, volatile or const 02858 // volatile object. A constructor shall not be declared const, 02859 // volatile, or const volatile (9.3.2). 02860 if (isVirtual) { 02861 if (!D.isInvalidType()) 02862 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 02863 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 02864 << SourceRange(D.getIdentifierLoc()); 02865 D.setInvalidType(); 02866 } 02867 if (SC == FunctionDecl::Static) { 02868 if (!D.isInvalidType()) 02869 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 02870 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 02871 << SourceRange(D.getIdentifierLoc()); 02872 D.setInvalidType(); 02873 SC = FunctionDecl::None; 02874 } 02875 02876 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 02877 if (FTI.TypeQuals != 0) { 02878 if (FTI.TypeQuals & Qualifiers::Const) 02879 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02880 << "const" << SourceRange(D.getIdentifierLoc()); 02881 if (FTI.TypeQuals & Qualifiers::Volatile) 02882 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02883 << "volatile" << SourceRange(D.getIdentifierLoc()); 02884 if (FTI.TypeQuals & Qualifiers::Restrict) 02885 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 02886 << "restrict" << SourceRange(D.getIdentifierLoc()); 02887 } 02888 02889 // Rebuild the function type "R" without any type qualifiers (in 02890 // case any of the errors above fired) and with "void" as the 02891 // return type, since constructors don't have return types. We 02892 // *always* have to do this, because GetTypeForDeclarator will 02893 // put in a result type of "int" when none was specified. 02894 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 02895 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 02896 Proto->getNumArgs(), 02897 Proto->isVariadic(), 0, 02898 Proto->hasExceptionSpec(), 02899 Proto->hasAnyExceptionSpec(), 02900 Proto->getNumExceptions(), 02901 Proto->exception_begin(), 02902 Proto->getExtInfo()); 02903 } 02904 02905 /// CheckConstructor - Checks a fully-formed constructor for 02906 /// well-formedness, issuing any diagnostics required. Returns true if 02907 /// the constructor declarator is invalid. 02908 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 02909 CXXRecordDecl *ClassDecl 02910 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 02911 if (!ClassDecl) 02912 return Constructor->setInvalidDecl(); 02913 02914 // C++ [class.copy]p3: 02915 // A declaration of a constructor for a class X is ill-formed if 02916 // its first parameter is of type (optionally cv-qualified) X and 02917 // either there are no other parameters or else all other 02918 // parameters have default arguments. 02919 if (!Constructor->isInvalidDecl() && 02920 ((Constructor->getNumParams() == 1) || 02921 (Constructor->getNumParams() > 1 && 02922 Constructor->getParamDecl(1)->hasDefaultArg())) && 02923 Constructor->getTemplateSpecializationKind() 02924 != TSK_ImplicitInstantiation) { 02925 QualType ParamType = Constructor->getParamDecl(0)->getType(); 02926 QualType ClassTy = Context.getTagDeclType(ClassDecl); 02927 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 02928 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 02929 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 02930 << FixItHint::CreateInsertion(ParamLoc, " const &"); 02931 02932 // FIXME: Rather that making the constructor invalid, we should endeavor 02933 // to fix the type. 02934 Constructor->setInvalidDecl(); 02935 } 02936 } 02937 02938 // Notify the class that we've added a constructor. In principle we 02939 // don't need to do this for out-of-line declarations; in practice 02940 // we only instantiate the most recent declaration of a method, so 02941 // we have to call this for everything but friends. 02942 if (!Constructor->getFriendObjectKind()) 02943 ClassDecl->addedConstructor(Context, Constructor); 02944 } 02945 02946 /// CheckDestructor - Checks a fully-formed destructor for well-formedness, 02947 /// issuing any diagnostics required. Returns true on error. 02948 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 02949 CXXRecordDecl *RD = Destructor->getParent(); 02950 02951 if (Destructor->isVirtual()) { 02952 SourceLocation Loc; 02953 02954 if (!Destructor->isImplicit()) 02955 Loc = Destructor->getLocation(); 02956 else 02957 Loc = RD->getLocation(); 02958 02959 // If we have a virtual destructor, look up the deallocation function 02960 FunctionDecl *OperatorDelete = 0; 02961 DeclarationName Name = 02962 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 02963 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 02964 return true; 02965 02966 Destructor->setOperatorDelete(OperatorDelete); 02967 } 02968 02969 return false; 02970 } 02971 02972 static inline bool 02973 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 02974 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 02975 FTI.ArgInfo[0].Param && 02976 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 02977 } 02978 02979 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 02980 /// the well-formednes of the destructor declarator @p D with type @p 02981 /// R. If there are any errors in the declarator, this routine will 02982 /// emit diagnostics and set the declarator to invalid. Even if this happens, 02983 /// will be updated to reflect a well-formed type for the destructor and 02984 /// returned. 02985 QualType Sema::CheckDestructorDeclarator(Declarator &D, 02986 FunctionDecl::StorageClass& SC) { 02987 // C++ [class.dtor]p1: 02988 // [...] A typedef-name that names a class is a class-name 02989 // (7.1.3); however, a typedef-name that names a class shall not 02990 // be used as the identifier in the declarator for a destructor 02991 // declaration. 02992 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 02993 if (isa<TypedefType>(DeclaratorType)) { 02994 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 02995 << DeclaratorType; 02996 D.setInvalidType(); 02997 } 02998 02999 // C++ [class.dtor]p2: 03000 // A destructor is used to destroy objects of its class type. A 03001 // destructor takes no parameters, and no return type can be 03002 // specified for it (not even void). The address of a destructor 03003 // shall not be taken. A destructor shall not be static. A 03004 // destructor can be invoked for a const, volatile or const 03005 // volatile object. A destructor shall not be declared const, 03006 // volatile or const volatile (9.3.2). 03007 if (SC == FunctionDecl::Static) { 03008 if (!D.isInvalidType()) 03009 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 03010 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 03011 << SourceRange(D.getIdentifierLoc()); 03012 SC = FunctionDecl::None; 03013 D.setInvalidType(); 03014 } 03015 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 03016 // Destructors don't have return types, but the parser will 03017 // happily parse something like: 03018 // 03019 // class X { 03020 // float ~X(); 03021 // }; 03022 // 03023 // The return type will be eliminated later. 03024 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 03025 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 03026 << SourceRange(D.getIdentifierLoc()); 03027 } 03028 03029 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 03030 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 03031 if (FTI.TypeQuals & Qualifiers::Const) 03032 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 03033 << "const" << SourceRange(D.getIdentifierLoc()); 03034 if (FTI.TypeQuals & Qualifiers::Volatile) 03035 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 03036 << "volatile" << SourceRange(D.getIdentifierLoc()); 03037 if (FTI.TypeQuals & Qualifiers::Restrict) 03038 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 03039 << "restrict" << SourceRange(D.getIdentifierLoc()); 03040 D.setInvalidType(); 03041 } 03042 03043 // Make sure we don't have any parameters. 03044 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 03045 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 03046 03047 // Delete the parameters. 03048 FTI.freeArgs(); 03049 D.setInvalidType(); 03050 } 03051 03052 // Make sure the destructor isn't variadic. 03053 if (FTI.isVariadic) { 03054 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 03055 D.setInvalidType(); 03056 } 03057 03058 // Rebuild the function type "R" without any type qualifiers or 03059 // parameters (in case any of the errors above fired) and with 03060 // "void" as the return type, since destructors don't have return 03061 // types. We *always* have to do this, because GetTypeForDeclarator 03062 // will put in a result type of "int" when none was specified. 03063 // FIXME: Exceptions! 03064 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 03065 false, false, 0, 0, FunctionType::ExtInfo()); 03066 } 03067 03068 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 03069 /// well-formednes of the conversion function declarator @p D with 03070 /// type @p R. If there are any errors in the declarator, this routine 03071 /// will emit diagnostics and return true. Otherwise, it will return 03072 /// false. Either way, the type @p R will be updated to reflect a 03073 /// well-formed type for the conversion operator. 03074 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 03075 FunctionDecl::StorageClass& SC) { 03076 // C++ [class.conv.fct]p1: 03077 // Neither parameter types nor return type can be specified. The 03078 // type of a conversion function (8.3.5) is "function taking no 03079 // parameter returning conversion-type-id." 03080 if (SC == FunctionDecl::Static) { 03081 if (!D.isInvalidType()) 03082 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 03083 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 03084 << SourceRange(D.getIdentifierLoc()); 03085 D.setInvalidType(); 03086 SC = FunctionDecl::None; 03087 } 03088 03089 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 03090 03091 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 03092 // Conversion functions don't have return types, but the parser will 03093 // happily parse something like: 03094 // 03095 // class X { 03096 // float operator bool(); 03097 // }; 03098 // 03099 // The return type will be changed later anyway. 03100 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 03101 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 03102 << SourceRange(D.getIdentifierLoc()); 03103 D.setInvalidType(); 03104 } 03105 03106 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 03107 03108 // Make sure we don't have any parameters. 03109 if (Proto->getNumArgs() > 0) { 03110 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 03111 03112 // Delete the parameters. 03113 D.getTypeObject(0).Fun.freeArgs(); 03114 D.setInvalidType(); 03115 } else if (Proto->isVariadic()) { 03116 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 03117 D.setInvalidType(); 03118 } 03119 03120 // Diagnose "&operator bool()" and other such nonsense. This 03121 // is actually a gcc extension which we don't support. 03122 if (Proto->getResultType() != ConvType) { 03123 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 03124 << Proto->getResultType(); 03125 D.setInvalidType(); 03126 ConvType = Proto->getResultType(); 03127 } 03128 03129 // C++ [class.conv.fct]p4: 03130 // The conversion-type-id shall not represent a function type nor 03131 // an array type. 03132 if (ConvType->isArrayType()) { 03133 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 03134 ConvType = Context.getPointerType(ConvType); 03135 D.setInvalidType(); 03136 } else if (ConvType->isFunctionType()) { 03137 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 03138 ConvType = Context.getPointerType(ConvType); 03139 D.setInvalidType(); 03140 } 03141 03142 // Rebuild the function type "R" without any parameters (in case any 03143 // of the errors above fired) and with the conversion type as the 03144 // return type. 03145 if (D.isInvalidType()) { 03146 R = Context.getFunctionType(ConvType, 0, 0, false, 03147 Proto->getTypeQuals(), 03148 Proto->hasExceptionSpec(), 03149 Proto->hasAnyExceptionSpec(), 03150 Proto->getNumExceptions(), 03151 Proto->exception_begin(), 03152 Proto->getExtInfo()); 03153 } 03154 03155 // C++0x explicit conversion operators. 03156 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 03157 Diag(D.getDeclSpec().getExplicitSpecLoc(), 03158 diag::warn_explicit_conversion_functions) 03159 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 03160 } 03161 03162 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 03163 /// the declaration of the given C++ conversion function. This routine 03164 /// is responsible for recording the conversion function in the C++ 03165 /// class, if possible. 03166 Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 03167 assert(Conversion && "Expected to receive a conversion function declaration"); 03168 03169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 03170 03171 // Make sure we aren't redeclaring the conversion function. 03172 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 03173 03174 // C++ [class.conv.fct]p1: 03175 // [...] A conversion function is never used to convert a 03176 // (possibly cv-qualified) object to the (possibly cv-qualified) 03177 // same object type (or a reference to it), to a (possibly 03178 // cv-qualified) base class of that type (or a reference to it), 03179 // or to (possibly cv-qualified) void. 03180 // FIXME: Suppress this warning if the conversion function ends up being a 03181 // virtual function that overrides a virtual function in a base class. 03182 QualType ClassType 03183 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 03184 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 03185 ConvType = ConvTypeRef->getPointeeType(); 03186 if (ConvType->isRecordType()) { 03187 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 03188 if (ConvType == ClassType) 03189 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 03190 << ClassType; 03191 else if (IsDerivedFrom(ClassType, ConvType)) 03192 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 03193 << ClassType << ConvType; 03194 } else if (ConvType->isVoidType()) { 03195 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 03196 << ClassType << ConvType; 03197 } 03198 03199 if (Conversion->getPrimaryTemplate()) { 03200 // ignore specializations 03201 } else if (Conversion->getPreviousDeclaration()) { 03202 if (FunctionTemplateDecl *ConversionTemplate 03203 = Conversion->getDescribedFunctionTemplate()) { 03204 if (ClassDecl->replaceConversion( 03205 ConversionTemplate->getPreviousDeclaration(), 03206 ConversionTemplate)) 03207 return DeclPtrTy::make(ConversionTemplate); 03208 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 03209 Conversion)) 03210 return DeclPtrTy::make(Conversion); 03211 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 03212 } else if (FunctionTemplateDecl *ConversionTemplate 03213 = Conversion->getDescribedFunctionTemplate()) 03214 ClassDecl->addConversionFunction(ConversionTemplate); 03215 else 03216 ClassDecl->addConversionFunction(Conversion); 03217 03218 return DeclPtrTy::make(Conversion); 03219 } 03220 03221 //===----------------------------------------------------------------------===// 03222 // Namespace Handling 03223 //===----------------------------------------------------------------------===// 03224 03225 /// ActOnStartNamespaceDef - This is called at the start of a namespace 03226 /// definition. 03227 Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 03228 SourceLocation IdentLoc, 03229 IdentifierInfo *II, 03230 SourceLocation LBrace, 03231 AttributeList *AttrList) { 03232 NamespaceDecl *Namespc = 03233 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 03234 Namespc->setLBracLoc(LBrace); 03235 03236 Scope *DeclRegionScope = NamespcScope->getParent(); 03237 03238 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 03239 03240 if (II) { 03241 // C++ [namespace.def]p2: 03242 // The identifier in an original-namespace-definition shall not have been 03243 // previously defined in the declarative region in which the 03244 // original-namespace-definition appears. The identifier in an 03245 // original-namespace-definition is the name of the namespace. Subsequently 03246 // in that declarative region, it is treated as an original-namespace-name. 03247 03248 NamedDecl *PrevDecl 03249 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName, 03250 ForRedeclaration); 03251 03252 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 03253 // This is an extended namespace definition. 03254 // Attach this namespace decl to the chain of extended namespace 03255 // definitions. 03256 OrigNS->setNextNamespace(Namespc); 03257 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 03258 03259 // Remove the previous declaration from the scope. 03260 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 03261 IdResolver.RemoveDecl(OrigNS); 03262 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 03263 } 03264 } else if (PrevDecl) { 03265 // This is an invalid name redefinition. 03266 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 03267 << Namespc->getDeclName(); 03268 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 03269 Namespc->setInvalidDecl(); 03270 // Continue on to push Namespc as current DeclContext and return it. 03271 } else if (II->isStr("std") && 03272 CurContext->getLookupContext()->isTranslationUnit()) { 03273 // This is the first "real" definition of the namespace "std", so update 03274 // our cache of the "std" namespace to point at this definition. 03275 if (StdNamespace) { 03276 // We had already defined a dummy namespace "std". Link this new 03277 // namespace definition to the dummy namespace "std". 03278 StdNamespace->setNextNamespace(Namespc); 03279 StdNamespace->setLocation(IdentLoc); 03280 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 03281 } 03282 03283 // Make our StdNamespace cache point at the first real definition of the 03284 // "std" namespace. 03285 StdNamespace = Namespc; 03286 } 03287 03288 PushOnScopeChains(Namespc, DeclRegionScope); 03289 } else { 03290 // Anonymous namespaces. 03291 assert(Namespc->isAnonymousNamespace()); 03292 03293 // Link the anonymous namespace into its parent. 03294 NamespaceDecl *PrevDecl; 03295 DeclContext *Parent = CurContext->getLookupContext(); 03296 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 03297 PrevDecl = TU->getAnonymousNamespace(); 03298 TU->setAnonymousNamespace(Namespc); 03299 } else { 03300 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 03301 PrevDecl = ND->getAnonymousNamespace(); 03302 ND->setAnonymousNamespace(Namespc); 03303 } 03304 03305 // Link the anonymous namespace with its previous declaration. 03306 if (PrevDecl) { 03307 assert(PrevDecl->isAnonymousNamespace()); 03308 assert(!PrevDecl->getNextNamespace()); 03309 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 03310 PrevDecl->setNextNamespace(Namespc); 03311 } 03312 03313 CurContext->addDecl(Namespc); 03314 03315 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 03316 // behaves as if it were replaced by 03317 // namespace unique { /* empty body */ } 03318 // using namespace unique; 03319 // namespace unique { namespace-body } 03320 // where all occurrences of 'unique' in a translation unit are 03321 // replaced by the same identifier and this identifier differs 03322 // from all other identifiers in the entire program. 03323 03324 // We just create the namespace with an empty name and then add an 03325 // implicit using declaration, just like the standard suggests. 03326 // 03327 // CodeGen enforces the "universally unique" aspect by giving all 03328 // declarations semantically contained within an anonymous 03329 // namespace internal linkage. 03330 03331 if (!PrevDecl) { 03332 UsingDirectiveDecl* UD 03333 = UsingDirectiveDecl::Create(Context, CurContext, 03334 /* 'using' */ LBrace, 03335 /* 'namespace' */ SourceLocation(), 03336 /* qualifier */ SourceRange(), 03337 /* NNS */ NULL, 03338 /* identifier */ SourceLocation(), 03339 Namespc, 03340 /* Ancestor */ CurContext); 03341 UD->setImplicit(); 03342 CurContext->addDecl(UD); 03343 } 03344 } 03345 03346 // Although we could have an invalid decl (i.e. the namespace name is a 03347 // redefinition), push it as current DeclContext and try to continue parsing. 03348 // FIXME: We should be able to push Namespc here, so that the each DeclContext 03349 // for the namespace has the declarations that showed up in that particular 03350 // namespace definition. 03351 PushDeclContext(NamespcScope, Namespc); 03352 return DeclPtrTy::make(Namespc); 03353 } 03354 03355 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 03356 /// is a namespace alias, returns the namespace it points to. 03357 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 03358 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 03359 return AD->getNamespace(); 03360 return dyn_cast_or_null<NamespaceDecl>(D); 03361 } 03362 03363 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 03364 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 03365 void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 03366 Decl *Dcl = D.getAs<Decl>(); 03367 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 03368 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 03369 Namespc->setRBracLoc(RBrace); 03370 PopDeclContext(); 03371 } 03372 03373 Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 03374 SourceLocation UsingLoc, 03375 SourceLocation NamespcLoc, 03376 CXXScopeSpec &SS, 03377 SourceLocation IdentLoc, 03378 IdentifierInfo *NamespcName, 03379 AttributeList *AttrList) { 03380 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 03381 assert(NamespcName && "Invalid NamespcName."); 03382 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 03383 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 03384 03385 UsingDirectiveDecl *UDir = 0; 03386 03387 // Lookup namespace name. 03388 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 03389 LookupParsedName(R, S, &SS); 03390 if (R.isAmbiguous()) 03391 return DeclPtrTy(); 03392 03393 if (!R.empty()) { 03394 NamedDecl *Named = R.getFoundDecl(); 03395 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 03396 && "expected namespace decl"); 03397 // C++ [namespace.udir]p1: 03398 // A using-directive specifies that the names in the nominated 03399 // namespace can be used in the scope in which the 03400 // using-directive appears after the using-directive. During 03401 // unqualified name lookup (3.4.1), the names appear as if they 03402 // were declared in the nearest enclosing namespace which 03403 // contains both the using-directive and the nominated 03404 // namespace. [Note: in this context, "contains" means "contains 03405 // directly or indirectly". ] 03406 03407 // Find enclosing context containing both using-directive and 03408 // nominated namespace. 03409 NamespaceDecl *NS = getNamespaceDecl(Named); 03410 DeclContext *CommonAncestor = cast<DeclContext>(NS); 03411 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 03412 CommonAncestor = CommonAncestor->getParent(); 03413 03414 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 03415 SS.getRange(), 03416 (NestedNameSpecifier *)SS.getScopeRep(), 03417 IdentLoc, Named, CommonAncestor); 03418 PushUsingDirective(S, UDir); 03419 } else { 03420 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 03421 } 03422 03423 // FIXME: We ignore attributes for now. 03424 delete AttrList; 03425 return DeclPtrTy::make(UDir); 03426 } 03427 03428 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 03429 // If scope has associated entity, then using directive is at namespace 03430 // or translation unit scope. We add UsingDirectiveDecls, into 03431 // it's lookup structure. 03432 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 03433 Ctx->addDecl(UDir); 03434 else 03435 // Otherwise it is block-sope. using-directives will affect lookup 03436 // only to the end of scope. 03437 S->PushUsingDirective(DeclPtrTy::make(UDir)); 03438 } 03439 03440 03441 Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 03442 AccessSpecifier AS, 03443 bool HasUsingKeyword, 03444 SourceLocation UsingLoc, 03445 CXXScopeSpec &SS, 03446 UnqualifiedId &Name, 03447 AttributeList *AttrList, 03448 bool IsTypeName, 03449 SourceLocation TypenameLoc) { 03450 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 03451 03452 switch (Name.getKind()) { 03453 case UnqualifiedId::IK_Identifier: 03454 case UnqualifiedId::IK_OperatorFunctionId: 03455 case UnqualifiedId::IK_LiteralOperatorId: 03456 case UnqualifiedId::IK_ConversionFunctionId: 03457 break; 03458 03459 case UnqualifiedId::IK_ConstructorName: 03460 case UnqualifiedId::IK_ConstructorTemplateId: 03461 // C++0x inherited constructors. 03462 if (getLangOptions().CPlusPlus0x) break; 03463 03464 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 03465 << SS.getRange(); 03466 return DeclPtrTy(); 03467 03468 case UnqualifiedId::IK_DestructorName: 03469 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 03470 << SS.getRange(); 03471 return DeclPtrTy(); 03472 03473 case UnqualifiedId::IK_TemplateId: 03474 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 03475 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 03476 return DeclPtrTy(); 03477 } 03478 03479 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 03480 if (!TargetName) 03481 return DeclPtrTy(); 03482 03483 // Warn about using declarations. 03484 // TODO: store that the declaration was written without 'using' and 03485 // talk about access decls instead of using decls in the 03486 // diagnostics. 03487 if (!HasUsingKeyword) { 03488 UsingLoc = Name.getSourceRange().getBegin(); 03489 03490 Diag(UsingLoc, diag::warn_access_decl_deprecated) 03491 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 03492 } 03493 03494 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 03495 Name.getSourceRange().getBegin(), 03496 TargetName, AttrList, 03497 /* IsInstantiation */ false, 03498 IsTypeName, TypenameLoc); 03499 if (UD) 03500 PushOnScopeChains(UD, S, /*AddToContext*/ false); 03501 03502 return DeclPtrTy::make(UD); 03503 } 03504 03505 /// Determines whether to create a using shadow decl for a particular 03506 /// decl, given the set of decls existing prior to this using lookup. 03507 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 03508 const LookupResult &Previous) { 03509 // Diagnose finding a decl which is not from a base class of the 03510 // current class. We do this now because there are cases where this 03511 // function will silently decide not to build a shadow decl, which 03512 // will pre-empt further diagnostics. 03513 // 03514 // We don't need to do this in C++0x because we do the check once on 03515 // the qualifier. 03516 // 03517 // FIXME: diagnose the following if we care enough: 03518 // struct A { int foo; }; 03519 // struct B : A { using A::foo; }; 03520 // template <class T> struct C : A {}; 03521 // template <class T> struct D : C<T> { using B::foo; } // <--- 03522 // This is invalid (during instantiation) in C++03 because B::foo 03523 // resolves to the using decl in B, which is not a base class of D<T>. 03524 // We can't diagnose it immediately because C<T> is an unknown 03525 // specialization. The UsingShadowDecl in D<T> then points directly 03526 // to A::foo, which will look well-formed when we instantiate. 03527 // The right solution is to not collapse the shadow-decl chain. 03528 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 03529 DeclContext *OrigDC = Orig->getDeclContext(); 03530 03531 // Handle enums and anonymous structs. 03532 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 03533 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 03534 while (OrigRec->isAnonymousStructOrUnion()) 03535 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 03536 03537 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 03538 if (OrigDC == CurContext) { 03539 Diag(Using->getLocation(), 03540 diag::err_using_decl_nested_name_specifier_is_current_class) 03541 << Using->getNestedNameRange(); 03542 Diag(Orig->getLocation(), diag::note_using_decl_target); 03543 return true; 03544 } 03545 03546 Diag(Using->getNestedNameRange().getBegin(), 03547 diag::err_using_decl_nested_name_specifier_is_not_base_class) 03548 << Using->getTargetNestedNameDecl() 03549 << cast<CXXRecordDecl>(CurContext) 03550 << Using->getNestedNameRange(); 03551 Diag(Orig->getLocation(), diag::note_using_decl_target); 03552 return true; 03553 } 03554 } 03555 03556 if (Previous.empty()) return false; 03557 03558 NamedDecl *Target = Orig; 03559 if (isa<UsingShadowDecl>(Target)) 03560 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 03561 03562 // If the target happens to be one of the previous declarations, we 03563 // don't have a conflict. 03564 // 03565 // FIXME: but we might be increasing its access, in which case we 03566 // should redeclare it. 03567 NamedDecl *NonTag = 0, *Tag = 0; 03568 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 03569 I != E; ++I) { 03570 NamedDecl *D = (*I)->getUnderlyingDecl(); 03571 if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 03572 return false; 03573 03574 (isa<TagDecl>(D) ? Tag : NonTag) = D; 03575 } 03576 03577 if (Target->isFunctionOrFunctionTemplate()) { 03578 FunctionDecl *FD; 03579 if (isa<FunctionTemplateDecl>(Target)) 03580 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 03581 else 03582 FD = cast<FunctionDecl>(Target); 03583 03584 NamedDecl *OldDecl = 0; 03585 switch (CheckOverload(FD, Previous, OldDecl)) { 03586 case Ovl_Overload: 03587 return false; 03588 03589 case Ovl_NonFunction: 03590 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03591 break; 03592 03593 // We found a decl with the exact signature. 03594 case Ovl_Match: 03595 if (isa<UsingShadowDecl>(OldDecl)) { 03596 // Silently ignore the possible conflict. 03597 return false; 03598 } 03599 03600 // If we're in a record, we want to hide the target, so we 03601 // return true (without a diagnostic) to tell the caller not to 03602 // build a shadow decl. 03603 if (CurContext->isRecord()) 03604 return true; 03605 03606 // If we're not in a record, this is an error. 03607 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03608 break; 03609 } 03610 03611 Diag(Target->getLocation(), diag::note_using_decl_target); 03612 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 03613 return true; 03614 } 03615 03616 // Target is not a function. 03617 03618 if (isa<TagDecl>(Target)) { 03619 // No conflict between a tag and a non-tag. 03620 if (!Tag) return false; 03621 03622 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03623 Diag(Target->getLocation(), diag::note_using_decl_target); 03624 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 03625 return true; 03626 } 03627 03628 // No conflict between a tag and a non-tag. 03629 if (!NonTag) return false; 03630 03631 Diag(Using->getLocation(), diag::err_using_decl_conflict); 03632 Diag(Target->getLocation(), diag::note_using_decl_target); 03633 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 03634 return true; 03635 } 03636 03637 /// Builds a shadow declaration corresponding to a 'using' declaration. 03638 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 03639 UsingDecl *UD, 03640 NamedDecl *Orig) { 03641 03642 // If we resolved to another shadow declaration, just coalesce them. 03643 NamedDecl *Target = Orig; 03644 if (isa<UsingShadowDecl>(Target)) { 03645 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 03646 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 03647 } 03648 03649 UsingShadowDecl *Shadow 03650 = UsingShadowDecl::Create(Context, CurContext, 03651 UD->getLocation(), UD, Target); 03652 UD->addShadowDecl(Shadow); 03653 03654 if (S) 03655 PushOnScopeChains(Shadow, S); 03656 else 03657 CurContext->addDecl(Shadow); 03658 Shadow->setAccess(UD->getAccess()); 03659 03660 // Register it as a conversion if appropriate. 03661 if (Shadow->getDeclName().getNameKind() 03662 == DeclarationName::CXXConversionFunctionName) 03663 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow); 03664 03665 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 03666 Shadow->setInvalidDecl(); 03667 03668 return Shadow; 03669 } 03670 03671 /// Hides a using shadow declaration. This is required by the current 03672 /// using-decl implementation when a resolvable using declaration in a 03673 /// class is followed by a declaration which would hide or override 03674 /// one or more of the using decl's targets; for example: 03675 /// 03676 /// struct Base { void foo(int); }; 03677 /// struct Derived : Base { 03678 /// using Base::foo; 03679 /// void foo(int); 03680 /// }; 03681 /// 03682 /// The governing language is C++03 [namespace.udecl]p12: 03683 /// 03684 /// When a using-declaration brings names from a base class into a 03685 /// derived class scope, member functions in the derived class 03686 /// override and/or hide member functions with the same name and 03687 /// parameter types in a base class (rather than conflicting). 03688 /// 03689 /// There are two ways to implement this: 03690 /// (1) optimistically create shadow decls when they're not hidden 03691 /// by existing declarations, or 03692 /// (2) don't create any shadow decls (or at least don't make them 03693 /// visible) until we've fully parsed/instantiated the class. 03694 /// The problem with (1) is that we might have to retroactively remove 03695 /// a shadow decl, which requires several O(n) operations because the 03696 /// decl structures are (very reasonably) not designed for removal. 03697 /// (2) avoids this but is very fiddly and phase-dependent. 03698 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 03699 if (Shadow->getDeclName().getNameKind() == 03700 DeclarationName::CXXConversionFunctionName) 03701 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 03702 03703 // Remove it from the DeclContext... 03704 Shadow->getDeclContext()->removeDecl(Shadow); 03705 03706 // ...and the scope, if applicable... 03707 if (S) { 03708 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 03709 IdResolver.RemoveDecl(Shadow); 03710 } 03711 03712 // ...and the using decl. 03713 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 03714 03715 // TODO: complain somehow if Shadow was used. It shouldn't 03716 // be possible for this to happen, because...? 03717 } 03718 03719 /// Builds a using declaration. 03720 /// 03721 /// \param IsInstantiation - Whether this call arises from an 03722 /// instantiation of an unresolved using declaration. We treat 03723 /// the lookup differently for these declarations. 03724 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 03725 SourceLocation UsingLoc, 03726 CXXScopeSpec &SS, 03727 SourceLocation IdentLoc, 03728 DeclarationName Name, 03729 AttributeList *AttrList, 03730 bool IsInstantiation, 03731 bool IsTypeName, 03732 SourceLocation TypenameLoc) { 03733 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 03734 assert(IdentLoc.isValid() && "Invalid TargetName location."); 03735 03736 // FIXME: We ignore attributes for now. 03737 delete AttrList; 03738 03739 if (SS.isEmpty()) { 03740 Diag(IdentLoc, diag::err_using_requires_qualname); 03741 return 0; 03742 } 03743 03744 // Do the redeclaration lookup in the current scope. 03745 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 03746 ForRedeclaration); 03747 Previous.setHideTags(false); 03748 if (S) { 03749 LookupName(Previous, S); 03750 03751 // It is really dumb that we have to do this. 03752 LookupResult::Filter F = Previous.makeFilter(); 03753 while (F.hasNext()) { 03754 NamedDecl *D = F.next(); 03755 if (!isDeclInScope(D, CurContext, S)) 03756 F.erase(); 03757 } 03758 F.done(); 03759 } else { 03760 assert(IsInstantiation && "no scope in non-instantiation"); 03761 assert(CurContext->isRecord() && "scope not record in instantiation"); 03762 LookupQualifiedName(Previous, CurContext); 03763 } 03764 03765 NestedNameSpecifier *NNS = 03766 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 03767 03768 // Check for invalid redeclarations. 03769 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 03770 return 0; 03771 03772 // Check for bad qualifiers. 03773 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 03774 return 0; 03775 03776 DeclContext *LookupContext = computeDeclContext(SS); 03777 NamedDecl *D; 03778 if (!LookupContext) { 03779 if (IsTypeName) { 03780 // FIXME: not all declaration name kinds are legal here 03781 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 03782 UsingLoc, TypenameLoc, 03783 SS.getRange(), NNS, 03784 IdentLoc, Name); 03785 } else { 03786 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 03787 UsingLoc, SS.getRange(), NNS, 03788 IdentLoc, Name); 03789 } 03790 } else { 03791 D = UsingDecl::Create(Context, CurContext, IdentLoc, 03792 SS.getRange(), UsingLoc, NNS, Name, 03793 IsTypeName); 03794 } 03795 D->setAccess(AS); 03796 CurContext->addDecl(D); 03797 03798 if (!LookupContext) return D; 03799 UsingDecl *UD = cast<UsingDecl>(D); 03800 03801 if (RequireCompleteDeclContext(SS, LookupContext)) { 03802 UD->setInvalidDecl(); 03803 return UD; 03804 } 03805 03806 // Look up the target name. 03807 03808 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 03809 03810 // Unlike most lookups, we don't always want to hide tag 03811 // declarations: tag names are visible through the using declaration 03812 // even if hidden by ordinary names, *except* in a dependent context 03813 // where it's important for the sanity of two-phase lookup. 03814 if (!IsInstantiation) 03815 R.setHideTags(false); 03816 03817 LookupQualifiedName(R, LookupContext); 03818 03819 if (R.empty()) { 03820 Diag(IdentLoc, diag::err_no_member) 03821 << Name << LookupContext << SS.getRange(); 03822 UD->setInvalidDecl(); 03823 return UD; 03824 } 03825 03826 if (R.isAmbiguous()) { 03827 UD->setInvalidDecl(); 03828 return UD; 03829 } 03830 03831 if (IsTypeName) { 03832 // If we asked for a typename and got a non-type decl, error out. 03833 if (!R.getAsSingle<TypeDecl>()) { 03834 Diag(IdentLoc, diag::err_using_typename_non_type); 03835 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 03836 Diag((*I)->getUnderlyingDecl()->getLocation(), 03837 diag::note_using_decl_target); 03838 UD->setInvalidDecl(); 03839 return UD; 03840 } 03841 } else { 03842 // If we asked for a non-typename and we got a type, error out, 03843 // but only if this is an instantiation of an unresolved using 03844 // decl. Otherwise just silently find the type name. 03845 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 03846 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 03847 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 03848 UD->setInvalidDecl(); 03849 return UD; 03850 } 03851 } 03852 03853 // C++0x N2914 [namespace.udecl]p6: 03854 // A using-declaration shall not name a namespace. 03855 if (R.getAsSingle<NamespaceDecl>()) { 03856 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 03857 << SS.getRange(); 03858 UD->setInvalidDecl(); 03859 return UD; 03860 } 03861 03862 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 03863 if (!CheckUsingShadowDecl(UD, *I, Previous)) 03864 BuildUsingShadowDecl(S, UD, *I); 03865 } 03866 03867 return UD; 03868 } 03869 03870 /// Checks that the given using declaration is not an invalid 03871 /// redeclaration. Note that this is checking only for the using decl 03872 /// itself, not for any ill-formedness among the UsingShadowDecls. 03873 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 03874 bool isTypeName, 03875 const CXXScopeSpec &SS, 03876 SourceLocation NameLoc, 03877 const LookupResult &Prev) { 03878 // C++03 [namespace.udecl]p8: 03879 // C++0x [namespace.udecl]p10: 03880 // A using-declaration is a declaration and can therefore be used 03881 // repeatedly where (and only where) multiple declarations are 03882 // allowed. 03883 // That's only in file contexts. 03884 if (CurContext->getLookupContext()->isFileContext()) 03885 return false; 03886 03887 NestedNameSpecifier *Qual 03888 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 03889 03890 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 03891 NamedDecl *D = *I; 03892 03893 bool DTypename; 03894 NestedNameSpecifier *DQual; 03895 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 03896 DTypename = UD->isTypeName(); 03897 DQual = UD->getTargetNestedNameDecl(); 03898 } else if (UnresolvedUsingValueDecl *UD 03899 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 03900 DTypename = false; 03901 DQual = UD->getTargetNestedNameSpecifier(); 03902 } else if (UnresolvedUsingTypenameDecl *UD 03903 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 03904 DTypename = true; 03905 DQual = UD->getTargetNestedNameSpecifier(); 03906 } else continue; 03907 03908 // using decls differ if one says 'typename' and the other doesn't. 03909 // FIXME: non-dependent using decls? 03910 if (isTypeName != DTypename) continue; 03911 03912 // using decls differ if they name different scopes (but note that 03913 // template instantiation can cause this check to trigger when it 03914 // didn't before instantiation). 03915 if (Context.getCanonicalNestedNameSpecifier(Qual) != 03916 Context.getCanonicalNestedNameSpecifier(DQual)) 03917 continue; 03918 03919 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 03920 Diag(D->getLocation(), diag::note_using_decl) << 1; 03921 return true; 03922 } 03923 03924 return false; 03925 } 03926 03927 03928 /// Checks that the given nested-name qualifier used in a using decl 03929 /// in the current context is appropriately related to the current 03930 /// scope. If an error is found, diagnoses it and returns true. 03931 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 03932 const CXXScopeSpec &SS, 03933 SourceLocation NameLoc) { 03934 DeclContext *NamedContext = computeDeclContext(SS); 03935 03936 if (!CurContext->isRecord()) { 03937 // C++03 [namespace.udecl]p3: 03938 // C++0x [namespace.udecl]p8: 03939 // A using-declaration for a class member shall be a member-declaration. 03940 03941 // If we weren't able to compute a valid scope, it must be a 03942 // dependent class scope. 03943 if (!NamedContext || NamedContext->isRecord()) { 03944 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 03945 << SS.getRange(); 03946 return true; 03947 } 03948 03949 // Otherwise, everything is known to be fine. 03950 return false; 03951 } 03952 03953 // The current scope is a record. 03954 03955 // If the named context is dependent, we can't decide much. 03956 if (!NamedContext) { 03957 // FIXME: in C++0x, we can diagnose if we can prove that the 03958 // nested-name-specifier does not refer to a base class, which is 03959 // still possible in some cases. 03960 03961 // Otherwise we have to conservatively report that things might be 03962 // okay. 03963 return false; 03964 } 03965 03966 if (!NamedContext->isRecord()) { 03967 // Ideally this would point at the last name in the specifier, 03968 // but we don't have that level of source info. 03969 Diag(SS.getRange().getBegin(), 03970 diag::err_using_decl_nested_name_specifier_is_not_class) 03971 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 03972 return true; 03973 } 03974 03975 if (getLangOptions().CPlusPlus0x) { 03976 // C++0x [namespace.udecl]p3: 03977 // In a using-declaration used as a member-declaration, the 03978 // nested-name-specifier shall name a base class of the class 03979 // being defined. 03980 03981 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 03982 cast<CXXRecordDecl>(NamedContext))) { 03983 if (CurContext == NamedContext) { 03984 Diag(NameLoc, 03985 diag::err_using_decl_nested_name_specifier_is_current_class) 03986 << SS.getRange(); 03987 return true; 03988 } 03989 03990 Diag(SS.getRange().getBegin(), 03991 diag::err_using_decl_nested_name_specifier_is_not_base_class) 03992 << (NestedNameSpecifier*) SS.getScopeRep() 03993 << cast<CXXRecordDecl>(CurContext) 03994 << SS.getRange(); 03995 return true; 03996 } 03997 03998 return false; 03999 } 04000 04001 // C++03 [namespace.udecl]p4: 04002 // A using-declaration used as a member-declaration shall refer 04003 // to a member of a base class of the class being defined [etc.]. 04004 04005 // Salient point: SS doesn't have to name a base class as long as 04006 // lookup only finds members from base classes. Therefore we can 04007 // diagnose here only if we can prove that that can't happen, 04008 // i.e. if the class hierarchies provably don't intersect. 04009 04010 // TODO: it would be nice if "definitely valid" results were cached 04011 // in the UsingDecl and UsingShadowDecl so that these checks didn't 04012 // need to be repeated. 04013 04014 struct UserData { 04015 llvm::DenseSet<const CXXRecordDecl*> Bases; 04016 04017 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 04018 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 04019 Data->Bases.insert(Base); 04020 return true; 04021 } 04022 04023 bool hasDependentBases(const CXXRecordDecl *Class) { 04024 return !Class->forallBases(collect, this); 04025 } 04026 04027 /// Returns true if the base is dependent or is one of the 04028 /// accumulated base classes. 04029 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 04030 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 04031 return !Data->Bases.count(Base); 04032 } 04033 04034 bool mightShareBases(const CXXRecordDecl *Class) { 04035 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 04036 } 04037 }; 04038 04039 UserData Data; 04040 04041 // Returns false if we find a dependent base. 04042 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 04043 return false; 04044 04045 // Returns false if the class has a dependent base or if it or one 04046 // of its bases is present in the base set of the current context. 04047 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 04048 return false; 04049 04050 Diag(SS.getRange().getBegin(), 04051 diag::err_using_decl_nested_name_specifier_is_not_base_class) 04052 << (NestedNameSpecifier*) SS.getScopeRep() 04053 << cast<CXXRecordDecl>(CurContext) 04054 << SS.getRange(); 04055 04056 return true; 04057 } 04058 04059 Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 04060 SourceLocation NamespaceLoc, 04061 SourceLocation AliasLoc, 04062 IdentifierInfo *Alias, 04063 CXXScopeSpec &SS, 04064 SourceLocation IdentLoc, 04065 IdentifierInfo *Ident) { 04066 04067 // Lookup the namespace name. 04068 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 04069 LookupParsedName(R, S, &SS); 04070 04071 // Check if we have a previous declaration with the same name. 04072 NamedDecl *PrevDecl 04073 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 04074 ForRedeclaration); 04075 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 04076 PrevDecl = 0; 04077 04078 if (PrevDecl) { 04079 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 04080 // We already have an alias with the same name that points to the same 04081 // namespace, so don't create a new one. 04082 // FIXME: At some point, we'll want to create the (redundant) 04083 // declaration to maintain better source information. 04084 if (!R.isAmbiguous() && !R.empty() && 04085 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 04086 return DeclPtrTy(); 04087 } 04088 04089 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 04090 diag::err_redefinition_different_kind; 04091 Diag(AliasLoc, DiagID) << Alias; 04092 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 04093 return DeclPtrTy(); 04094 } 04095 04096 if (R.isAmbiguous()) 04097 return DeclPtrTy(); 04098 04099 if (R.empty()) { 04100 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 04101 return DeclPtrTy(); 04102 } 04103 04104 NamespaceAliasDecl *AliasDecl = 04105 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 04106 Alias, SS.getRange(), 04107 (NestedNameSpecifier *)SS.getScopeRep(), 04108 IdentLoc, R.getFoundDecl()); 04109 04110 PushOnScopeChains(AliasDecl, S); 04111 return DeclPtrTy::make(AliasDecl); 04112 } 04113 04114 namespace { 04115 /// \brief Scoped object used to handle the state changes required in Sema 04116 /// to implicitly define the body of a C++ member function; 04117 class ImplicitlyDefinedFunctionScope { 04118 Sema &S; 04119 DeclContext *PreviousContext; 04120 04121 public: 04122 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 04123 : S(S), PreviousContext(S.CurContext) 04124 { 04125 S.CurContext = Method; 04126 S.PushFunctionScope(); 04127 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 04128 } 04129 04130 ~ImplicitlyDefinedFunctionScope() { 04131 S.PopExpressionEvaluationContext(); 04132 S.PopFunctionOrBlockScope(); 04133 S.CurContext = PreviousContext; 04134 } 04135 }; 04136 } 04137 04138 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 04139 CXXConstructorDecl *Constructor) { 04140 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 04141 !Constructor->isUsed()) && 04142 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 04143 04144 CXXRecordDecl *ClassDecl = Constructor->getParent(); 04145 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 04146 04147 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 04148 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) { 04149 Diag(CurrentLocation, diag::note_member_synthesized_at) 04150 << CXXConstructor << Context.getTagDeclType(ClassDecl); 04151 Constructor->setInvalidDecl(); 04152 } else { 04153 Constructor->setUsed(); 04154 } 04155 } 04156 04157 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 04158 CXXDestructorDecl *Destructor) { 04159 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 04160 "DefineImplicitDestructor - call it for implicit default dtor"); 04161 CXXRecordDecl *ClassDecl = Destructor->getParent(); 04162 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 04163 04164 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 04165 04166 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 04167 Destructor->getParent()); 04168 04169 // FIXME: If CheckDestructor fails, we should emit a note about where the 04170 // implicit destructor was needed. 04171 if (CheckDestructor(Destructor)) { 04172 Diag(CurrentLocation, diag::note_member_synthesized_at) 04173 << CXXDestructor << Context.getTagDeclType(ClassDecl); 04174 04175 Destructor->setInvalidDecl(); 04176 return; 04177 } 04178 04179 Destructor->setUsed(); 04180 } 04181 04182 /// \brief Builds a statement that copies the given entity from \p From to 04183 /// \c To. 04184 /// 04185 /// This routine is used to copy the members of a class with an 04186 /// implicitly-declared copy assignment operator. When the entities being 04187 /// copied are arrays, this routine builds for loops to copy them. 04188 /// 04189 /// \param S The Sema object used for type-checking. 04190 /// 04191 /// \param Loc The location where the implicit copy is being generated. 04192 /// 04193 /// \param T The type of the expressions being copied. Both expressions must 04194 /// have this type. 04195 /// 04196 /// \param To The expression we are copying to. 04197 /// 04198 /// \param From The expression we are copying from. 04199 /// 04200 /// \param CopyingBaseSubobject Whether we're copying a base subobject. 04201 /// Otherwise, it's a non-static member subobject. 04202 /// 04203 /// \param Depth Internal parameter recording the depth of the recursion. 04204 /// 04205 /// \returns A statement or a loop that copies the expressions. 04206 static Sema::OwningStmtResult 04207 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 04208 Sema::OwningExprResult To, Sema::OwningExprResult From, 04209 bool CopyingBaseSubobject, unsigned Depth = 0) { 04210 typedef Sema::OwningStmtResult OwningStmtResult; 04211 typedef Sema::OwningExprResult OwningExprResult; 04212 04213 // C++0x [class.copy]p30: 04214 // Each subobject is assigned in the manner appropriate to its type: 04215 // 04216 // - if the subobject is of class type, the copy assignment operator 04217 // for the class is used (as if by explicit qualification; that is, 04218 // ignoring any possible virtual overriding functions in more derived 04219 // classes); 04220 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 04221 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 04222 04223 // Look for operator=. 04224 DeclarationName Name 04225 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 04226 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 04227 S.LookupQualifiedName(OpLookup, ClassDecl, false); 04228 04229 // Filter out any result that isn't a copy-assignment operator. 04230 LookupResult::Filter F = OpLookup.makeFilter(); 04231 while (F.hasNext()) { 04232 NamedDecl *D = F.next(); 04233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 04234 if (Method->isCopyAssignmentOperator()) 04235 continue; 04236 04237 F.erase(); 04238 } 04239 F.done(); 04240 04241 // Suppress the protected check (C++ [class.protected]) for each of the 04242 // assignment operators we found. This strange dance is required when 04243 // we're assigning via a base classes's copy-assignment operator. To 04244 // ensure that we're getting the right base class subobject (without 04245 // ambiguities), we need to cast "this" to that subobject type; to 04246 // ensure that we don't go through the virtual call mechanism, we need 04247 // to qualify the operator= name with the base class (see below). However, 04248 // this means that if the base class has a protected copy assignment 04249 // operator, the protected member access check will fail. So, we 04250 // rewrite "protected" access to "public" access in this case, since we 04251 // know by construction that we're calling from a derived class. 04252 if (CopyingBaseSubobject) { 04253 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 04254 L != LEnd; ++L) { 04255 if (L.getAccess() == AS_protected) 04256 L.setAccess(AS_public); 04257 } 04258 } 04259 04260 // Create the nested-name-specifier that will be used to qualify the 04261 // reference to operator=; this is required to suppress the virtual 04262 // call mechanism. 04263 CXXScopeSpec SS; 04264 SS.setRange(Loc); 04265 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false, 04266 T.getTypePtr())); 04267 04268 // Create the reference to operator=. 04269 OwningExprResult OpEqualRef 04270 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS, 04271 /*FirstQualifierInScope=*/0, OpLookup, 04272 /*TemplateArgs=*/0, 04273 /*SuppressQualifierCheck=*/true); 04274 if (OpEqualRef.isInvalid()) 04275 return S.StmtError(); 04276 04277 // Build the call to the assignment operator. 04278 Expr *FromE = From.takeAs<Expr>(); 04279 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 04280 OpEqualRef.takeAs<Expr>(), 04281 Loc, &FromE, 1, 0, Loc); 04282 if (Call.isInvalid()) 04283 return S.StmtError(); 04284 04285 return S.Owned(Call.takeAs<Stmt>()); 04286 } 04287 04288 // - if the subobject is of scalar type, the built-in assignment 04289 // operator is used. 04290 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 04291 if (!ArrayTy) { 04292 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc, 04293 BinaryOperator::Assign, 04294 To.takeAs<Expr>(), 04295 From.takeAs<Expr>()); 04296 if (Assignment.isInvalid()) 04297 return S.StmtError(); 04298 04299 return S.Owned(Assignment.takeAs<Stmt>()); 04300 } 04301 04302 // - if the subobject is an array, each element is assigned, in the 04303 // manner appropriate to the element type; 04304 04305 // Construct a loop over the array bounds, e.g., 04306 // 04307 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 04308 // 04309 // that will copy each of the array elements. 04310 QualType SizeType = S.Context.getSizeType(); 04311 04312 // Create the iteration variable. 04313 IdentifierInfo *IterationVarName = 0; 04314 { 04315 llvm::SmallString<8> Str; 04316 llvm::raw_svector_ostream OS(Str); 04317 OS << "__i" << Depth; 04318 IterationVarName = &S.Context.Idents.get(OS.str()); 04319 } 04320 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, 04321 IterationVarName, SizeType, 04322 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 04323 VarDecl::None, VarDecl::None); 04324 04325 // Initialize the iteration variable to zero. 04326 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 04327 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc)); 04328 04329 // Create a reference to the iteration variable; we'll use this several 04330 // times throughout. 04331 Expr *IterationVarRef 04332 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>(); 04333 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 04334 04335 // Create the DeclStmt that holds the iteration variable. 04336 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 04337 04338 // Create the comparison against the array bound. 04339 llvm::APInt Upper = ArrayTy->getSize(); 04340 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType)); 04341 OwningExprResult Comparison 04342 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(), 04343 new (S.Context) IntegerLiteral(Upper, SizeType, Loc), 04344 BinaryOperator::NE, S.Context.BoolTy, Loc)); 04345 04346 // Create the pre-increment of the iteration variable. 04347 OwningExprResult Increment 04348 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(), 04349 UnaryOperator::PreInc, 04350 SizeType, Loc)); 04351 04352 // Subscript the "from" and "to" expressions with the iteration variable. 04353 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc, 04354 S.Owned(IterationVarRef->Retain()), 04355 Loc); 04356 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc, 04357 S.Owned(IterationVarRef->Retain()), 04358 Loc); 04359 assert(!From.isInvalid() && "Builtin subscripting can't fail!"); 04360 assert(!To.isInvalid() && "Builtin subscripting can't fail!"); 04361 04362 // Build the copy for an individual element of the array. 04363 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc, 04364 ArrayTy->getElementType(), 04365 move(To), move(From), 04366 CopyingBaseSubobject, Depth+1); 04367 if (Copy.isInvalid()) { 04368 InitStmt->Destroy(S.Context); 04369 return S.StmtError(); 04370 } 04371 04372 // Construct the loop that copies all elements of this array. 04373 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt), 04374 S.MakeFullExpr(Comparison), 04375 Sema::DeclPtrTy(), 04376 S.MakeFullExpr(Increment), 04377 Loc, move(Copy)); 04378 } 04379 04380 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 04381 CXXMethodDecl *CopyAssignOperator) { 04382 assert((CopyAssignOperator->isImplicit() && 04383 CopyAssignOperator->isOverloadedOperator() && 04384 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 04385 !CopyAssignOperator->isUsed()) && 04386 "DefineImplicitCopyAssignment called for wrong function"); 04387 04388 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 04389 04390 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 04391 CopyAssignOperator->setInvalidDecl(); 04392 return; 04393 } 04394 04395 CopyAssignOperator->setUsed(); 04396 04397 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 04398 04399 // C++0x [class.copy]p30: 04400 // The implicitly-defined or explicitly-defaulted copy assignment operator 04401 // for a non-union class X performs memberwise copy assignment of its 04402 // subobjects. The direct base classes of X are assigned first, in the 04403 // order of their declaration in the base-specifier-list, and then the 04404 // immediate non-static data members of X are assigned, in the order in 04405 // which they were declared in the class definition. 04406 04407 // The statements that form the synthesized function body. 04408 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this); 04409 04410 // The parameter for the "other" object, which we are copying from. 04411 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 04412 Qualifiers OtherQuals = Other->getType().getQualifiers(); 04413 QualType OtherRefType = Other->getType(); 04414 if (const LValueReferenceType *OtherRef 04415 = OtherRefType->getAs<LValueReferenceType>()) { 04416 OtherRefType = OtherRef->getPointeeType(); 04417 OtherQuals = OtherRefType.getQualifiers(); 04418 } 04419 04420 // Our location for everything implicitly-generated. 04421 SourceLocation Loc = CopyAssignOperator->getLocation(); 04422 04423 // Construct a reference to the "other" object. We'll be using this 04424 // throughout the generated ASTs. 04425 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>(); 04426 assert(OtherRef && "Reference to parameter cannot fail!"); 04427 04428 // Construct the "this" pointer. We'll be using this throughout the generated 04429 // ASTs. 04430 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 04431 assert(This && "Reference to this cannot fail!"); 04432 04433 // Assign base classes. 04434 bool Invalid = false; 04435 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 04436 E = ClassDecl->bases_end(); Base != E; ++Base) { 04437 // Form the assignment: 04438 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 04439 QualType BaseType = Base->getType().getUnqualifiedType(); 04440 CXXRecordDecl *BaseClassDecl = 0; 04441 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>()) 04442 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl()); 04443 else { 04444 Invalid = true; 04445 continue; 04446 } 04447 04448 // Construct the "from" expression, which is an implicit cast to the 04449 // appropriately-qualified base type. 04450 Expr *From = OtherRef->Retain(); 04451 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 04452 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true, 04453 CXXBaseSpecifierArray(Base)); 04454 04455 // Dereference "this". 04456 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref, 04457 Owned(This->Retain())); 04458 04459 // Implicitly cast "this" to the appropriately-qualified base type. 04460 Expr *ToE = To.takeAs<Expr>(); 04461 ImpCastExprToType(ToE, 04462 Context.getCVRQualifiedType(BaseType, 04463 CopyAssignOperator->getTypeQualifiers()), 04464 CastExpr::CK_UncheckedDerivedToBase, 04465 /*isLvalue=*/true, CXXBaseSpecifierArray(Base)); 04466 To = Owned(ToE); 04467 04468 // Build the copy. 04469 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 04470 move(To), Owned(From), 04471 /*CopyingBaseSubobject=*/true); 04472 if (Copy.isInvalid()) { 04473 Diag(CurrentLocation, diag::note_member_synthesized_at) 04474 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 04475 CopyAssignOperator->setInvalidDecl(); 04476 return; 04477 } 04478 04479 // Success! Record the copy. 04480 Statements.push_back(Copy.takeAs<Expr>()); 04481 } 04482 04483 // \brief Reference to the __builtin_memcpy function. 04484 Expr *BuiltinMemCpyRef = 0; 04485 04486 // Assign non-static members. 04487 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 04488 FieldEnd = ClassDecl->field_end(); 04489 Field != FieldEnd; ++Field) { 04490 // Check for members of reference type; we can't copy those. 04491 if (Field->getType()->isReferenceType()) { 04492 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 04493 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 04494 Diag(Field->getLocation(), diag::note_declared_at); 04495 Diag(CurrentLocation, diag::note_member_synthesized_at) 04496 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 04497 Invalid = true; 04498 continue; 04499 } 04500 04501 // Check for members of const-qualified, non-class type. 04502 QualType BaseType = Context.getBaseElementType(Field->getType()); 04503 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 04504 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 04505 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 04506 Diag(Field->getLocation(), diag::note_declared_at); 04507 Diag(CurrentLocation, diag::note_member_synthesized_at) 04508 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 04509 Invalid = true; 04510 continue; 04511 } 04512 04513 QualType FieldType = Field->getType().getNonReferenceType(); 04514 04515 // Build references to the field in the object we're copying from and to. 04516 CXXScopeSpec SS; // Intentionally empty 04517 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 04518 LookupMemberName); 04519 MemberLookup.addDecl(*Field); 04520 MemberLookup.resolveKind(); 04521 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()), 04522 OtherRefType, 04523 Loc, /*IsArrow=*/false, 04524 SS, 0, MemberLookup, 0); 04525 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()), 04526 This->getType(), 04527 Loc, /*IsArrow=*/true, 04528 SS, 0, MemberLookup, 0); 04529 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 04530 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 04531 04532 // If the field should be copied with __builtin_memcpy rather than via 04533 // explicit assignments, do so. This optimization only applies for arrays 04534 // of scalars and arrays of class type with trivial copy-assignment 04535 // operators. 04536 if (FieldType->isArrayType() && 04537 (!BaseType->isRecordType() || 04538 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 04539 ->hasTrivialCopyAssignment())) { 04540 // Compute the size of the memory buffer to be copied. 04541 QualType SizeType = Context.getSizeType(); 04542 llvm::APInt Size(Context.getTypeSize(SizeType), 04543 Context.getTypeSizeInChars(BaseType).getQuantity()); 04544 for (const ConstantArrayType *Array 04545 = Context.getAsConstantArrayType(FieldType); 04546 Array; 04547 Array = Context.getAsConstantArrayType(Array->getElementType())) { 04548 llvm::APInt ArraySize = Array->getSize(); 04549 ArraySize.zextOrTrunc(Size.getBitWidth()); 04550 Size *= ArraySize; 04551 } 04552 04553 // Take the address of the field references for "from" and "to". 04554 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From)); 04555 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To)); 04556 04557 // Create a reference to the __builtin_memcpy builtin function. 04558 if (!BuiltinMemCpyRef) { 04559 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 04560 LookupOrdinaryName); 04561 LookupName(R, TUScope, true); 04562 04563 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 04564 if (!BuiltinMemCpy) { 04565 // Something went horribly wrong earlier, and we will have complained 04566 // about it. 04567 Invalid = true; 04568 continue; 04569 } 04570 04571 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 04572 BuiltinMemCpy->getType(), 04573 Loc, 0).takeAs<Expr>(); 04574 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 04575 } 04576 04577 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this); 04578 CallArgs.push_back(To.takeAs<Expr>()); 04579 CallArgs.push_back(From.takeAs<Expr>()); 04580 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc)); 04581 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly 04582 Commas.push_back(Loc); 04583 Commas.push_back(Loc); 04584 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0, 04585 Owned(BuiltinMemCpyRef->Retain()), 04586 Loc, move_arg(CallArgs), 04587 Commas.data(), Loc); 04588 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 04589 Statements.push_back(Call.takeAs<Expr>()); 04590 continue; 04591 } 04592 04593 // Build the copy of this field. 04594 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 04595 move(To), move(From), 04596 /*CopyingBaseSubobject=*/false); 04597 if (Copy.isInvalid()) { 04598 Diag(CurrentLocation, diag::note_member_synthesized_at) 04599 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 04600 CopyAssignOperator->setInvalidDecl(); 04601 return; 04602 } 04603 04604 // Success! Record the copy. 04605 Statements.push_back(Copy.takeAs<Stmt>()); 04606 } 04607 04608 if (!Invalid) { 04609 // Add a "return *this;" 04610 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref, 04611 Owned(This->Retain())); 04612 04613 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj)); 04614 if (Return.isInvalid()) 04615 Invalid = true; 04616 else { 04617 Statements.push_back(Return.takeAs<Stmt>()); 04618 } 04619 } 04620 04621 if (Invalid) { 04622 CopyAssignOperator->setInvalidDecl(); 04623 return; 04624 } 04625 04626 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 04627 /*isStmtExpr=*/false); 04628 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 04629 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 04630 } 04631 04632 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 04633 CXXConstructorDecl *CopyConstructor, 04634 unsigned TypeQuals) { 04635 assert((CopyConstructor->isImplicit() && 04636 CopyConstructor->isCopyConstructor(TypeQuals) && 04637 !CopyConstructor->isUsed()) && 04638 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 04639 04640 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 04641 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 04642 04643 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 04644 04645 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) { 04646 Diag(CurrentLocation, diag::note_member_synthesized_at) 04647 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 04648 CopyConstructor->setInvalidDecl(); 04649 } else { 04650 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 04651 CopyConstructor->getLocation(), 04652 MultiStmtArg(*this, 0, 0), 04653 /*isStmtExpr=*/false) 04654 .takeAs<Stmt>()); 04655 } 04656 04657 CopyConstructor->setUsed(); 04658 } 04659 04660 Sema::OwningExprResult 04661 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 04662 CXXConstructorDecl *Constructor, 04663 MultiExprArg ExprArgs, 04664 bool RequiresZeroInit, 04665 CXXConstructExpr::ConstructionKind ConstructKind) { 04666 bool Elidable = false; 04667 04668 // C++0x [class.copy]p34: 04669 // When certain criteria are met, an implementation is allowed to 04670 // omit the copy/move construction of a class object, even if the 04671 // copy/move constructor and/or destructor for the object have 04672 // side effects. [...] 04673 // - when a temporary class object that has not been bound to a 04674 // reference (12.2) would be copied/moved to a class object 04675 // with the same cv-unqualified type, the copy/move operation 04676 // can be omitted by constructing the temporary object 04677 // directly into the target of the omitted copy/move 04678 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 04679 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 04680 Elidable = SubExpr->isTemporaryObject() && 04681 Context.hasSameUnqualifiedType(SubExpr->getType(), 04682 Context.getTypeDeclType(Constructor->getParent())); 04683 } 04684 04685 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 04686 Elidable, move(ExprArgs), RequiresZeroInit, 04687 ConstructKind); 04688 } 04689 04690 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 04691 /// including handling of its default argument expressions. 04692 Sema::OwningExprResult 04693 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 04694 CXXConstructorDecl *Constructor, bool Elidable, 04695 MultiExprArg ExprArgs, 04696 bool RequiresZeroInit, 04697 CXXConstructExpr::ConstructionKind ConstructKind) { 04698 unsigned NumExprs = ExprArgs.size(); 04699 Expr **Exprs = (Expr **)ExprArgs.release(); 04700 04701 MarkDeclarationReferenced(ConstructLoc, Constructor); 04702 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 04703 Constructor, Elidable, Exprs, NumExprs, 04704 RequiresZeroInit, ConstructKind)); 04705 } 04706 04707 bool Sema::InitializeVarWithConstructor(VarDecl *VD, 04708 CXXConstructorDecl *Constructor, 04709 MultiExprArg Exprs) { 04710 OwningExprResult TempResult = 04711 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 04712 move(Exprs)); 04713 if (TempResult.isInvalid()) 04714 return true; 04715 04716 Expr *Temp = TempResult.takeAs<Expr>(); 04717 MarkDeclarationReferenced(VD->getLocation(), Constructor); 04718 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 04719 VD->setInit(Temp); 04720 04721 return false; 04722 } 04723 04724 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 04725 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 04726 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 04727 !ClassDecl->hasTrivialDestructor()) { 04728 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context); 04729 MarkDeclarationReferenced(VD->getLocation(), Destructor); 04730 CheckDestructorAccess(VD->getLocation(), Destructor, 04731 PDiag(diag::err_access_dtor_var) 04732 << VD->getDeclName() 04733 << VD->getType()); 04734 } 04735 } 04736 04737 /// AddCXXDirectInitializerToDecl - This action is called immediately after 04738 /// ActOnDeclarator, when a C++ direct initializer is present. 04739 /// e.g: "int x(1);" 04740 void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 04741 SourceLocation LParenLoc, 04742 MultiExprArg Exprs, 04743 SourceLocation *CommaLocs, 04744 SourceLocation RParenLoc) { 04745 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 04746 Decl *RealDecl = Dcl.getAs<Decl>(); 04747 04748 // If there is no declaration, there was an error parsing it. Just ignore 04749 // the initializer. 04750 if (RealDecl == 0) 04751 return; 04752 04753 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 04754 if (!VDecl) { 04755 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 04756 RealDecl->setInvalidDecl(); 04757 return; 04758 } 04759 04760 // We will represent direct-initialization similarly to copy-initialization: 04761 // int x(1); -as-> int x = 1; 04762 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 04763 // 04764 // Clients that want to distinguish between the two forms, can check for 04765 // direct initializer using VarDecl::hasCXXDirectInitializer(). 04766 // A major benefit is that clients that don't particularly care about which 04767 // exactly form was it (like the CodeGen) can handle both cases without 04768 // special case code. 04769 04770 // C++ 8.5p11: 04771 // The form of initialization (using parentheses or '=') is generally 04772 // insignificant, but does matter when the entity being initialized has a 04773 // class type. 04774 QualType DeclInitType = VDecl->getType(); 04775 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 04776 DeclInitType = Context.getBaseElementType(Array); 04777 04778 if (!VDecl->getType()->isDependentType() && 04779 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 04780 diag::err_typecheck_decl_incomplete_type)) { 04781 VDecl->setInvalidDecl(); 04782 return; 04783 } 04784 04785 // The variable can not have an abstract class type. 04786 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 04787 diag::err_abstract_type_in_decl, 04788 AbstractVariableType)) 04789 VDecl->setInvalidDecl(); 04790 04791 const VarDecl *Def; 04792 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 04793 Diag(VDecl->getLocation(), diag::err_redefinition) 04794 << VDecl->getDeclName(); 04795 Diag(Def->getLocation(), diag::note_previous_definition); 04796 VDecl->setInvalidDecl(); 04797 return; 04798 } 04799 04800 // If either the declaration has a dependent type or if any of the 04801 // expressions is type-dependent, we represent the initialization 04802 // via a ParenListExpr for later use during template instantiation. 04803 if (VDecl->getType()->isDependentType() || 04804 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 04805 // Let clients know that initialization was done with a direct initializer. 04806 VDecl->setCXXDirectInitializer(true); 04807 04808 // Store the initialization expressions as a ParenListExpr. 04809 unsigned NumExprs = Exprs.size(); 04810 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 04811 (Expr **)Exprs.release(), 04812 NumExprs, RParenLoc)); 04813 return; 04814 } 04815 04816 // Capture the variable that is being initialized and the style of 04817 // initialization. 04818 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 04819 04820 // FIXME: Poor source location information. 04821 InitializationKind Kind 04822 = InitializationKind::CreateDirect(VDecl->getLocation(), 04823 LParenLoc, RParenLoc); 04824 04825 InitializationSequence InitSeq(*this, Entity, Kind, 04826 (Expr**)Exprs.get(), Exprs.size()); 04827 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 04828 if (Result.isInvalid()) { 04829 VDecl->setInvalidDecl(); 04830 return; 04831 } 04832 04833 Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 04834 VDecl->setInit(Result.takeAs<Expr>()); 04835 VDecl->setCXXDirectInitializer(true); 04836 04837 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 04838 FinalizeVarWithDestructor(VDecl, Record); 04839 } 04840 04841 /// \brief Given a constructor and the set of arguments provided for the 04842 /// constructor, convert the arguments and add any required default arguments 04843 /// to form a proper call to this constructor. 04844 /// 04845 /// \returns true if an error occurred, false otherwise. 04846 bool 04847 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 04848 MultiExprArg ArgsPtr, 04849 SourceLocation Loc, 04850 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 04851 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 04852 unsigned NumArgs = ArgsPtr.size(); 04853 Expr **Args = (Expr **)ArgsPtr.get(); 04854 04855 const FunctionProtoType *Proto 04856 = Constructor->getType()->getAs<FunctionProtoType>(); 04857 assert(Proto && "Constructor without a prototype?"); 04858 unsigned NumArgsInProto = Proto->getNumArgs(); 04859 04860 // If too few arguments are available, we'll fill in the rest with defaults. 04861 if (NumArgs < NumArgsInProto) 04862 ConvertedArgs.reserve(NumArgsInProto); 04863 else 04864 ConvertedArgs.reserve(NumArgs); 04865 04866 VariadicCallType CallType = 04867 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 04868 llvm::SmallVector<Expr *, 8> AllArgs; 04869 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 04870 Proto, 0, Args, NumArgs, AllArgs, 04871 CallType); 04872 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 04873 ConvertedArgs.push_back(AllArgs[i]); 04874 return Invalid; 04875 } 04876 04877 static inline bool 04878 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 04879 const FunctionDecl *FnDecl) { 04880 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 04881 if (isa<NamespaceDecl>(DC)) { 04882 return SemaRef.Diag(FnDecl->getLocation(), 04883 diag::err_operator_new_delete_declared_in_namespace) 04884 << FnDecl->getDeclName(); 04885 } 04886 04887 if (isa<TranslationUnitDecl>(DC) && 04888 FnDecl->getStorageClass() == FunctionDecl::Static) { 04889 return SemaRef.Diag(FnDecl->getLocation(), 04890 diag::err_operator_new_delete_declared_static) 04891 << FnDecl->getDeclName(); 04892 } 04893 04894 return false; 04895 } 04896 04897 static inline bool 04898 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 04899 CanQualType ExpectedResultType, 04900 CanQualType ExpectedFirstParamType, 04901 unsigned DependentParamTypeDiag, 04902 unsigned InvalidParamTypeDiag) { 04903 QualType ResultType = 04904 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 04905 04906 // Check that the result type is not dependent. 04907 if (ResultType->isDependentType()) 04908 return SemaRef.Diag(FnDecl->getLocation(), 04909 diag::err_operator_new_delete_dependent_result_type) 04910 << FnDecl->getDeclName() << ExpectedResultType; 04911 04912 // Check that the result type is what we expect. 04913 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 04914 return SemaRef.Diag(FnDecl->getLocation(), 04915 diag::err_operator_new_delete_invalid_result_type) 04916 << FnDecl->getDeclName() << ExpectedResultType; 04917 04918 // A function template must have at least 2 parameters. 04919 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 04920 return SemaRef.Diag(FnDecl->getLocation(), 04921 diag::err_operator_new_delete_template_too_few_parameters) 04922 << FnDecl->getDeclName(); 04923 04924 // The function decl must have at least 1 parameter. 04925 if (FnDecl->getNumParams() == 0) 04926 return SemaRef.Diag(FnDecl->getLocation(), 04927 diag::err_operator_new_delete_too_few_parameters) 04928 << FnDecl->getDeclName(); 04929 04930 // Check the the first parameter type is not dependent. 04931 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 04932 if (FirstParamType->isDependentType()) 04933 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 04934 << FnDecl->getDeclName() << ExpectedFirstParamType; 04935 04936 // Check that the first parameter type is what we expect. 04937 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 04938 ExpectedFirstParamType) 04939 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 04940 << FnDecl->getDeclName() << ExpectedFirstParamType; 04941 04942 return false; 04943 } 04944 04945 static bool 04946 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 04947 // C++ [basic.stc.dynamic.allocation]p1: 04948 // A program is ill-formed if an allocation function is declared in a 04949 // namespace scope other than global scope or declared static in global 04950 // scope. 04951 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 04952 return true; 04953 04954 CanQualType SizeTy = 04955 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 04956 04957 // C++ [basic.stc.dynamic.allocation]p1: 04958 // The return type shall be void*. The first parameter shall have type 04959 // std::size_t. 04960 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 04961 SizeTy, 04962 diag::err_operator_new_dependent_param_type, 04963 diag::err_operator_new_param_type)) 04964 return true; 04965 04966 // C++ [basic.stc.dynamic.allocation]p1: 04967 // The first parameter shall not have an associated default argument. 04968 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 04969 return SemaRef.Diag(FnDecl->getLocation(), 04970 diag::err_operator_new_default_arg) 04971 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 04972 04973 return false; 04974 } 04975 04976 static bool 04977 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 04978 // C++ [basic.stc.dynamic.deallocation]p1: 04979 // A program is ill-formed if deallocation functions are declared in a 04980 // namespace scope other than global scope or declared static in global 04981 // scope. 04982 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 04983 return true; 04984 04985 // C++ [basic.stc.dynamic.deallocation]p2: 04986 // Each deallocation function shall return void and its first parameter 04987 // shall be void*. 04988 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 04989 SemaRef.Context.VoidPtrTy, 04990 diag::err_operator_delete_dependent_param_type, 04991 diag::err_operator_delete_param_type)) 04992 return true; 04993 04994 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 04995 if (FirstParamType->isDependentType()) 04996 return SemaRef.Diag(FnDecl->getLocation(), 04997 diag::err_operator_delete_dependent_param_type) 04998 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 04999 05000 if (SemaRef.Context.getCanonicalType(FirstParamType) != 05001 SemaRef.Context.VoidPtrTy) 05002 return SemaRef.Diag(FnDecl->getLocation(), 05003 diag::err_operator_delete_param_type) 05004 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 05005 05006 return false; 05007 } 05008 05009 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 05010 /// of this overloaded operator is well-formed. If so, returns false; 05011 /// otherwise, emits appropriate diagnostics and returns true. 05012 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 05013 assert(FnDecl && FnDecl->isOverloadedOperator() && 05014 "Expected an overloaded operator declaration"); 05015 05016 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 05017 05018 // C++ [over.oper]p5: 05019 // The allocation and deallocation functions, operator new, 05020 // operator new[], operator delete and operator delete[], are 05021 // described completely in 3.7.3. The attributes and restrictions 05022 // found in the rest of this subclause do not apply to them unless 05023 // explicitly stated in 3.7.3. 05024 if (Op == OO_Delete || Op == OO_Array_Delete) 05025 return CheckOperatorDeleteDeclaration(*this, FnDecl); 05026 05027 if (Op == OO_New || Op == OO_Array_New) 05028 return CheckOperatorNewDeclaration(*this, FnDecl); 05029 05030 // C++ [over.oper]p6: 05031 // An operator function shall either be a non-static member 05032 // function or be a non-member function and have at least one 05033 // parameter whose type is a class, a reference to a class, an 05034 // enumeration, or a reference to an enumeration. 05035 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 05036 if (MethodDecl->isStatic()) 05037 return Diag(FnDecl->getLocation(), 05038 diag::err_operator_overload_static) << FnDecl->getDeclName(); 05039 } else { 05040 bool ClassOrEnumParam = false; 05041 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 05042 ParamEnd = FnDecl->param_end(); 05043 Param != ParamEnd; ++Param) { 05044 QualType ParamType = (*Param)->getType().getNonReferenceType(); 05045 if (ParamType->isDependentType() || ParamType->isRecordType() || 05046 ParamType->isEnumeralType()) { 05047 ClassOrEnumParam = true; 05048 break; 05049 } 05050 } 05051 05052 if (!ClassOrEnumParam) 05053 return Diag(FnDecl->getLocation(), 05054 diag::err_operator_overload_needs_class_or_enum) 05055 << FnDecl->getDeclName(); 05056 } 05057 05058 // C++ [over.oper]p8: 05059 // An operator function cannot have default arguments (8.3.6), 05060 // except where explicitly stated below. 05061 // 05062 // Only the function-call operator allows default arguments 05063 // (C++ [over.call]p1). 05064 if (Op != OO_Call) { 05065 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 05066 Param != FnDecl->param_end(); ++Param) { 05067 if ((*Param)->hasDefaultArg()) 05068 return Diag((*Param)->getLocation(), 05069 diag::err_operator_overload_default_arg) 05070 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 05071 } 05072 } 05073 05074 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 05075 { false, false, false } 05076 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 05077 , { Unary, Binary, MemberOnly } 05078 #include "clang/Basic/OperatorKinds.def" 05079 }; 05080 05081 bool CanBeUnaryOperator = OperatorUses[Op][0]; 05082 bool CanBeBinaryOperator = OperatorUses[Op][1]; 05083 bool MustBeMemberOperator = OperatorUses[Op][2]; 05084 05085 // C++ [over.oper]p8: 05086 // [...] Operator functions cannot have more or fewer parameters 05087 // than the number required for the corresponding operator, as 05088 // described in the rest of this subclause. 05089 unsigned NumParams = FnDecl->getNumParams() 05090 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 05091 if (Op != OO_Call && 05092 ((NumParams == 1 && !CanBeUnaryOperator) || 05093 (NumParams == 2 && !CanBeBinaryOperator) || 05094 (NumParams < 1) || (NumParams > 2))) { 05095 // We have the wrong number of parameters. 05096 unsigned ErrorKind; 05097 if (CanBeUnaryOperator && CanBeBinaryOperator) { 05098 ErrorKind = 2; // 2 -> unary or binary. 05099 } else if (CanBeUnaryOperator) { 05100 ErrorKind = 0; // 0 -> unary 05101 } else { 05102 assert(CanBeBinaryOperator && 05103 "All non-call overloaded operators are unary or binary!"); 05104 ErrorKind = 1; // 1 -> binary 05105 } 05106 05107 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 05108 << FnDecl->getDeclName() << NumParams << ErrorKind; 05109 } 05110 05111 // Overloaded operators other than operator() cannot be variadic. 05112 if (Op != OO_Call && 05113 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 05114 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 05115 << FnDecl->getDeclName(); 05116 } 05117 05118 // Some operators must be non-static member functions. 05119 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 05120 return Diag(FnDecl->getLocation(), 05121 diag::err_operator_overload_must_be_member) 05122 << FnDecl->getDeclName(); 05123 } 05124 05125 // C++ [over.inc]p1: 05126 // The user-defined function called operator++ implements the 05127 // prefix and postfix ++ operator. If this function is a member 05128 // function with no parameters, or a non-member function with one 05129 // parameter of class or enumeration type, it defines the prefix 05130 // increment operator ++ for objects of that type. If the function 05131 // is a member function with one parameter (which shall be of type 05132 // int) or a non-member function with two parameters (the second 05133 // of which shall be of type int), it defines the postfix 05134 // increment operator ++ for objects of that type. 05135 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 05136 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 05137 bool ParamIsInt = false; 05138 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 05139 ParamIsInt = BT->getKind() == BuiltinType::Int; 05140 05141 if (!ParamIsInt) 05142 return Diag(LastParam->getLocation(), 05143 diag::err_operator_overload_post_incdec_must_be_int) 05144 << LastParam->getType() << (Op == OO_MinusMinus); 05145 } 05146 05147 // Notify the class if it got an assignment operator. 05148 if (Op == OO_Equal) { 05149 // Would have returned earlier otherwise. 05150 assert(isa<CXXMethodDecl>(FnDecl) && 05151 "Overloaded = not member, but not filtered."); 05152 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 05153 Method->getParent()->addedAssignmentOperator(Context, Method); 05154 } 05155 05156 return false; 05157 } 05158 05159 /// CheckLiteralOperatorDeclaration - Check whether the declaration 05160 /// of this literal operator function is well-formed. If so, returns 05161 /// false; otherwise, emits appropriate diagnostics and returns true. 05162 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 05163 DeclContext *DC = FnDecl->getDeclContext(); 05164 Decl::Kind Kind = DC->getDeclKind(); 05165 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 05166 Kind != Decl::LinkageSpec) { 05167 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 05168 << FnDecl->getDeclName(); 05169 return true; 05170 } 05171 05172 bool Valid = false; 05173 05174 // template <char...> type operator "" name() is the only valid template 05175 // signature, and the only valid signature with no parameters. 05176 if (FnDecl->param_size() == 0) { 05177 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 05178 // Must have only one template parameter 05179 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 05180 if (Params->size() == 1) { 05181 NonTypeTemplateParmDecl *PmDecl = 05182 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 05183 05184 // The template parameter must be a char parameter pack. 05185 // FIXME: This test will always fail because non-type parameter packs 05186 // have not been implemented. 05187 if (PmDecl && PmDecl->isTemplateParameterPack() && 05188 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 05189 Valid = true; 05190 } 05191 } 05192 } else { 05193 // Check the first parameter 05194 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 05195 05196 QualType T = (*Param)->getType(); 05197 05198 // unsigned long long int, long double, and any character type are allowed 05199 // as the only parameters. 05200 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 05201 Context.hasSameType(T, Context.LongDoubleTy) || 05202 Context.hasSameType(T, Context.CharTy) || 05203 Context.hasSameType(T, Context.WCharTy) || 05204 Context.hasSameType(T, Context.Char16Ty) || 05205 Context.hasSameType(T, Context.Char32Ty)) { 05206 if (++Param == FnDecl->param_end()) 05207 Valid = true; 05208 goto FinishedParams; 05209 } 05210 05211 // Otherwise it must be a pointer to const; let's strip those qualifiers. 05212 const PointerType *PT = T->getAs<PointerType>(); 05213 if (!PT) 05214 goto FinishedParams; 05215 T = PT->getPointeeType(); 05216 if (!T.isConstQualified()) 05217 goto FinishedParams; 05218 T = T.getUnqualifiedType(); 05219 05220 // Move on to the second parameter; 05221 ++Param; 05222 05223 // If there is no second parameter, the first must be a const char * 05224 if (Param == FnDecl->param_end()) { 05225 if (Context.hasSameType(T, Context.CharTy)) 05226 Valid = true; 05227 goto FinishedParams; 05228 } 05229 05230 // const char *, const wchar_t*, const char16_t*, and const char32_t* 05231 // are allowed as the first parameter to a two-parameter function 05232 if (!(Context.hasSameType(T, Context.CharTy) || 05233 Context.hasSameType(T, Context.WCharTy) || 05234 Context.hasSameType(T, Context.Char16Ty) || 05235 Context.hasSameType(T, Context.Char32Ty))) 05236 goto FinishedParams; 05237 05238 // The second and final parameter must be an std::size_t 05239 T = (*Param)->getType().getUnqualifiedType(); 05240 if (Context.hasSameType(T, Context.getSizeType()) && 05241 ++Param == FnDecl->param_end()) 05242 Valid = true; 05243 } 05244 05245 // FIXME: This diagnostic is absolutely terrible. 05246 FinishedParams: 05247 if (!Valid) { 05248 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 05249 << FnDecl->getDeclName(); 05250 return true; 05251 } 05252 05253 return false; 05254 } 05255 05256 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 05257 /// linkage specification, including the language and (if present) 05258 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is 05259 /// the location of the language string literal, which is provided 05260 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of 05261 /// the '{' brace. Otherwise, this linkage specification does not 05262 /// have any braces. 05263 Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 05264 SourceLocation ExternLoc, 05265 SourceLocation LangLoc, 05266 llvm::StringRef Lang, 05267 SourceLocation LBraceLoc) { 05268 LinkageSpecDecl::LanguageIDs Language; 05269 if (Lang == "\"C\"") 05270 Language = LinkageSpecDecl::lang_c; 05271 else if (Lang == "\"C++\"") 05272 Language = LinkageSpecDecl::lang_cxx; 05273 else { 05274 Diag(LangLoc, diag::err_bad_language); 05275 return DeclPtrTy(); 05276 } 05277 05278 // FIXME: Add all the various semantics of linkage specifications 05279 05280 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 05281 LangLoc, Language, 05282 LBraceLoc.isValid()); 05283 CurContext->addDecl(D); 05284 PushDeclContext(S, D); 05285 return DeclPtrTy::make(D); 05286 } 05287 05288 /// ActOnFinishLinkageSpecification - Completely the definition of 05289 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 05290 /// valid, it's the position of the closing '}' brace in a linkage 05291 /// specification that uses braces. 05292 Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 05293 DeclPtrTy LinkageSpec, 05294 SourceLocation RBraceLoc) { 05295 if (LinkageSpec) 05296 PopDeclContext(); 05297 return LinkageSpec; 05298 } 05299 05300 /// \brief Perform semantic analysis for the variable declaration that 05301 /// occurs within a C++ catch clause, returning the newly-created 05302 /// variable. 05303 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 05304 TypeSourceInfo *TInfo, 05305 IdentifierInfo *Name, 05306 SourceLocation Loc, 05307 SourceRange Range) { 05308 bool Invalid = false; 05309 05310 // Arrays and functions decay. 05311 if (ExDeclType->isArrayType()) 05312 ExDeclType = Context.getArrayDecayedType(ExDeclType); 05313 else if (ExDeclType->isFunctionType()) 05314 ExDeclType = Context.getPointerType(ExDeclType); 05315 05316 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 05317 // The exception-declaration shall not denote a pointer or reference to an 05318 // incomplete type, other than [cv] void*. 05319 // N2844 forbids rvalue references. 05320 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 05321 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 05322 Invalid = true; 05323 } 05324 05325 // GCC allows catching pointers and references to incomplete types 05326 // as an extension; so do we, but we warn by default. 05327 05328 QualType BaseType = ExDeclType; 05329 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 05330 unsigned DK = diag::err_catch_incomplete; 05331 bool IncompleteCatchIsInvalid = true; 05332 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 05333 BaseType = Ptr->getPointeeType(); 05334 Mode = 1; 05335 DK = diag::ext_catch_incomplete_ptr; 05336 IncompleteCatchIsInvalid = false; 05337 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 05338 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 05339 BaseType = Ref->getPointeeType(); 05340 Mode = 2; 05341 DK = diag::ext_catch_incomplete_ref; 05342 IncompleteCatchIsInvalid = false; 05343 } 05344 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 05345 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 05346 IncompleteCatchIsInvalid) 05347 Invalid = true; 05348 05349 if (!Invalid && !ExDeclType->isDependentType() && 05350 RequireNonAbstractType(Loc, ExDeclType, 05351 diag::err_abstract_type_in_decl, 05352 AbstractVariableType)) 05353 Invalid = true; 05354 05355 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 05356 Name, ExDeclType, TInfo, VarDecl::None, 05357 VarDecl::None); 05358 ExDecl->setExceptionVariable(true); 05359 05360 if (!Invalid) { 05361 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 05362 // C++ [except.handle]p16: 05363 // The object declared in an exception-declaration or, if the 05364 // exception-declaration does not specify a name, a temporary (12.2) is 05365 // copy-initialized (8.5) from the exception object. [...] 05366 // The object is destroyed when the handler exits, after the destruction 05367 // of any automatic objects initialized within the handler. 05368 // 05369 // We just pretend to initialize the object with itself, then make sure 05370 // it can be destroyed later. 05371 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 05372 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 05373 Loc, ExDeclType, 0); 05374 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 05375 SourceLocation()); 05376 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 05377 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 05378 MultiExprArg(*this, (void**)&ExDeclRef, 1)); 05379 if (Result.isInvalid()) 05380 Invalid = true; 05381 else 05382 FinalizeVarWithDestructor(ExDecl, RecordTy); 05383 } 05384 } 05385 05386 if (Invalid) 05387 ExDecl->setInvalidDecl(); 05388 05389 return ExDecl; 05390 } 05391 05392 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 05393 /// handler. 05394 Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 05395 TypeSourceInfo *TInfo = 0; 05396 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 05397 05398 bool Invalid = D.isInvalidType(); 05399 IdentifierInfo *II = D.getIdentifier(); 05400 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 05401 LookupOrdinaryName, 05402 ForRedeclaration)) { 05403 // The scope should be freshly made just for us. There is just no way 05404 // it contains any previous declaration. 05405 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 05406 if (PrevDecl->isTemplateParameter()) { 05407 // Maybe we will complain about the shadowed template parameter. 05408 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 05409 } 05410 } 05411 05412 if (D.getCXXScopeSpec().isSet() && !Invalid) { 05413 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 05414 << D.getCXXScopeSpec().getRange(); 05415 Invalid = true; 05416 } 05417 05418 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 05419 D.getIdentifier(), 05420 D.getIdentifierLoc(), 05421 D.getDeclSpec().getSourceRange()); 05422 05423 if (Invalid) 05424 ExDecl->setInvalidDecl(); 05425 05426 // Add the exception declaration into this scope. 05427 if (II) 05428 PushOnScopeChains(ExDecl, S); 05429 else 05430 CurContext->addDecl(ExDecl); 05431 05432 ProcessDeclAttributes(S, ExDecl, D); 05433 return DeclPtrTy::make(ExDecl); 05434 } 05435 05436 Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 05437 ExprArg assertexpr, 05438 ExprArg assertmessageexpr) { 05439 Expr *AssertExpr = (Expr *)assertexpr.get(); 05440 StringLiteral *AssertMessage = 05441 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 05442 05443 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 05444 llvm::APSInt Value(32); 05445 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 05446 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 05447 AssertExpr->getSourceRange(); 05448 return DeclPtrTy(); 05449 } 05450 05451 if (Value == 0) { 05452 Diag(AssertLoc, diag::err_static_assert_failed) 05453 << AssertMessage->getString() << AssertExpr->getSourceRange(); 05454 } 05455 } 05456 05457 assertexpr.release(); 05458 assertmessageexpr.release(); 05459 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 05460 AssertExpr, AssertMessage); 05461 05462 CurContext->addDecl(Decl); 05463 return DeclPtrTy::make(Decl); 05464 } 05465 05466 /// \brief Perform semantic analysis of the given friend type declaration. 05467 /// 05468 /// \returns A friend declaration that. 05469 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 05470 TypeSourceInfo *TSInfo) { 05471 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 05472 05473 QualType T = TSInfo->getType(); 05474 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange(); 05475 05476 if (!getLangOptions().CPlusPlus0x) { 05477 // C++03 [class.friend]p2: 05478 // An elaborated-type-specifier shall be used in a friend declaration 05479 // for a class.* 05480 // 05481 // * The class-key of the elaborated-type-specifier is required. 05482 if (!ActiveTemplateInstantiations.empty()) { 05483 // Do not complain about the form of friend template types during 05484 // template instantiation; we will already have complained when the 05485 // template was declared. 05486 } else if (!T->isElaboratedTypeSpecifier()) { 05487 // If we evaluated the type to a record type, suggest putting 05488 // a tag in front. 05489 if (const RecordType *RT = T->getAs<RecordType>()) { 05490 RecordDecl *RD = RT->getDecl(); 05491 05492 std::string InsertionText = std::string(" ") + RD->getKindName(); 05493 05494 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 05495 << (unsigned) RD->getTagKind() 05496 << T 05497 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 05498 InsertionText); 05499 } else { 05500 Diag(FriendLoc, diag::ext_nonclass_type_friend) 05501 << T 05502 << SourceRange(FriendLoc, TypeRange.getEnd()); 05503 } 05504 } else if (T->getAs<EnumType>()) { 05505 Diag(FriendLoc, diag::ext_enum_friend) 05506 << T 05507 << SourceRange(FriendLoc, TypeRange.getEnd()); 05508 } 05509 } 05510 05511 // C++0x [class.friend]p3: 05512 // If the type specifier in a friend declaration designates a (possibly 05513 // cv-qualified) class type, that class is declared as a friend; otherwise, 05514 // the friend declaration is ignored. 05515 05516 // FIXME: C++0x has some syntactic restrictions on friend type declarations 05517 // in [class.friend]p3 that we do not implement. 05518 05519 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 05520 } 05521 05522 /// Handle a friend type declaration. This works in tandem with 05523 /// ActOnTag. 05524 /// 05525 /// Notes on friend class templates: 05526 /// 05527 /// We generally treat friend class declarations as if they were 05528 /// declaring a class. So, for example, the elaborated type specifier 05529 /// in a friend declaration is required to obey the restrictions of a 05530 /// class-head (i.e. no typedefs in the scope chain), template 05531 /// parameters are required to match up with simple template-ids, &c. 05532 /// However, unlike when declaring a template specialization, it's 05533 /// okay to refer to a template specialization without an empty 05534 /// template parameter declaration, e.g. 05535 /// friend class A<T>::B<unsigned>; 05536 /// We permit this as a special case; if there are any template 05537 /// parameters present at all, require proper matching, i.e. 05538 /// template <> template <class T> friend class A<int>::B; 05539 Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 05540 MultiTemplateParamsArg TempParams) { 05541 SourceLocation Loc = DS.getSourceRange().getBegin(); 05542 05543 assert(DS.isFriendSpecified()); 05544 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 05545 05546 // Try to convert the decl specifier to a type. This works for 05547 // friend templates because ActOnTag never produces a ClassTemplateDecl 05548 // for a TUK_Friend. 05549 Declarator TheDeclarator(DS, Declarator::MemberContext); 05550 TypeSourceInfo *TSI; 05551 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI); 05552 if (TheDeclarator.isInvalidType()) 05553 return DeclPtrTy(); 05554 05555 if (!TSI) 05556 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin()); 05557 05558 // This is definitely an error in C++98. It's probably meant to 05559 // be forbidden in C++0x, too, but the specification is just 05560 // poorly written. 05561 // 05562 // The problem is with declarations like the following: 05563 // template <T> friend A<T>::foo; 05564 // where deciding whether a class C is a friend or not now hinges 05565 // on whether there exists an instantiation of A that causes 05566 // 'foo' to equal C. There are restrictions on class-heads 05567 // (which we declare (by fiat) elaborated friend declarations to 05568 // be) that makes this tractable. 05569 // 05570 // FIXME: handle "template <> friend class A<T>;", which 05571 // is possibly well-formed? Who even knows? 05572 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 05573 Diag(Loc, diag::err_tagless_friend_type_template) 05574 << DS.getSourceRange(); 05575 return DeclPtrTy(); 05576 } 05577 05578 // C++98 [class.friend]p1: A friend of a class is a function 05579 // or class that is not a member of the class . . . 05580 // This is fixed in DR77, which just barely didn't make the C++03 05581 // deadline. It's also a very silly restriction that seriously 05582 // affects inner classes and which nobody else seems to implement; 05583 // thus we never diagnose it, not even in -pedantic. 05584 // 05585 // But note that we could warn about it: it's always useless to 05586 // friend one of your own members (it's not, however, worthless to 05587 // friend a member of an arbitrary specialization of your template). 05588 05589 Decl *D; 05590 if (unsigned NumTempParamLists = TempParams.size()) 05591 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 05592 NumTempParamLists, 05593 (TemplateParameterList**) TempParams.release(), 05594 TSI, 05595 DS.getFriendSpecLoc()); 05596 else 05597 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 05598 05599 if (!D) 05600 return DeclPtrTy(); 05601 05602 D->setAccess(AS_public); 05603 CurContext->addDecl(D); 05604 05605 return DeclPtrTy::make(D); 05606 } 05607 05608 Sema::DeclPtrTy 05609 Sema::ActOnFriendFunctionDecl(Scope *S, 05610 Declarator &D, 05611 bool IsDefinition, 05612 MultiTemplateParamsArg TemplateParams) { 05613 const DeclSpec &DS = D.getDeclSpec(); 05614 05615 assert(DS.isFriendSpecified()); 05616 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 05617 05618 SourceLocation Loc = D.getIdentifierLoc(); 05619 TypeSourceInfo *TInfo = 0; 05620 QualType T = GetTypeForDeclarator(D, S, &TInfo); 05621 05622 // C++ [class.friend]p1 05623 // A friend of a class is a function or class.... 05624 // Note that this sees through typedefs, which is intended. 05625 // It *doesn't* see through dependent types, which is correct 05626 // according to [temp.arg.type]p3: 05627 // If a declaration acquires a function type through a 05628 // type dependent on a template-parameter and this causes 05629 // a declaration that does not use the syntactic form of a 05630 // function declarator to have a function type, the program 05631 // is ill-formed. 05632 if (!T->isFunctionType()) { 05633 Diag(Loc, diag::err_unexpected_friend); 05634 05635 // It might be worthwhile to try to recover by creating an 05636 // appropriate declaration. 05637 return DeclPtrTy(); 05638 } 05639 05640 // C++ [namespace.memdef]p3 05641 // - If a friend declaration in a non-local class first declares a 05642 // class or function, the friend class or function is a member 05643 // of the innermost enclosing namespace. 05644 // - The name of the friend is not found by simple name lookup 05645 // until a matching declaration is provided in that namespace 05646 // scope (either before or after the class declaration granting 05647 // friendship). 05648 // - If a friend function is called, its name may be found by the 05649 // name lookup that considers functions from namespaces and 05650 // classes associated with the types of the function arguments. 05651 // - When looking for a prior declaration of a class or a function 05652 // declared as a friend, scopes outside the innermost enclosing 05653 // namespace scope are not considered. 05654 05655 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 05656 DeclarationName Name = GetNameForDeclarator(D); 05657 assert(Name); 05658 05659 // The context we found the declaration in, or in which we should 05660 // create the declaration. 05661 DeclContext *DC; 05662 05663 // FIXME: handle local classes 05664 05665 // Recover from invalid scope qualifiers as if they just weren't there. 05666 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 05667 ForRedeclaration); 05668 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 05669 DC = computeDeclContext(ScopeQual); 05670 05671 // FIXME: handle dependent contexts 05672 if (!DC) return DeclPtrTy(); 05673 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy(); 05674 05675 LookupQualifiedName(Previous, DC); 05676 05677 // If searching in that context implicitly found a declaration in 05678 // a different context, treat it like it wasn't found at all. 05679 // TODO: better diagnostics for this case. Suggesting the right 05680 // qualified scope would be nice... 05681 // FIXME: getRepresentativeDecl() is not right here at all 05682 if (Previous.empty() || 05683 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) { 05684 D.setInvalidType(); 05685 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 05686 return DeclPtrTy(); 05687 } 05688 05689 // C++ [class.friend]p1: A friend of a class is a function or 05690 // class that is not a member of the class . . . 05691 if (DC->Equals(CurContext)) 05692 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 05693 05694 // Otherwise walk out to the nearest namespace scope looking for matches. 05695 } else { 05696 // TODO: handle local class contexts. 05697 05698 DC = CurContext; 05699 while (true) { 05700 // Skip class contexts. If someone can cite chapter and verse 05701 // for this behavior, that would be nice --- it's what GCC and 05702 // EDG do, and it seems like a reasonable intent, but the spec 05703 // really only says that checks for unqualified existing 05704 // declarations should stop at the nearest enclosing namespace, 05705 // not that they should only consider the nearest enclosing 05706 // namespace. 05707 while (DC->isRecord()) 05708 DC = DC->getParent(); 05709 05710 LookupQualifiedName(Previous, DC); 05711 05712 // TODO: decide what we think about using declarations. 05713 if (!Previous.empty()) 05714 break; 05715 05716 if (DC->isFileContext()) break; 05717 DC = DC->getParent(); 05718 } 05719 05720 // C++ [class.friend]p1: A friend of a class is a function or 05721 // class that is not a member of the class . . . 05722 // C++0x changes this for both friend types and functions. 05723 // Most C++ 98 compilers do seem to give an error here, so 05724 // we do, too. 05725 if (!Previous.empty() && DC->Equals(CurContext) 05726 && !getLangOptions().CPlusPlus0x) 05727 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 05728 } 05729 05730 if (DC->isFileContext()) { 05731 // This implies that it has to be an operator or function. 05732 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 05733 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 05734 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 05735 Diag(Loc, diag::err_introducing_special_friend) << 05736 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 05737 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 05738 return DeclPtrTy(); 05739 } 05740 } 05741 05742 bool Redeclaration = false; 05743 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 05744 move(TemplateParams), 05745 IsDefinition, 05746 Redeclaration); 05747 if (!ND) return DeclPtrTy(); 05748 05749 assert(ND->getDeclContext() == DC); 05750 assert(ND->getLexicalDeclContext() == CurContext); 05751 05752 // Add the function declaration to the appropriate lookup tables, 05753 // adjusting the redeclarations list as necessary. We don't 05754 // want to do this yet if the friending class is dependent. 05755 // 05756 // Also update the scope-based lookup if the target context's 05757 // lookup context is in lexical scope. 05758 if (!CurContext->isDependentContext()) { 05759 DC = DC->getLookupContext(); 05760 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 05761 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 05762 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 05763 } 05764 05765 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 05766 D.getIdentifierLoc(), ND, 05767 DS.getFriendSpecLoc()); 05768 FrD->setAccess(AS_public); 05769 CurContext->addDecl(FrD); 05770 05771 return DeclPtrTy::make(ND); 05772 } 05773 05774 void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 05775 AdjustDeclIfTemplate(dcl); 05776 05777 Decl *Dcl = dcl.getAs<Decl>(); 05778 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 05779 if (!Fn) { 05780 Diag(DelLoc, diag::err_deleted_non_function); 05781 return; 05782 } 05783 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 05784 Diag(DelLoc, diag::err_deleted_decl_not_first); 05785 Diag(Prev->getLocation(), diag::note_previous_declaration); 05786 // If the declaration wasn't the first, we delete the function anyway for 05787 // recovery. 05788 } 05789 Fn->setDeleted(); 05790 } 05791 05792 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 05793 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 05794 ++CI) { 05795 Stmt *SubStmt = *CI; 05796 if (!SubStmt) 05797 continue; 05798 if (isa<ReturnStmt>(SubStmt)) 05799 Self.Diag(SubStmt->getSourceRange().getBegin(), 05800 diag::err_return_in_constructor_handler); 05801 if (!isa<Expr>(SubStmt)) 05802 SearchForReturnInStmt(Self, SubStmt); 05803 } 05804 } 05805 05806 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 05807 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 05808 CXXCatchStmt *Handler = TryBlock->getHandler(I); 05809 SearchForReturnInStmt(*this, Handler); 05810 } 05811 } 05812 05813 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 05814 const CXXMethodDecl *Old) { 05815 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 05816 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 05817 05818 if (Context.hasSameType(NewTy, OldTy) || 05819 NewTy->isDependentType() || OldTy->isDependentType()) 05820 return false; 05821 05822 // Check if the return types are covariant 05823 QualType NewClassTy, OldClassTy; 05824 05825 /// Both types must be pointers or references to classes. 05826 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 05827 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 05828 NewClassTy = NewPT->getPointeeType(); 05829 OldClassTy = OldPT->getPointeeType(); 05830 } 05831 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 05832 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 05833 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 05834 NewClassTy = NewRT->getPointeeType(); 05835 OldClassTy = OldRT->getPointeeType(); 05836 } 05837 } 05838 } 05839 05840 // The return types aren't either both pointers or references to a class type. 05841 if (NewClassTy.isNull()) { 05842 Diag(New->getLocation(), 05843 diag::err_different_return_type_for_overriding_virtual_function) 05844 << New->getDeclName() << NewTy << OldTy; 05845 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05846 05847 return true; 05848 } 05849 05850 // C++ [class.virtual]p6: 05851 // If the return type of D::f differs from the return type of B::f, the 05852 // class type in the return type of D::f shall be complete at the point of 05853 // declaration of D::f or shall be the class type D. 05854 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 05855 if (!RT->isBeingDefined() && 05856 RequireCompleteType(New->getLocation(), NewClassTy, 05857 PDiag(diag::err_covariant_return_incomplete) 05858 << New->getDeclName())) 05859 return true; 05860 } 05861 05862 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 05863 // Check if the new class derives from the old class. 05864 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 05865 Diag(New->getLocation(), 05866 diag::err_covariant_return_not_derived) 05867 << New->getDeclName() << NewTy << OldTy; 05868 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05869 return true; 05870 } 05871 05872 // Check if we the conversion from derived to base is valid. 05873 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 05874 diag::err_covariant_return_inaccessible_base, 05875 diag::err_covariant_return_ambiguous_derived_to_base_conv, 05876 // FIXME: Should this point to the return type? 05877 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 05878 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05879 return true; 05880 } 05881 } 05882 05883 // The qualifiers of the return types must be the same. 05884 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 05885 Diag(New->getLocation(), 05886 diag::err_covariant_return_type_different_qualifications) 05887 << New->getDeclName() << NewTy << OldTy; 05888 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05889 return true; 05890 }; 05891 05892 05893 // The new class type must have the same or less qualifiers as the old type. 05894 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 05895 Diag(New->getLocation(), 05896 diag::err_covariant_return_type_class_type_more_qualified) 05897 << New->getDeclName() << NewTy << OldTy; 05898 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05899 return true; 05900 }; 05901 05902 return false; 05903 } 05904 05905 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 05906 const CXXMethodDecl *Old) 05907 { 05908 if (Old->hasAttr<FinalAttr>()) { 05909 Diag(New->getLocation(), diag::err_final_function_overridden) 05910 << New->getDeclName(); 05911 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 05912 return true; 05913 } 05914 05915 return false; 05916 } 05917 05918 /// \brief Mark the given method pure. 05919 /// 05920 /// \param Method the method to be marked pure. 05921 /// 05922 /// \param InitRange the source range that covers the "0" initializer. 05923 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 05924 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 05925 Method->setPure(); 05926 05927 // A class is abstract if at least one function is pure virtual. 05928 Method->getParent()->setAbstract(true); 05929 return false; 05930 } 05931 05932 if (!Method->isInvalidDecl()) 05933 Diag(Method->getLocation(), diag::err_non_virtual_pure) 05934 << Method->getDeclName() << InitRange; 05935 return true; 05936 } 05937 05938 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 05939 /// an initializer for the out-of-line declaration 'Dcl'. The scope 05940 /// is a fresh scope pushed for just this purpose. 05941 /// 05942 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 05943 /// static data member of class X, names should be looked up in the scope of 05944 /// class X. 05945 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 05946 // If there is no declaration, there was an error parsing it. 05947 Decl *D = Dcl.getAs<Decl>(); 05948 if (D == 0) return; 05949 05950 // We should only get called for declarations with scope specifiers, like: 05951 // int foo::bar; 05952 assert(D->isOutOfLine()); 05953 EnterDeclaratorContext(S, D->getDeclContext()); 05954 } 05955 05956 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 05957 /// initializer for the out-of-line declaration 'Dcl'. 05958 void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 05959 // If there is no declaration, there was an error parsing it. 05960 Decl *D = Dcl.getAs<Decl>(); 05961 if (D == 0) return; 05962 05963 assert(D->isOutOfLine()); 05964 ExitDeclaratorContext(S); 05965 } 05966 05967 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 05968 /// C++ if/switch/while/for statement. 05969 /// e.g: "if (int x = f()) {...}" 05970 Action::DeclResult 05971 Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 05972 // C++ 6.4p2: 05973 // The declarator shall not specify a function or an array. 05974 // The type-specifier-seq shall not contain typedef and shall not declare a 05975 // new class or enumeration. 05976 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 05977 "Parser allowed 'typedef' as storage class of condition decl."); 05978 05979 TypeSourceInfo *TInfo = 0; 05980 TagDecl *OwnedTag = 0; 05981 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 05982 05983 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 05984 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 05985 // would be created and CXXConditionDeclExpr wants a VarDecl. 05986 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 05987 << D.getSourceRange(); 05988 return DeclResult(); 05989 } else if (OwnedTag && OwnedTag->isDefinition()) { 05990 // The type-specifier-seq shall not declare a new class or enumeration. 05991 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 05992 } 05993 05994 DeclPtrTy Dcl = ActOnDeclarator(S, D); 05995 if (!Dcl) 05996 return DeclResult(); 05997 05998 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 05999 VD->setDeclaredInCondition(true); 06000 return Dcl; 06001 } 06002 06003 static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) { 06004 // Ignore dependent types. 06005 if (MD->isDependentContext()) 06006 return false; 06007 06008 // Ignore declarations that are not definitions. 06009 if (!MD->isThisDeclarationADefinition()) 06010 return false; 06011 06012 CXXRecordDecl *RD = MD->getParent(); 06013 06014 // Ignore classes without a vtable. 06015 if (!RD->isDynamicClass()) 06016 return false; 06017 06018 switch (MD->getParent()->getTemplateSpecializationKind()) { 06019 case TSK_Undeclared: 06020 case TSK_ExplicitSpecialization: 06021 // Classes that aren't instantiations of templates don't need their 06022 // virtual methods marked until we see the definition of the key 06023 // function. 06024 break; 06025 06026 case TSK_ImplicitInstantiation: 06027 // This is a constructor of a class template; mark all of the virtual 06028 // members as referenced to ensure that they get instantiatied. 06029 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) 06030 return true; 06031 break; 06032 06033 case TSK_ExplicitInstantiationDeclaration: 06034 return false; 06035 06036 case TSK_ExplicitInstantiationDefinition: 06037 // This is method of a explicit instantiation; mark all of the virtual 06038 // members as referenced to ensure that they get instantiatied. 06039 return true; 06040 } 06041 06042 // Consider only out-of-line definitions of member functions. When we see 06043 // an inline definition, it's too early to compute the key function. 06044 if (!MD->isOutOfLine()) 06045 return false; 06046 06047 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD); 06048 06049 // If there is no key function, we will need a copy of the vtable. 06050 if (!KeyFunction) 06051 return true; 06052 06053 // If this is the key function, we need to mark virtual members. 06054 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 06055 return true; 06056 06057 return false; 06058 } 06059 06060 void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc, 06061 CXXMethodDecl *MD) { 06062 CXXRecordDecl *RD = MD->getParent(); 06063 06064 // We will need to mark all of the virtual members as referenced to build the 06065 // vtable. 06066 if (!needsVTable(MD, Context)) 06067 return; 06068 06069 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind(); 06070 if (kind == TSK_ImplicitInstantiation) 06071 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc)); 06072 else 06073 MarkVirtualMembersReferenced(Loc, RD); 06074 } 06075 06076 bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() { 06077 if (ClassesWithUnmarkedVirtualMembers.empty()) 06078 return false; 06079 06080 while (!ClassesWithUnmarkedVirtualMembers.empty()) { 06081 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first; 06082 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second; 06083 ClassesWithUnmarkedVirtualMembers.pop_back(); 06084 MarkVirtualMembersReferenced(Loc, RD); 06085 } 06086 06087 return true; 06088 } 06089 06090 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 06091 const CXXRecordDecl *RD) { 06092 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 06093 e = RD->method_end(); i != e; ++i) { 06094 CXXMethodDecl *MD = *i; 06095 06096 // C++ [basic.def.odr]p2: 06097 // [...] A virtual member function is used if it is not pure. [...] 06098 if (MD->isVirtual() && !MD->isPure()) 06099 MarkDeclarationReferenced(Loc, MD); 06100 } 06101 06102 // Only classes that have virtual bases need a VTT. 06103 if (RD->getNumVBases() == 0) 06104 return; 06105 06106 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 06107 e = RD->bases_end(); i != e; ++i) { 06108 const CXXRecordDecl *Base = 06109 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 06110 if (i->isVirtual()) 06111 continue; 06112 if (Base->getNumVBases() == 0) 06113 continue; 06114 MarkVirtualMembersReferenced(Loc, Base); 06115 } 06116 } 06117 06118 /// SetIvarInitializers - This routine builds initialization ASTs for the 06119 /// Objective-C implementation whose ivars need be initialized. 06120 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 06121 if (!getLangOptions().CPlusPlus) 06122 return; 06123 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 06124 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 06125 CollectIvarsToConstructOrDestruct(OID, ivars); 06126 if (ivars.empty()) 06127 return; 06128 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 06129 for (unsigned i = 0; i < ivars.size(); i++) { 06130 FieldDecl *Field = ivars[i]; 06131 CXXBaseOrMemberInitializer *Member; 06132 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 06133 InitializationKind InitKind = 06134 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 06135 06136 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 06137 Sema::OwningExprResult MemberInit = 06138 InitSeq.Perform(*this, InitEntity, InitKind, 06139 Sema::MultiExprArg(*this, 0, 0)); 06140 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 06141 // Note, MemberInit could actually come back empty if no initialization 06142 // is required (e.g., because it would call a trivial default constructor) 06143 if (!MemberInit.get() || MemberInit.isInvalid()) 06144 continue; 06145 06146 Member = 06147 new (Context) CXXBaseOrMemberInitializer(Context, 06148 Field, SourceLocation(), 06149 SourceLocation(), 06150 MemberInit.takeAs<Expr>(), 06151 SourceLocation()); 06152 AllToInit.push_back(Member); 06153 } 06154 ObjCImplementation->setIvarInitializers(Context, 06155 AllToInit.data(), AllToInit.size()); 06156 } 06157 }