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