SemaDeclCXX.cpp revision b001de7458d17c17e6d8b8034c7cfcefd3b70c00
1579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// 3579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// The LLVM Compiler Infrastructure 4579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// 5579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// This file is distributed under the University of Illinois Open Source 6579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// License. See LICENSE.TXT for details. 7579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// 8579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson//===----------------------------------------------------------------------===// 9579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// 10579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// This file implements semantic analysis for C++ declarations. 11579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// 12579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson//===----------------------------------------------------------------------===// 13579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 14579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/SemaInternal.h" 15579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/CXXFieldCollector.h" 16579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/Scope.h" 17579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/Initialization.h" 18579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/Lookup.h" 19579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/ASTConsumer.h" 20579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/ASTContext.h" 21579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/ASTMutationListener.h" 22579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/CharUnits.h" 23579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/CXXInheritance.h" 24579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/DeclVisitor.h" 25579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/ExprCXX.h" 26579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/RecordLayout.h" 27579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/StmtVisitor.h" 28579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/TypeLoc.h" 29579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/AST/TypeOrdering.h" 30579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/DeclSpec.h" 31579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Sema/ParsedTemplate.h" 32579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Basic/PartialDiagnostic.h" 33579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "clang/Lex/Preprocessor.h" 34579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "llvm/ADT/DenseSet.h" 35579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include "llvm/ADT/STLExtras.h" 36579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include <map> 37579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson#include <set> 38579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 39579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonusing namespace clang; 40579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 41579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson//===----------------------------------------------------------------------===// 42579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson// CheckDefaultArgumentVisitor 43579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson//===----------------------------------------------------------------------===// 44579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 45579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonnamespace { 46579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 47579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// the default argument of a parameter to determine whether it 48579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// contains any ill-formed subexpressions. For example, this will 49579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// diagnose the use of local variables or parameters within the 50579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// default argument expression. 51579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson class CheckDefaultArgumentVisitor 52579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 53579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson Expr *DefaultArg; 54579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson Sema *S; 55579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 56579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson public: 57579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 58579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson : DefaultArg(defarg), S(s) {} 59579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 60579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool VisitExpr(Expr *Node); 61579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool VisitDeclRefExpr(DeclRefExpr *DRE); 62579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool VisitCXXThisExpr(CXXThisExpr *ThisE); 63579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson }; 64579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 65579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// VisitExpr - Visit all of the children of this expression. 66579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 67579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool IsInvalid = false; 68579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson for (Stmt::child_range I = Node->children(); I; ++I) 69579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson IsInvalid |= Visit(*I); 70579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return IsInvalid; 71579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 72579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 73579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// VisitDeclRefExpr - Visit a reference to a declaration, to 74579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// determine whether this declaration can be used in the default 75579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// argument expression. 76579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 77579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson NamedDecl *Decl = DRE->getDecl(); 78579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 79579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // C++ [dcl.fct.default]p9 80579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Default arguments are evaluated each time the function is 81579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // called. The order of evaluation of function arguments is 82579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // unspecified. Consequently, parameters of a function shall not 83579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // be used in default argument expressions, even if they are not 84579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // evaluated. Parameters of a function declared before a default 85579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // argument expression are in scope and can hide namespace and 86579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // class member names. 87579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return S->Diag(DRE->getSourceRange().getBegin(), 88579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson diag::err_param_default_argument_references_param) 89579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson << Param->getDeclName() << DefaultArg->getSourceRange(); 90579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 91579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // C++ [dcl.fct.default]p7 92579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Local variables shall not be used in default argument 93579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // expressions. 94579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (VDecl->isLocalVarDecl()) 95579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return S->Diag(DRE->getSourceRange().getBegin(), 96579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson diag::err_param_default_argument_references_local) 97579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson << VDecl->getDeclName() << DefaultArg->getSourceRange(); 98579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 99579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 100579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return false; 101579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 102579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 103579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson /// VisitCXXThisExpr - Visit a C++ "this" expression. 104579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 105579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // C++ [dcl.fct.default]p8: 106579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // The keyword this shall not be used in a default argument of a 107579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // member function. 108579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return S->Diag(ThisE->getSourceRange().getBegin(), 109579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson diag::err_param_default_argument_references_this) 110579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson << ThisE->getSourceRange(); 111579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 112579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson} 113579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 114579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonvoid Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) { 115579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson assert(Context && "ImplicitExceptionSpecification without an ASTContext"); 116579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // If we have an MSAny or unknown spec already, don't bother. 117579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 118579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 119579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 120579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson const FunctionProtoType *Proto 121579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson = Method->getType()->getAs<FunctionProtoType>(); 122579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 123579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 124579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 125579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // If this function can throw any exceptions, make a note of that. 126579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) { 127579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ClearExceptions(); 128579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ComputedEST = EST; 129579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 130579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 131579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 132579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // FIXME: If the call to this decl is using any of its default arguments, we 133579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // need to search them for potentially-throwing calls. 134579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 135579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // If this function has a basic noexcept, it doesn't affect the outcome. 136579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (EST == EST_BasicNoexcept) 137579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 138579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 139579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // If we have a throw-all spec at this point, ignore the function. 140579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (ComputedEST == EST_None) 141579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 142579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 143579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // If we're still at noexcept(true) and there's a nothrow() callee, 144579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // change to that specification. 145579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (EST == EST_DynamicNone) { 146579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (ComputedEST == EST_BasicNoexcept) 147579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ComputedEST = EST_DynamicNone; 148579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 149579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 150579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 151579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Check out noexcept specs. 152579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (EST == EST_ComputedNoexcept) { 153579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context); 154579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson assert(NR != FunctionProtoType::NR_NoNoexcept && 155579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson "Must have noexcept result for EST_ComputedNoexcept."); 156579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson assert(NR != FunctionProtoType::NR_Dependent && 157579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson "Should not generate implicit declarations for dependent cases, " 158579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson "and don't know how to handle them anyway."); 159579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 160579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // noexcept(false) -> no spec on the new function 161579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (NR == FunctionProtoType::NR_Throw) { 162579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ClearExceptions(); 163579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ComputedEST = EST_None; 164579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 165579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // noexcept(true) won't change anything either. 166579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 167579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 168579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 169579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson assert(EST == EST_Dynamic && "EST case not considered earlier."); 170579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson assert(ComputedEST != EST_None && 171579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson "Shouldn't collect exceptions when throw-all is guaranteed."); 172579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ComputedEST = EST_Dynamic; 173579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Record the exceptions in this function's exception specification. 174579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 175579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson EEnd = Proto->exception_end(); 176579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson E != EEnd; ++E) 177579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (ExceptionsSeen.insert(Context->getCanonicalType(*E))) 178579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson Exceptions.push_back(*E); 179579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson} 180579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 181579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonvoid Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 182579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 183579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return; 184579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 185579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // FIXME: 186579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // 187579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // C++0x [except.spec]p14: 188579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // [An] implicit exception-specification specifies the type-id T if and 189579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // only if T is allowed by the exception-specification of a function directly 190579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // invoked by f's implicit definition; f shall allow all exceptions if any 191579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // function it directly invokes allows all exceptions, and f shall allow no 192579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // exceptions if every function it directly invokes allows no exceptions. 193579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // 194579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Note in particular that if an implicit exception-specification is generated 195579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // for a function containing a throw-expression, that specification can still 196579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // be noexcept(true). 197579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // 198579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Note also that 'directly invoked' is not defined in the standard, and there 199579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // is no indication that we should only consider potentially-evaluated calls. 200579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // 201579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // Ultimately we should implement the intent of the standard: the exception 202579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // specification should be the set of exceptions which can be thrown by the 203579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // implicit definition. For now, we assume that any non-nothrow expression can 204579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson // throw any exception. 205579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 206579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (E->CanThrow(*Context)) 207579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson ComputedEST = EST_None; 208579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson} 209579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 210579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilsonbool 211579d7739c53a2707ad711a2d2cae46d7d782f06Jesse WilsonSema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 212579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson SourceLocation EqualLoc) { 213579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson if (RequireCompleteType(Param->getLocation(), Param->getType(), 214579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson diag::err_typecheck_decl_incomplete_type)) { 215579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson Param->setInvalidDecl(); 216579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson return true; 217579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson } 218579d7739c53a2707ad711a2d2cae46d7d782f06Jesse Wilson 219 // C++ [dcl.fct.default]p5 220 // A default argument expression is implicitly converted (clause 221 // 4) to the parameter type. The default argument expression has 222 // the same semantic constraints as the initializer expression in 223 // a declaration of a variable of the parameter type, using the 224 // copy-initialization semantics (8.5). 225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 226 Param); 227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 228 EqualLoc); 229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 231 MultiExprArg(*this, &Arg, 1)); 232 if (Result.isInvalid()) 233 return true; 234 Arg = Result.takeAs<Expr>(); 235 236 CheckImplicitConversions(Arg, EqualLoc); 237 Arg = MaybeCreateExprWithCleanups(Arg); 238 239 // Okay: add the default argument to the parameter 240 Param->setDefaultArg(Arg); 241 242 // We have already instantiated this parameter; provide each of the 243 // instantiations with the uninstantiated default argument. 244 UnparsedDefaultArgInstantiationsMap::iterator InstPos 245 = UnparsedDefaultArgInstantiations.find(Param); 246 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 249 250 // We're done tracking this parameter's instantiations. 251 UnparsedDefaultArgInstantiations.erase(InstPos); 252 } 253 254 return false; 255} 256 257/// ActOnParamDefaultArgument - Check whether the default argument 258/// provided for a function parameter is well-formed. If so, attach it 259/// to the parameter declaration. 260void 261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 262 Expr *DefaultArg) { 263 if (!param || !DefaultArg) 264 return; 265 266 ParmVarDecl *Param = cast<ParmVarDecl>(param); 267 UnparsedDefaultArgLocs.erase(Param); 268 269 // Default arguments are only permitted in C++ 270 if (!getLangOptions().CPlusPlus) { 271 Diag(EqualLoc, diag::err_param_default_argument) 272 << DefaultArg->getSourceRange(); 273 Param->setInvalidDecl(); 274 return; 275 } 276 277 // Check for unexpanded parameter packs. 278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 279 Param->setInvalidDecl(); 280 return; 281 } 282 283 // Check that the default argument is well-formed 284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 285 if (DefaultArgChecker.Visit(DefaultArg)) { 286 Param->setInvalidDecl(); 287 return; 288 } 289 290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 291} 292 293/// ActOnParamUnparsedDefaultArgument - We've seen a default 294/// argument for a function parameter, but we can't parse it yet 295/// because we're inside a class definition. Note that this default 296/// argument will be parsed later. 297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 298 SourceLocation EqualLoc, 299 SourceLocation ArgLoc) { 300 if (!param) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 if (Param) 305 Param->setUnparsedDefaultArg(); 306 307 UnparsedDefaultArgLocs[Param] = ArgLoc; 308} 309 310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 311/// the default argument for the parameter param failed. 312void Sema::ActOnParamDefaultArgumentError(Decl *param) { 313 if (!param) 314 return; 315 316 ParmVarDecl *Param = cast<ParmVarDecl>(param); 317 318 Param->setInvalidDecl(); 319 320 UnparsedDefaultArgLocs.erase(Param); 321} 322 323/// CheckExtraCXXDefaultArguments - Check for any extra default 324/// arguments in the declarator, which is not a function declaration 325/// or definition and therefore is not permitted to have default 326/// arguments. This routine should be invoked for every declarator 327/// that is not a function declaration or definition. 328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 329 // C++ [dcl.fct.default]p3 330 // A default argument expression shall be specified only in the 331 // parameter-declaration-clause of a function declaration or in a 332 // template-parameter (14.1). It shall not be specified for a 333 // parameter pack. If it is specified in a 334 // parameter-declaration-clause, it shall not occur within a 335 // declarator or abstract-declarator of a parameter-declaration. 336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 337 DeclaratorChunk &chunk = D.getTypeObject(i); 338 if (chunk.Kind == DeclaratorChunk::Function) { 339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 340 ParmVarDecl *Param = 341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 342 if (Param->hasUnparsedDefaultArg()) { 343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 346 delete Toks; 347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 348 } else if (Param->getDefaultArg()) { 349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 350 << Param->getDefaultArg()->getSourceRange(); 351 Param->setDefaultArg(0); 352 } 353 } 354 } 355 } 356} 357 358// MergeCXXFunctionDecl - Merge two declarations of the same C++ 359// function, once we already know that they have the same 360// type. Subroutine of MergeFunctionDecl. Returns true if there was an 361// error, false otherwise. 362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 363 bool Invalid = false; 364 365 // C++ [dcl.fct.default]p4: 366 // For non-template functions, default arguments can be added in 367 // later declarations of a function in the same 368 // scope. Declarations in different scopes have completely 369 // distinct sets of default arguments. That is, declarations in 370 // inner scopes do not acquire default arguments from 371 // declarations in outer scopes, and vice versa. In a given 372 // function declaration, all parameters subsequent to a 373 // parameter with a default argument shall have default 374 // arguments supplied in this or previous declarations. A 375 // default argument shall not be redefined by a later 376 // declaration (not even to the same value). 377 // 378 // C++ [dcl.fct.default]p6: 379 // Except for member functions of class templates, the default arguments 380 // in a member function definition that appears outside of the class 381 // definition are added to the set of default arguments provided by the 382 // member function declaration in the class definition. 383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 384 ParmVarDecl *OldParam = Old->getParamDecl(p); 385 ParmVarDecl *NewParam = New->getParamDecl(p); 386 387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 388 389 unsigned DiagDefaultParamID = 390 diag::err_param_default_argument_redefinition; 391 392 // MSVC accepts that default parameters be redefined for member functions 393 // of template class. The new default parameter's value is ignored. 394 Invalid = true; 395 if (getLangOptions().MicrosoftExt) { 396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 397 if (MD && MD->getParent()->getDescribedClassTemplate()) { 398 // Merge the old default argument into the new parameter. 399 NewParam->setHasInheritedDefaultArg(); 400 if (OldParam->hasUninstantiatedDefaultArg()) 401 NewParam->setUninstantiatedDefaultArg( 402 OldParam->getUninstantiatedDefaultArg()); 403 else 404 NewParam->setDefaultArg(OldParam->getInit()); 405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 406 Invalid = false; 407 } 408 } 409 410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 411 // hint here. Alternatively, we could walk the type-source information 412 // for NewParam to find the last source location in the type... but it 413 // isn't worth the effort right now. This is the kind of test case that 414 // is hard to get right: 415 // int f(int); 416 // void g(int (*fp)(int) = f); 417 // void g(int (*fp)(int) = &f); 418 Diag(NewParam->getLocation(), DiagDefaultParamID) 419 << NewParam->getDefaultArgRange(); 420 421 // Look for the function declaration where the default argument was 422 // actually written, which may be a declaration prior to Old. 423 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 424 Older; Older = Older->getPreviousDeclaration()) { 425 if (!Older->getParamDecl(p)->hasDefaultArg()) 426 break; 427 428 OldParam = Older->getParamDecl(p); 429 } 430 431 Diag(OldParam->getLocation(), diag::note_previous_definition) 432 << OldParam->getDefaultArgRange(); 433 } else if (OldParam->hasDefaultArg()) { 434 // Merge the old default argument into the new parameter. 435 // It's important to use getInit() here; getDefaultArg() 436 // strips off any top-level ExprWithCleanups. 437 NewParam->setHasInheritedDefaultArg(); 438 if (OldParam->hasUninstantiatedDefaultArg()) 439 NewParam->setUninstantiatedDefaultArg( 440 OldParam->getUninstantiatedDefaultArg()); 441 else 442 NewParam->setDefaultArg(OldParam->getInit()); 443 } else if (NewParam->hasDefaultArg()) { 444 if (New->getDescribedFunctionTemplate()) { 445 // Paragraph 4, quoted above, only applies to non-template functions. 446 Diag(NewParam->getLocation(), 447 diag::err_param_default_argument_template_redecl) 448 << NewParam->getDefaultArgRange(); 449 Diag(Old->getLocation(), diag::note_template_prev_declaration) 450 << false; 451 } else if (New->getTemplateSpecializationKind() 452 != TSK_ImplicitInstantiation && 453 New->getTemplateSpecializationKind() != TSK_Undeclared) { 454 // C++ [temp.expr.spec]p21: 455 // Default function arguments shall not be specified in a declaration 456 // or a definition for one of the following explicit specializations: 457 // - the explicit specialization of a function template; 458 // - the explicit specialization of a member function template; 459 // - the explicit specialization of a member function of a class 460 // template where the class template specialization to which the 461 // member function specialization belongs is implicitly 462 // instantiated. 463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 465 << New->getDeclName() 466 << NewParam->getDefaultArgRange(); 467 } else if (New->getDeclContext()->isDependentContext()) { 468 // C++ [dcl.fct.default]p6 (DR217): 469 // Default arguments for a member function of a class template shall 470 // be specified on the initial declaration of the member function 471 // within the class template. 472 // 473 // Reading the tea leaves a bit in DR217 and its reference to DR205 474 // leads me to the conclusion that one cannot add default function 475 // arguments for an out-of-line definition of a member function of a 476 // dependent type. 477 int WhichKind = 2; 478 if (CXXRecordDecl *Record 479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 480 if (Record->getDescribedClassTemplate()) 481 WhichKind = 0; 482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 483 WhichKind = 1; 484 else 485 WhichKind = 2; 486 } 487 488 Diag(NewParam->getLocation(), 489 diag::err_param_default_argument_member_template_redecl) 490 << WhichKind 491 << NewParam->getDefaultArgRange(); 492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 493 CXXSpecialMember NewSM = getSpecialMember(Ctor), 494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 495 if (NewSM != OldSM) { 496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 497 << NewParam->getDefaultArgRange() << NewSM; 498 Diag(Old->getLocation(), diag::note_previous_declaration_special) 499 << OldSM; 500 } 501 } 502 } 503 } 504 505 // C++0x [dcl.constexpr]p1: If any declaration of a function or function 506 // template has a constexpr specifier then all its declarations shall 507 // contain the constexpr specifier. [Note: An explicit specialization can 508 // differ from the template declaration with respect to the constexpr 509 // specifier. -- end note] 510 // 511 // FIXME: Don't reject changes in constexpr in explicit specializations. 512 if (New->isConstexpr() != Old->isConstexpr()) { 513 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 514 << New << New->isConstexpr(); 515 Diag(Old->getLocation(), diag::note_previous_declaration); 516 Invalid = true; 517 } 518 519 if (CheckEquivalentExceptionSpec(Old, New)) 520 Invalid = true; 521 522 return Invalid; 523} 524 525/// \brief Merge the exception specifications of two variable declarations. 526/// 527/// This is called when there's a redeclaration of a VarDecl. The function 528/// checks if the redeclaration might have an exception specification and 529/// validates compatibility and merges the specs if necessary. 530void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 531 // Shortcut if exceptions are disabled. 532 if (!getLangOptions().CXXExceptions) 533 return; 534 535 assert(Context.hasSameType(New->getType(), Old->getType()) && 536 "Should only be called if types are otherwise the same."); 537 538 QualType NewType = New->getType(); 539 QualType OldType = Old->getType(); 540 541 // We're only interested in pointers and references to functions, as well 542 // as pointers to member functions. 543 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 544 NewType = R->getPointeeType(); 545 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 546 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 547 NewType = P->getPointeeType(); 548 OldType = OldType->getAs<PointerType>()->getPointeeType(); 549 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 550 NewType = M->getPointeeType(); 551 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 552 } 553 554 if (!NewType->isFunctionProtoType()) 555 return; 556 557 // There's lots of special cases for functions. For function pointers, system 558 // libraries are hopefully not as broken so that we don't need these 559 // workarounds. 560 if (CheckEquivalentExceptionSpec( 561 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 562 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 563 New->setInvalidDecl(); 564 } 565} 566 567/// CheckCXXDefaultArguments - Verify that the default arguments for a 568/// function declaration are well-formed according to C++ 569/// [dcl.fct.default]. 570void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 571 unsigned NumParams = FD->getNumParams(); 572 unsigned p; 573 574 // Find first parameter with a default argument 575 for (p = 0; p < NumParams; ++p) { 576 ParmVarDecl *Param = FD->getParamDecl(p); 577 if (Param->hasDefaultArg()) 578 break; 579 } 580 581 // C++ [dcl.fct.default]p4: 582 // In a given function declaration, all parameters 583 // subsequent to a parameter with a default argument shall 584 // have default arguments supplied in this or previous 585 // declarations. A default argument shall not be redefined 586 // by a later declaration (not even to the same value). 587 unsigned LastMissingDefaultArg = 0; 588 for (; p < NumParams; ++p) { 589 ParmVarDecl *Param = FD->getParamDecl(p); 590 if (!Param->hasDefaultArg()) { 591 if (Param->isInvalidDecl()) 592 /* We already complained about this parameter. */; 593 else if (Param->getIdentifier()) 594 Diag(Param->getLocation(), 595 diag::err_param_default_argument_missing_name) 596 << Param->getIdentifier(); 597 else 598 Diag(Param->getLocation(), 599 diag::err_param_default_argument_missing); 600 601 LastMissingDefaultArg = p; 602 } 603 } 604 605 if (LastMissingDefaultArg > 0) { 606 // Some default arguments were missing. Clear out all of the 607 // default arguments up to (and including) the last missing 608 // default argument, so that we leave the function parameters 609 // in a semantically valid state. 610 for (p = 0; p <= LastMissingDefaultArg; ++p) { 611 ParmVarDecl *Param = FD->getParamDecl(p); 612 if (Param->hasDefaultArg()) { 613 Param->setDefaultArg(0); 614 } 615 } 616 } 617} 618 619// CheckConstexprParameterTypes - Check whether a function's parameter types 620// are all literal types. If so, return true. If not, produce a suitable 621// diagnostic depending on @p CCK and return false. 622static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, 623 Sema::CheckConstexprKind CCK) { 624 unsigned ArgIndex = 0; 625 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 626 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 627 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 628 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 629 SourceLocation ParamLoc = PD->getLocation(); 630 if (!(*i)->isDependentType() && 631 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ? 632 SemaRef.PDiag(diag::err_constexpr_non_literal_param) 633 << ArgIndex+1 << PD->getSourceRange() 634 << isa<CXXConstructorDecl>(FD) : 635 SemaRef.PDiag(), 636 /*AllowIncompleteType*/ true)) { 637 if (CCK == Sema::CCK_NoteNonConstexprInstantiation) 638 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param) 639 << ArgIndex+1 << PD->getSourceRange() 640 << isa<CXXConstructorDecl>(FD) << *i; 641 return false; 642 } 643 } 644 return true; 645} 646 647// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 648// the requirements of a constexpr function declaration or a constexpr 649// constructor declaration. Return true if it does, false if not. 650// 651// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308. 652// 653// \param CCK Specifies whether to produce diagnostics if the function does not 654// satisfy the requirements. 655bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD, 656 CheckConstexprKind CCK) { 657 assert((CCK != CCK_NoteNonConstexprInstantiation || 658 (NewFD->getTemplateInstantiationPattern() && 659 NewFD->getTemplateInstantiationPattern()->isConstexpr())) && 660 "only constexpr templates can be instantiated non-constexpr"); 661 662 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(NewFD)) { 663 // C++0x [dcl.constexpr]p4: 664 // In the definition of a constexpr constructor, each of the parameter 665 // types shall be a literal type. 666 if (!CheckConstexprParameterTypes(*this, NewFD, CCK)) 667 return false; 668 669 // In addition, either its function-body shall be = delete or = default or 670 // it shall satisfy the following constraints: 671 // - the class shall not have any virtual base classes; 672 const CXXRecordDecl *RD = CD->getParent(); 673 if (RD->getNumVBases()) { 674 // Note, this is still illegal if the body is = default, since the 675 // implicit body does not satisfy the requirements of a constexpr 676 // constructor. We also reject cases where the body is = delete, as 677 // required by N3308. 678 if (CCK != CCK_Instantiation) { 679 Diag(NewFD->getLocation(), 680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base 681 : diag::note_constexpr_tmpl_virtual_base) 682 << RD->isStruct() << RD->getNumVBases(); 683 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 684 E = RD->vbases_end(); I != E; ++I) 685 Diag(I->getSourceRange().getBegin(), 686 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 687 } 688 return false; 689 } 690 } else { 691 // C++0x [dcl.constexpr]p3: 692 // The definition of a constexpr function shall satisfy the following 693 // constraints: 694 // - it shall not be virtual; 695 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 696 if (Method && Method->isVirtual()) { 697 if (CCK != CCK_Instantiation) { 698 Diag(NewFD->getLocation(), 699 CCK == CCK_Declaration ? diag::err_constexpr_virtual 700 : diag::note_constexpr_tmpl_virtual); 701 702 // If it's not obvious why this function is virtual, find an overridden 703 // function which uses the 'virtual' keyword. 704 const CXXMethodDecl *WrittenVirtual = Method; 705 while (!WrittenVirtual->isVirtualAsWritten()) 706 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 707 if (WrittenVirtual != Method) 708 Diag(WrittenVirtual->getLocation(), 709 diag::note_overridden_virtual_function); 710 } 711 return false; 712 } 713 714 // - its return type shall be a literal type; 715 QualType RT = NewFD->getResultType(); 716 if (!RT->isDependentType() && 717 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ? 718 PDiag(diag::err_constexpr_non_literal_return) : 719 PDiag(), 720 /*AllowIncompleteType*/ true)) { 721 if (CCK == CCK_NoteNonConstexprInstantiation) 722 Diag(NewFD->getLocation(), 723 diag::note_constexpr_tmpl_non_literal_return) << RT; 724 return false; 725 } 726 727 // - each of its parameter types shall be a literal type; 728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK)) 729 return false; 730 } 731 732 return true; 733} 734 735/// Check the given declaration statement is legal within a constexpr function 736/// body. C++0x [dcl.constexpr]p3,p4. 737/// 738/// \return true if the body is OK, false if we have diagnosed a problem. 739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 740 DeclStmt *DS) { 741 // C++0x [dcl.constexpr]p3 and p4: 742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 743 // contain only 744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 746 switch ((*DclIt)->getKind()) { 747 case Decl::StaticAssert: 748 case Decl::Using: 749 case Decl::UsingShadow: 750 case Decl::UsingDirective: 751 case Decl::UnresolvedUsingTypename: 752 // - static_assert-declarations 753 // - using-declarations, 754 // - using-directives, 755 continue; 756 757 case Decl::Typedef: 758 case Decl::TypeAlias: { 759 // - typedef declarations and alias-declarations that do not define 760 // classes or enumerations, 761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 762 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 763 // Don't allow variably-modified types in constexpr functions. 764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 766 << TL.getSourceRange() << TL.getType() 767 << isa<CXXConstructorDecl>(Dcl); 768 return false; 769 } 770 continue; 771 } 772 773 case Decl::Enum: 774 case Decl::CXXRecord: 775 // As an extension, we allow the declaration (but not the definition) of 776 // classes and enumerations in all declarations, not just in typedef and 777 // alias declarations. 778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 780 << isa<CXXConstructorDecl>(Dcl); 781 return false; 782 } 783 continue; 784 785 case Decl::Var: 786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 787 << isa<CXXConstructorDecl>(Dcl); 788 return false; 789 790 default: 791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 792 << isa<CXXConstructorDecl>(Dcl); 793 return false; 794 } 795 } 796 797 return true; 798} 799 800/// Check that the given field is initialized within a constexpr constructor. 801/// 802/// \param Dcl The constexpr constructor being checked. 803/// \param Field The field being checked. This may be a member of an anonymous 804/// struct or union nested within the class being checked. 805/// \param Inits All declarations, including anonymous struct/union members and 806/// indirect members, for which any initialization was provided. 807/// \param Diagnosed Set to true if an error is produced. 808static void CheckConstexprCtorInitializer(Sema &SemaRef, 809 const FunctionDecl *Dcl, 810 FieldDecl *Field, 811 llvm::SmallSet<Decl*, 16> &Inits, 812 bool &Diagnosed) { 813 if (!Inits.count(Field)) { 814 if (!Diagnosed) { 815 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 816 Diagnosed = true; 817 } 818 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 819 } else if (Field->isAnonymousStructOrUnion()) { 820 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 821 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 822 I != E; ++I) 823 // If an anonymous union contains an anonymous struct of which any member 824 // is initialized, all members must be initialized. 825 if (!RD->isUnion() || Inits.count(*I)) 826 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 827 } 828} 829 830/// Check the body for the given constexpr function declaration only contains 831/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 832/// 833/// \return true if the body is OK, false if we have diagnosed a problem. 834bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 835 if (isa<CXXTryStmt>(Body)) { 836 // C++0x [dcl.constexpr]p3: 837 // The definition of a constexpr function shall satisfy the following 838 // constraints: [...] 839 // - its function-body shall be = delete, = default, or a 840 // compound-statement 841 // 842 // C++0x [dcl.constexpr]p4: 843 // In the definition of a constexpr constructor, [...] 844 // - its function-body shall not be a function-try-block; 845 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 846 << isa<CXXConstructorDecl>(Dcl); 847 return false; 848 } 849 850 // - its function-body shall be [...] a compound-statement that contains only 851 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 852 853 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 854 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 855 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 856 switch ((*BodyIt)->getStmtClass()) { 857 case Stmt::NullStmtClass: 858 // - null statements, 859 continue; 860 861 case Stmt::DeclStmtClass: 862 // - static_assert-declarations 863 // - using-declarations, 864 // - using-directives, 865 // - typedef declarations and alias-declarations that do not define 866 // classes or enumerations, 867 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 868 return false; 869 continue; 870 871 case Stmt::ReturnStmtClass: 872 // - and exactly one return statement; 873 if (isa<CXXConstructorDecl>(Dcl)) 874 break; 875 876 ReturnStmts.push_back((*BodyIt)->getLocStart()); 877 // FIXME 878 // - every constructor call and implicit conversion used in initializing 879 // the return value shall be one of those allowed in a constant 880 // expression. 881 // Deal with this as part of a general check that the function can produce 882 // a constant expression (for [dcl.constexpr]p5). 883 continue; 884 885 default: 886 break; 887 } 888 889 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 890 << isa<CXXConstructorDecl>(Dcl); 891 return false; 892 } 893 894 if (const CXXConstructorDecl *Constructor 895 = dyn_cast<CXXConstructorDecl>(Dcl)) { 896 const CXXRecordDecl *RD = Constructor->getParent(); 897 // - every non-static data member and base class sub-object shall be 898 // initialized; 899 if (RD->isUnion()) { 900 // DR1359: Exactly one member of a union shall be initialized. 901 if (Constructor->getNumCtorInitializers() == 0) { 902 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 903 return false; 904 } 905 } else if (!Constructor->isDelegatingConstructor()) { 906 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 907 908 // Skip detailed checking if we have enough initializers, and we would 909 // allow at most one initializer per member. 910 bool AnyAnonStructUnionMembers = false; 911 unsigned Fields = 0; 912 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 913 E = RD->field_end(); I != E; ++I, ++Fields) { 914 if ((*I)->isAnonymousStructOrUnion()) { 915 AnyAnonStructUnionMembers = true; 916 break; 917 } 918 } 919 if (AnyAnonStructUnionMembers || 920 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 921 // Check initialization of non-static data members. Base classes are 922 // always initialized so do not need to be checked. Dependent bases 923 // might not have initializers in the member initializer list. 924 llvm::SmallSet<Decl*, 16> Inits; 925 for (CXXConstructorDecl::init_const_iterator 926 I = Constructor->init_begin(), E = Constructor->init_end(); 927 I != E; ++I) { 928 if (FieldDecl *FD = (*I)->getMember()) 929 Inits.insert(FD); 930 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 931 Inits.insert(ID->chain_begin(), ID->chain_end()); 932 } 933 934 bool Diagnosed = false; 935 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 936 E = RD->field_end(); I != E; ++I) 937 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 938 if (Diagnosed) 939 return false; 940 } 941 } 942 943 // FIXME 944 // - every constructor involved in initializing non-static data members 945 // and base class sub-objects shall be a constexpr constructor; 946 // - every assignment-expression that is an initializer-clause appearing 947 // directly or indirectly within a brace-or-equal-initializer for 948 // a non-static data member that is not named by a mem-initializer-id 949 // shall be a constant expression; and 950 // - every implicit conversion used in converting a constructor argument 951 // to the corresponding parameter type and converting 952 // a full-expression to the corresponding member type shall be one of 953 // those allowed in a constant expression. 954 // Deal with these as part of a general check that the function can produce 955 // a constant expression (for [dcl.constexpr]p5). 956 } else { 957 if (ReturnStmts.empty()) { 958 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 959 return false; 960 } 961 if (ReturnStmts.size() > 1) { 962 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 963 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 964 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 965 return false; 966 } 967 } 968 969 return true; 970} 971 972/// isCurrentClassName - Determine whether the identifier II is the 973/// name of the class type currently being defined. In the case of 974/// nested classes, this will only return true if II is the name of 975/// the innermost class. 976bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 977 const CXXScopeSpec *SS) { 978 assert(getLangOptions().CPlusPlus && "No class names in C!"); 979 980 CXXRecordDecl *CurDecl; 981 if (SS && SS->isSet() && !SS->isInvalid()) { 982 DeclContext *DC = computeDeclContext(*SS, true); 983 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 984 } else 985 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 986 987 if (CurDecl && CurDecl->getIdentifier()) 988 return &II == CurDecl->getIdentifier(); 989 else 990 return false; 991} 992 993/// \brief Check the validity of a C++ base class specifier. 994/// 995/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 996/// and returns NULL otherwise. 997CXXBaseSpecifier * 998Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 999 SourceRange SpecifierRange, 1000 bool Virtual, AccessSpecifier Access, 1001 TypeSourceInfo *TInfo, 1002 SourceLocation EllipsisLoc) { 1003 QualType BaseType = TInfo->getType(); 1004 1005 // C++ [class.union]p1: 1006 // A union shall not have base classes. 1007 if (Class->isUnion()) { 1008 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1009 << SpecifierRange; 1010 return 0; 1011 } 1012 1013 if (EllipsisLoc.isValid() && 1014 !TInfo->getType()->containsUnexpandedParameterPack()) { 1015 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1016 << TInfo->getTypeLoc().getSourceRange(); 1017 EllipsisLoc = SourceLocation(); 1018 } 1019 1020 if (BaseType->isDependentType()) 1021 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1022 Class->getTagKind() == TTK_Class, 1023 Access, TInfo, EllipsisLoc); 1024 1025 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1026 1027 // Base specifiers must be record types. 1028 if (!BaseType->isRecordType()) { 1029 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1030 return 0; 1031 } 1032 1033 // C++ [class.union]p1: 1034 // A union shall not be used as a base class. 1035 if (BaseType->isUnionType()) { 1036 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1037 return 0; 1038 } 1039 1040 // C++ [class.derived]p2: 1041 // The class-name in a base-specifier shall not be an incompletely 1042 // defined class. 1043 if (RequireCompleteType(BaseLoc, BaseType, 1044 PDiag(diag::err_incomplete_base_class) 1045 << SpecifierRange)) { 1046 Class->setInvalidDecl(); 1047 return 0; 1048 } 1049 1050 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1051 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1052 assert(BaseDecl && "Record type has no declaration"); 1053 BaseDecl = BaseDecl->getDefinition(); 1054 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1055 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1056 assert(CXXBaseDecl && "Base type is not a C++ type"); 1057 1058 // C++ [class]p3: 1059 // If a class is marked final and it appears as a base-type-specifier in 1060 // base-clause, the program is ill-formed. 1061 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1062 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1063 << CXXBaseDecl->getDeclName(); 1064 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1065 << CXXBaseDecl->getDeclName(); 1066 return 0; 1067 } 1068 1069 if (BaseDecl->isInvalidDecl()) 1070 Class->setInvalidDecl(); 1071 1072 // Create the base specifier. 1073 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1074 Class->getTagKind() == TTK_Class, 1075 Access, TInfo, EllipsisLoc); 1076} 1077 1078/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1079/// one entry in the base class list of a class specifier, for 1080/// example: 1081/// class foo : public bar, virtual private baz { 1082/// 'public bar' and 'virtual private baz' are each base-specifiers. 1083BaseResult 1084Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1085 bool Virtual, AccessSpecifier Access, 1086 ParsedType basetype, SourceLocation BaseLoc, 1087 SourceLocation EllipsisLoc) { 1088 if (!classdecl) 1089 return true; 1090 1091 AdjustDeclIfTemplate(classdecl); 1092 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1093 if (!Class) 1094 return true; 1095 1096 TypeSourceInfo *TInfo = 0; 1097 GetTypeFromParser(basetype, &TInfo); 1098 1099 if (EllipsisLoc.isInvalid() && 1100 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1101 UPPC_BaseType)) 1102 return true; 1103 1104 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1105 Virtual, Access, TInfo, 1106 EllipsisLoc)) 1107 return BaseSpec; 1108 1109 return true; 1110} 1111 1112/// \brief Performs the actual work of attaching the given base class 1113/// specifiers to a C++ class. 1114bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1115 unsigned NumBases) { 1116 if (NumBases == 0) 1117 return false; 1118 1119 // Used to keep track of which base types we have already seen, so 1120 // that we can properly diagnose redundant direct base types. Note 1121 // that the key is always the unqualified canonical type of the base 1122 // class. 1123 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1124 1125 // Copy non-redundant base specifiers into permanent storage. 1126 unsigned NumGoodBases = 0; 1127 bool Invalid = false; 1128 for (unsigned idx = 0; idx < NumBases; ++idx) { 1129 QualType NewBaseType 1130 = Context.getCanonicalType(Bases[idx]->getType()); 1131 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1132 if (KnownBaseTypes[NewBaseType]) { 1133 // C++ [class.mi]p3: 1134 // A class shall not be specified as a direct base class of a 1135 // derived class more than once. 1136 Diag(Bases[idx]->getSourceRange().getBegin(), 1137 diag::err_duplicate_base_class) 1138 << KnownBaseTypes[NewBaseType]->getType() 1139 << Bases[idx]->getSourceRange(); 1140 1141 // Delete the duplicate base class specifier; we're going to 1142 // overwrite its pointer later. 1143 Context.Deallocate(Bases[idx]); 1144 1145 Invalid = true; 1146 } else { 1147 // Okay, add this new base class. 1148 KnownBaseTypes[NewBaseType] = Bases[idx]; 1149 Bases[NumGoodBases++] = Bases[idx]; 1150 } 1151 } 1152 1153 // Attach the remaining base class specifiers to the derived class. 1154 Class->setBases(Bases, NumGoodBases); 1155 1156 // Delete the remaining (good) base class specifiers, since their 1157 // data has been copied into the CXXRecordDecl. 1158 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1159 Context.Deallocate(Bases[idx]); 1160 1161 return Invalid; 1162} 1163 1164/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1165/// class, after checking whether there are any duplicate base 1166/// classes. 1167void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1168 unsigned NumBases) { 1169 if (!ClassDecl || !Bases || !NumBases) 1170 return; 1171 1172 AdjustDeclIfTemplate(ClassDecl); 1173 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1174 (CXXBaseSpecifier**)(Bases), NumBases); 1175} 1176 1177static CXXRecordDecl *GetClassForType(QualType T) { 1178 if (const RecordType *RT = T->getAs<RecordType>()) 1179 return cast<CXXRecordDecl>(RT->getDecl()); 1180 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1181 return ICT->getDecl(); 1182 else 1183 return 0; 1184} 1185 1186/// \brief Determine whether the type \p Derived is a C++ class that is 1187/// derived from the type \p Base. 1188bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1189 if (!getLangOptions().CPlusPlus) 1190 return false; 1191 1192 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1193 if (!DerivedRD) 1194 return false; 1195 1196 CXXRecordDecl *BaseRD = GetClassForType(Base); 1197 if (!BaseRD) 1198 return false; 1199 1200 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1201 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1202} 1203 1204/// \brief Determine whether the type \p Derived is a C++ class that is 1205/// derived from the type \p Base. 1206bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1207 if (!getLangOptions().CPlusPlus) 1208 return false; 1209 1210 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1211 if (!DerivedRD) 1212 return false; 1213 1214 CXXRecordDecl *BaseRD = GetClassForType(Base); 1215 if (!BaseRD) 1216 return false; 1217 1218 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1219} 1220 1221void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1222 CXXCastPath &BasePathArray) { 1223 assert(BasePathArray.empty() && "Base path array must be empty!"); 1224 assert(Paths.isRecordingPaths() && "Must record paths!"); 1225 1226 const CXXBasePath &Path = Paths.front(); 1227 1228 // We first go backward and check if we have a virtual base. 1229 // FIXME: It would be better if CXXBasePath had the base specifier for 1230 // the nearest virtual base. 1231 unsigned Start = 0; 1232 for (unsigned I = Path.size(); I != 0; --I) { 1233 if (Path[I - 1].Base->isVirtual()) { 1234 Start = I - 1; 1235 break; 1236 } 1237 } 1238 1239 // Now add all bases. 1240 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1241 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1242} 1243 1244/// \brief Determine whether the given base path includes a virtual 1245/// base class. 1246bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1247 for (CXXCastPath::const_iterator B = BasePath.begin(), 1248 BEnd = BasePath.end(); 1249 B != BEnd; ++B) 1250 if ((*B)->isVirtual()) 1251 return true; 1252 1253 return false; 1254} 1255 1256/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1257/// conversion (where Derived and Base are class types) is 1258/// well-formed, meaning that the conversion is unambiguous (and 1259/// that all of the base classes are accessible). Returns true 1260/// and emits a diagnostic if the code is ill-formed, returns false 1261/// otherwise. Loc is the location where this routine should point to 1262/// if there is an error, and Range is the source range to highlight 1263/// if there is an error. 1264bool 1265Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1266 unsigned InaccessibleBaseID, 1267 unsigned AmbigiousBaseConvID, 1268 SourceLocation Loc, SourceRange Range, 1269 DeclarationName Name, 1270 CXXCastPath *BasePath) { 1271 // First, determine whether the path from Derived to Base is 1272 // ambiguous. This is slightly more expensive than checking whether 1273 // the Derived to Base conversion exists, because here we need to 1274 // explore multiple paths to determine if there is an ambiguity. 1275 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1276 /*DetectVirtual=*/false); 1277 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1278 assert(DerivationOkay && 1279 "Can only be used with a derived-to-base conversion"); 1280 (void)DerivationOkay; 1281 1282 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1283 if (InaccessibleBaseID) { 1284 // Check that the base class can be accessed. 1285 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1286 InaccessibleBaseID)) { 1287 case AR_inaccessible: 1288 return true; 1289 case AR_accessible: 1290 case AR_dependent: 1291 case AR_delayed: 1292 break; 1293 } 1294 } 1295 1296 // Build a base path if necessary. 1297 if (BasePath) 1298 BuildBasePathArray(Paths, *BasePath); 1299 return false; 1300 } 1301 1302 // We know that the derived-to-base conversion is ambiguous, and 1303 // we're going to produce a diagnostic. Perform the derived-to-base 1304 // search just one more time to compute all of the possible paths so 1305 // that we can print them out. This is more expensive than any of 1306 // the previous derived-to-base checks we've done, but at this point 1307 // performance isn't as much of an issue. 1308 Paths.clear(); 1309 Paths.setRecordingPaths(true); 1310 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1311 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1312 (void)StillOkay; 1313 1314 // Build up a textual representation of the ambiguous paths, e.g., 1315 // D -> B -> A, that will be used to illustrate the ambiguous 1316 // conversions in the diagnostic. We only print one of the paths 1317 // to each base class subobject. 1318 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1319 1320 Diag(Loc, AmbigiousBaseConvID) 1321 << Derived << Base << PathDisplayStr << Range << Name; 1322 return true; 1323} 1324 1325bool 1326Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1327 SourceLocation Loc, SourceRange Range, 1328 CXXCastPath *BasePath, 1329 bool IgnoreAccess) { 1330 return CheckDerivedToBaseConversion(Derived, Base, 1331 IgnoreAccess ? 0 1332 : diag::err_upcast_to_inaccessible_base, 1333 diag::err_ambiguous_derived_to_base_conv, 1334 Loc, Range, DeclarationName(), 1335 BasePath); 1336} 1337 1338 1339/// @brief Builds a string representing ambiguous paths from a 1340/// specific derived class to different subobjects of the same base 1341/// class. 1342/// 1343/// This function builds a string that can be used in error messages 1344/// to show the different paths that one can take through the 1345/// inheritance hierarchy to go from the derived class to different 1346/// subobjects of a base class. The result looks something like this: 1347/// @code 1348/// struct D -> struct B -> struct A 1349/// struct D -> struct C -> struct A 1350/// @endcode 1351std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1352 std::string PathDisplayStr; 1353 std::set<unsigned> DisplayedPaths; 1354 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1355 Path != Paths.end(); ++Path) { 1356 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1357 // We haven't displayed a path to this particular base 1358 // class subobject yet. 1359 PathDisplayStr += "\n "; 1360 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1361 for (CXXBasePath::const_iterator Element = Path->begin(); 1362 Element != Path->end(); ++Element) 1363 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1364 } 1365 } 1366 1367 return PathDisplayStr; 1368} 1369 1370//===----------------------------------------------------------------------===// 1371// C++ class member Handling 1372//===----------------------------------------------------------------------===// 1373 1374/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1375Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1376 SourceLocation ASLoc, 1377 SourceLocation ColonLoc) { 1378 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1379 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1380 ASLoc, ColonLoc); 1381 CurContext->addHiddenDecl(ASDecl); 1382 return ASDecl; 1383} 1384 1385/// CheckOverrideControl - Check C++0x override control semantics. 1386void Sema::CheckOverrideControl(const Decl *D) { 1387 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1388 if (!MD || !MD->isVirtual()) 1389 return; 1390 1391 if (MD->isDependentContext()) 1392 return; 1393 1394 // C++0x [class.virtual]p3: 1395 // If a virtual function is marked with the virt-specifier override and does 1396 // not override a member function of a base class, 1397 // the program is ill-formed. 1398 bool HasOverriddenMethods = 1399 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1400 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 1401 Diag(MD->getLocation(), 1402 diag::err_function_marked_override_not_overriding) 1403 << MD->getDeclName(); 1404 return; 1405 } 1406} 1407 1408/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1409/// function overrides a virtual member function marked 'final', according to 1410/// C++0x [class.virtual]p3. 1411bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1412 const CXXMethodDecl *Old) { 1413 if (!Old->hasAttr<FinalAttr>()) 1414 return false; 1415 1416 Diag(New->getLocation(), diag::err_final_function_overridden) 1417 << New->getDeclName(); 1418 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1419 return true; 1420} 1421 1422/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1423/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1424/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1425/// one has been parsed, and 'HasDeferredInit' is true if an initializer is 1426/// present but parsing it has been deferred. 1427Decl * 1428Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1429 MultiTemplateParamsArg TemplateParameterLists, 1430 Expr *BW, const VirtSpecifiers &VS, 1431 Expr *InitExpr, bool HasDeferredInit, 1432 bool IsDefinition) { 1433 const DeclSpec &DS = D.getDeclSpec(); 1434 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1435 DeclarationName Name = NameInfo.getName(); 1436 SourceLocation Loc = NameInfo.getLoc(); 1437 1438 // For anonymous bitfields, the location should point to the type. 1439 if (Loc.isInvalid()) 1440 Loc = D.getSourceRange().getBegin(); 1441 1442 Expr *BitWidth = static_cast<Expr*>(BW); 1443 Expr *Init = static_cast<Expr*>(InitExpr); 1444 1445 assert(isa<CXXRecordDecl>(CurContext)); 1446 assert(!DS.isFriendSpecified()); 1447 assert(!Init || !HasDeferredInit); 1448 1449 bool isFunc = D.isDeclarationOfFunction(); 1450 1451 // C++ 9.2p6: A member shall not be declared to have automatic storage 1452 // duration (auto, register) or with the extern storage-class-specifier. 1453 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1454 // data members and cannot be applied to names declared const or static, 1455 // and cannot be applied to reference members. 1456 switch (DS.getStorageClassSpec()) { 1457 case DeclSpec::SCS_unspecified: 1458 case DeclSpec::SCS_typedef: 1459 case DeclSpec::SCS_static: 1460 // FALL THROUGH. 1461 break; 1462 case DeclSpec::SCS_mutable: 1463 if (isFunc) { 1464 if (DS.getStorageClassSpecLoc().isValid()) 1465 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1466 else 1467 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1468 1469 // FIXME: It would be nicer if the keyword was ignored only for this 1470 // declarator. Otherwise we could get follow-up errors. 1471 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1472 } 1473 break; 1474 default: 1475 if (DS.getStorageClassSpecLoc().isValid()) 1476 Diag(DS.getStorageClassSpecLoc(), 1477 diag::err_storageclass_invalid_for_member); 1478 else 1479 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1480 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1481 } 1482 1483 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1484 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1485 !isFunc); 1486 1487 Decl *Member; 1488 if (isInstField) { 1489 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1490 1491 // FIXME: Check that the name is an identifier! 1492 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1493 1494 // Member field could not be with "template" keyword. 1495 // So TemplateParameterLists should be empty in this case. 1496 if (TemplateParameterLists.size()) { 1497 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0]; 1498 if (TemplateParams->size()) { 1499 // There is no such thing as a member field template. 1500 Diag(D.getIdentifierLoc(), diag::err_template_member) 1501 << II 1502 << SourceRange(TemplateParams->getTemplateLoc(), 1503 TemplateParams->getRAngleLoc()); 1504 } else { 1505 // There is an extraneous 'template<>' for this member. 1506 Diag(TemplateParams->getTemplateLoc(), 1507 diag::err_template_member_noparams) 1508 << II 1509 << SourceRange(TemplateParams->getTemplateLoc(), 1510 TemplateParams->getRAngleLoc()); 1511 } 1512 return 0; 1513 } 1514 1515 if (SS.isSet() && !SS.isInvalid()) { 1516 // The user provided a superfluous scope specifier inside a class 1517 // definition: 1518 // 1519 // class X { 1520 // int X::member; 1521 // }; 1522 DeclContext *DC = 0; 1523 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1524 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1525 << Name << FixItHint::CreateRemoval(SS.getRange()); 1526 else 1527 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1528 << Name << SS.getRange(); 1529 1530 SS.clear(); 1531 } 1532 1533 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1534 HasDeferredInit, AS); 1535 assert(Member && "HandleField never returns null"); 1536 } else { 1537 assert(!HasDeferredInit); 1538 1539 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 1540 if (!Member) { 1541 return 0; 1542 } 1543 1544 // Non-instance-fields can't have a bitfield. 1545 if (BitWidth) { 1546 if (Member->isInvalidDecl()) { 1547 // don't emit another diagnostic. 1548 } else if (isa<VarDecl>(Member)) { 1549 // C++ 9.6p3: A bit-field shall not be a static member. 1550 // "static member 'A' cannot be a bit-field" 1551 Diag(Loc, diag::err_static_not_bitfield) 1552 << Name << BitWidth->getSourceRange(); 1553 } else if (isa<TypedefDecl>(Member)) { 1554 // "typedef member 'x' cannot be a bit-field" 1555 Diag(Loc, diag::err_typedef_not_bitfield) 1556 << Name << BitWidth->getSourceRange(); 1557 } else { 1558 // A function typedef ("typedef int f(); f a;"). 1559 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1560 Diag(Loc, diag::err_not_integral_type_bitfield) 1561 << Name << cast<ValueDecl>(Member)->getType() 1562 << BitWidth->getSourceRange(); 1563 } 1564 1565 BitWidth = 0; 1566 Member->setInvalidDecl(); 1567 } 1568 1569 Member->setAccess(AS); 1570 1571 // If we have declared a member function template, set the access of the 1572 // templated declaration as well. 1573 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1574 FunTmpl->getTemplatedDecl()->setAccess(AS); 1575 } 1576 1577 if (VS.isOverrideSpecified()) { 1578 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1579 if (!MD || !MD->isVirtual()) { 1580 Diag(Member->getLocStart(), 1581 diag::override_keyword_only_allowed_on_virtual_member_functions) 1582 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1583 } else 1584 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1585 } 1586 if (VS.isFinalSpecified()) { 1587 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1588 if (!MD || !MD->isVirtual()) { 1589 Diag(Member->getLocStart(), 1590 diag::override_keyword_only_allowed_on_virtual_member_functions) 1591 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1592 } else 1593 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1594 } 1595 1596 if (VS.getLastLocation().isValid()) { 1597 // Update the end location of a method that has a virt-specifiers. 1598 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1599 MD->setRangeEnd(VS.getLastLocation()); 1600 } 1601 1602 CheckOverrideControl(Member); 1603 1604 assert((Name || isInstField) && "No identifier for non-field ?"); 1605 1606 if (Init) 1607 AddInitializerToDecl(Member, Init, false, 1608 DS.getTypeSpecType() == DeclSpec::TST_auto); 1609 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1610 ActOnUninitializedDecl(Member, DS.getTypeSpecType() == DeclSpec::TST_auto); 1611 1612 FinalizeDeclaration(Member); 1613 1614 if (isInstField) 1615 FieldCollector->Add(cast<FieldDecl>(Member)); 1616 return Member; 1617} 1618 1619/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1620/// in-class initializer for a non-static C++ class member, and after 1621/// instantiating an in-class initializer in a class template. Such actions 1622/// are deferred until the class is complete. 1623void 1624Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc, 1625 Expr *InitExpr) { 1626 FieldDecl *FD = cast<FieldDecl>(D); 1627 1628 if (!InitExpr) { 1629 FD->setInvalidDecl(); 1630 FD->removeInClassInitializer(); 1631 return; 1632 } 1633 1634 ExprResult Init = InitExpr; 1635 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1636 // FIXME: if there is no EqualLoc, this is list-initialization. 1637 Init = PerformCopyInitialization( 1638 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr); 1639 if (Init.isInvalid()) { 1640 FD->setInvalidDecl(); 1641 return; 1642 } 1643 1644 CheckImplicitConversions(Init.get(), EqualLoc); 1645 } 1646 1647 // C++0x [class.base.init]p7: 1648 // The initialization of each base and member constitutes a 1649 // full-expression. 1650 Init = MaybeCreateExprWithCleanups(Init); 1651 if (Init.isInvalid()) { 1652 FD->setInvalidDecl(); 1653 return; 1654 } 1655 1656 InitExpr = Init.release(); 1657 1658 FD->setInClassInitializer(InitExpr); 1659} 1660 1661/// \brief Find the direct and/or virtual base specifiers that 1662/// correspond to the given base type, for use in base initialization 1663/// within a constructor. 1664static bool FindBaseInitializer(Sema &SemaRef, 1665 CXXRecordDecl *ClassDecl, 1666 QualType BaseType, 1667 const CXXBaseSpecifier *&DirectBaseSpec, 1668 const CXXBaseSpecifier *&VirtualBaseSpec) { 1669 // First, check for a direct base class. 1670 DirectBaseSpec = 0; 1671 for (CXXRecordDecl::base_class_const_iterator Base 1672 = ClassDecl->bases_begin(); 1673 Base != ClassDecl->bases_end(); ++Base) { 1674 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1675 // We found a direct base of this type. That's what we're 1676 // initializing. 1677 DirectBaseSpec = &*Base; 1678 break; 1679 } 1680 } 1681 1682 // Check for a virtual base class. 1683 // FIXME: We might be able to short-circuit this if we know in advance that 1684 // there are no virtual bases. 1685 VirtualBaseSpec = 0; 1686 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1687 // We haven't found a base yet; search the class hierarchy for a 1688 // virtual base class. 1689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1690 /*DetectVirtual=*/false); 1691 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1692 BaseType, Paths)) { 1693 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1694 Path != Paths.end(); ++Path) { 1695 if (Path->back().Base->isVirtual()) { 1696 VirtualBaseSpec = Path->back().Base; 1697 break; 1698 } 1699 } 1700 } 1701 } 1702 1703 return DirectBaseSpec || VirtualBaseSpec; 1704} 1705 1706/// \brief Handle a C++ member initializer using braced-init-list syntax. 1707MemInitResult 1708Sema::ActOnMemInitializer(Decl *ConstructorD, 1709 Scope *S, 1710 CXXScopeSpec &SS, 1711 IdentifierInfo *MemberOrBase, 1712 ParsedType TemplateTypeTy, 1713 SourceLocation IdLoc, 1714 Expr *InitList, 1715 SourceLocation EllipsisLoc) { 1716 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1717 IdLoc, MultiInitializer(InitList), EllipsisLoc); 1718} 1719 1720/// \brief Handle a C++ member initializer using parentheses syntax. 1721MemInitResult 1722Sema::ActOnMemInitializer(Decl *ConstructorD, 1723 Scope *S, 1724 CXXScopeSpec &SS, 1725 IdentifierInfo *MemberOrBase, 1726 ParsedType TemplateTypeTy, 1727 SourceLocation IdLoc, 1728 SourceLocation LParenLoc, 1729 Expr **Args, unsigned NumArgs, 1730 SourceLocation RParenLoc, 1731 SourceLocation EllipsisLoc) { 1732 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1733 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs, 1734 RParenLoc), 1735 EllipsisLoc); 1736} 1737 1738/// \brief Handle a C++ member initializer. 1739MemInitResult 1740Sema::BuildMemInitializer(Decl *ConstructorD, 1741 Scope *S, 1742 CXXScopeSpec &SS, 1743 IdentifierInfo *MemberOrBase, 1744 ParsedType TemplateTypeTy, 1745 SourceLocation IdLoc, 1746 const MultiInitializer &Args, 1747 SourceLocation EllipsisLoc) { 1748 if (!ConstructorD) 1749 return true; 1750 1751 AdjustDeclIfTemplate(ConstructorD); 1752 1753 CXXConstructorDecl *Constructor 1754 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1755 if (!Constructor) { 1756 // The user wrote a constructor initializer on a function that is 1757 // not a C++ constructor. Ignore the error for now, because we may 1758 // have more member initializers coming; we'll diagnose it just 1759 // once in ActOnMemInitializers. 1760 return true; 1761 } 1762 1763 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1764 1765 // C++ [class.base.init]p2: 1766 // Names in a mem-initializer-id are looked up in the scope of the 1767 // constructor's class and, if not found in that scope, are looked 1768 // up in the scope containing the constructor's definition. 1769 // [Note: if the constructor's class contains a member with the 1770 // same name as a direct or virtual base class of the class, a 1771 // mem-initializer-id naming the member or base class and composed 1772 // of a single identifier refers to the class member. A 1773 // mem-initializer-id for the hidden base class may be specified 1774 // using a qualified name. ] 1775 if (!SS.getScopeRep() && !TemplateTypeTy) { 1776 // Look for a member, first. 1777 FieldDecl *Member = 0; 1778 DeclContext::lookup_result Result 1779 = ClassDecl->lookup(MemberOrBase); 1780 if (Result.first != Result.second) { 1781 Member = dyn_cast<FieldDecl>(*Result.first); 1782 1783 if (Member) { 1784 if (EllipsisLoc.isValid()) 1785 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1786 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc()); 1787 1788 return BuildMemberInitializer(Member, Args, IdLoc); 1789 } 1790 1791 // Handle anonymous union case. 1792 if (IndirectFieldDecl* IndirectField 1793 = dyn_cast<IndirectFieldDecl>(*Result.first)) { 1794 if (EllipsisLoc.isValid()) 1795 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1796 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc()); 1797 1798 return BuildMemberInitializer(IndirectField, Args, IdLoc); 1799 } 1800 } 1801 } 1802 // It didn't name a member, so see if it names a class. 1803 QualType BaseType; 1804 TypeSourceInfo *TInfo = 0; 1805 1806 if (TemplateTypeTy) { 1807 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1808 } else { 1809 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1810 LookupParsedName(R, S, &SS); 1811 1812 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1813 if (!TyD) { 1814 if (R.isAmbiguous()) return true; 1815 1816 // We don't want access-control diagnostics here. 1817 R.suppressDiagnostics(); 1818 1819 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1820 bool NotUnknownSpecialization = false; 1821 DeclContext *DC = computeDeclContext(SS, false); 1822 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1823 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1824 1825 if (!NotUnknownSpecialization) { 1826 // When the scope specifier can refer to a member of an unknown 1827 // specialization, we take it as a type name. 1828 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1829 SS.getWithLocInContext(Context), 1830 *MemberOrBase, IdLoc); 1831 if (BaseType.isNull()) 1832 return true; 1833 1834 R.clear(); 1835 R.setLookupName(MemberOrBase); 1836 } 1837 } 1838 1839 // If no results were found, try to correct typos. 1840 TypoCorrection Corr; 1841 if (R.empty() && BaseType.isNull() && 1842 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1843 ClassDecl, false, CTC_NoKeywords))) { 1844 std::string CorrectedStr(Corr.getAsString(getLangOptions())); 1845 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions())); 1846 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1847 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1848 // We have found a non-static data member with a similar 1849 // name to what was typed; complain and initialize that 1850 // member. 1851 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1852 << MemberOrBase << true << CorrectedQuotedStr 1853 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1854 Diag(Member->getLocation(), diag::note_previous_decl) 1855 << CorrectedQuotedStr; 1856 1857 return BuildMemberInitializer(Member, Args, IdLoc); 1858 } 1859 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1860 const CXXBaseSpecifier *DirectBaseSpec; 1861 const CXXBaseSpecifier *VirtualBaseSpec; 1862 if (FindBaseInitializer(*this, ClassDecl, 1863 Context.getTypeDeclType(Type), 1864 DirectBaseSpec, VirtualBaseSpec)) { 1865 // We have found a direct or virtual base class with a 1866 // similar name to what was typed; complain and initialize 1867 // that base class. 1868 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1869 << MemberOrBase << false << CorrectedQuotedStr 1870 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1871 1872 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1873 : VirtualBaseSpec; 1874 Diag(BaseSpec->getSourceRange().getBegin(), 1875 diag::note_base_class_specified_here) 1876 << BaseSpec->getType() 1877 << BaseSpec->getSourceRange(); 1878 1879 TyD = Type; 1880 } 1881 } 1882 } 1883 1884 if (!TyD && BaseType.isNull()) { 1885 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1886 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc()); 1887 return true; 1888 } 1889 } 1890 1891 if (BaseType.isNull()) { 1892 BaseType = Context.getTypeDeclType(TyD); 1893 if (SS.isSet()) { 1894 NestedNameSpecifier *Qualifier = 1895 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1896 1897 // FIXME: preserve source range information 1898 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1899 } 1900 } 1901 } 1902 1903 if (!TInfo) 1904 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1905 1906 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc); 1907} 1908 1909/// Checks a member initializer expression for cases where reference (or 1910/// pointer) members are bound to by-value parameters (or their addresses). 1911static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1912 Expr *Init, 1913 SourceLocation IdLoc) { 1914 QualType MemberTy = Member->getType(); 1915 1916 // We only handle pointers and references currently. 1917 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 1918 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 1919 return; 1920 1921 const bool IsPointer = MemberTy->isPointerType(); 1922 if (IsPointer) { 1923 if (const UnaryOperator *Op 1924 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 1925 // The only case we're worried about with pointers requires taking the 1926 // address. 1927 if (Op->getOpcode() != UO_AddrOf) 1928 return; 1929 1930 Init = Op->getSubExpr(); 1931 } else { 1932 // We only handle address-of expression initializers for pointers. 1933 return; 1934 } 1935 } 1936 1937 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 1938 // Taking the address of a temporary will be diagnosed as a hard error. 1939 if (IsPointer) 1940 return; 1941 1942 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 1943 << Member << Init->getSourceRange(); 1944 } else if (const DeclRefExpr *DRE 1945 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 1946 // We only warn when referring to a non-reference parameter declaration. 1947 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 1948 if (!Parameter || Parameter->getType()->isReferenceType()) 1949 return; 1950 1951 S.Diag(Init->getExprLoc(), 1952 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 1953 : diag::warn_bind_ref_member_to_parameter) 1954 << Member << Parameter << Init->getSourceRange(); 1955 } else { 1956 // Other initializers are fine. 1957 return; 1958 } 1959 1960 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 1961 << (unsigned)IsPointer; 1962} 1963 1964/// Checks an initializer expression for use of uninitialized fields, such as 1965/// containing the field that is being initialized. Returns true if there is an 1966/// uninitialized field was used an updates the SourceLocation parameter; false 1967/// otherwise. 1968static bool InitExprContainsUninitializedFields(const Stmt *S, 1969 const ValueDecl *LhsField, 1970 SourceLocation *L) { 1971 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1972 1973 if (isa<CallExpr>(S)) { 1974 // Do not descend into function calls or constructors, as the use 1975 // of an uninitialized field may be valid. One would have to inspect 1976 // the contents of the function/ctor to determine if it is safe or not. 1977 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1978 // may be safe, depending on what the function/ctor does. 1979 return false; 1980 } 1981 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1982 const NamedDecl *RhsField = ME->getMemberDecl(); 1983 1984 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1985 // The member expression points to a static data member. 1986 assert(VD->isStaticDataMember() && 1987 "Member points to non-static data member!"); 1988 (void)VD; 1989 return false; 1990 } 1991 1992 if (isa<EnumConstantDecl>(RhsField)) { 1993 // The member expression points to an enum. 1994 return false; 1995 } 1996 1997 if (RhsField == LhsField) { 1998 // Initializing a field with itself. Throw a warning. 1999 // But wait; there are exceptions! 2000 // Exception #1: The field may not belong to this record. 2001 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 2002 const Expr *base = ME->getBase(); 2003 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 2004 // Even though the field matches, it does not belong to this record. 2005 return false; 2006 } 2007 // None of the exceptions triggered; return true to indicate an 2008 // uninitialized field was used. 2009 *L = ME->getMemberLoc(); 2010 return true; 2011 } 2012 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 2013 // sizeof/alignof doesn't reference contents, do not warn. 2014 return false; 2015 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 2016 // address-of doesn't reference contents (the pointer may be dereferenced 2017 // in the same expression but it would be rare; and weird). 2018 if (UOE->getOpcode() == UO_AddrOf) 2019 return false; 2020 } 2021 for (Stmt::const_child_range it = S->children(); it; ++it) { 2022 if (!*it) { 2023 // An expression such as 'member(arg ?: "")' may trigger this. 2024 continue; 2025 } 2026 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 2027 return true; 2028 } 2029 return false; 2030} 2031 2032MemInitResult 2033Sema::BuildMemberInitializer(ValueDecl *Member, 2034 const MultiInitializer &Args, 2035 SourceLocation IdLoc) { 2036 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2037 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2038 assert((DirectMember || IndirectMember) && 2039 "Member must be a FieldDecl or IndirectFieldDecl"); 2040 2041 if (Member->isInvalidDecl()) 2042 return true; 2043 2044 // Diagnose value-uses of fields to initialize themselves, e.g. 2045 // foo(foo) 2046 // where foo is not also a parameter to the constructor. 2047 // TODO: implement -Wuninitialized and fold this into that framework. 2048 for (MultiInitializer::iterator I = Args.begin(), E = Args.end(); 2049 I != E; ++I) { 2050 SourceLocation L; 2051 Expr *Arg = *I; 2052 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg)) 2053 Arg = DIE->getInit(); 2054 if (InitExprContainsUninitializedFields(Arg, Member, &L)) { 2055 // FIXME: Return true in the case when other fields are used before being 2056 // uninitialized. For example, let this field be the i'th field. When 2057 // initializing the i'th field, throw a warning if any of the >= i'th 2058 // fields are used, as they are not yet initialized. 2059 // Right now we are only handling the case where the i'th field uses 2060 // itself in its initializer. 2061 Diag(L, diag::warn_field_is_uninit); 2062 } 2063 } 2064 2065 bool HasDependentArg = Args.isTypeDependent(); 2066 2067 Expr *Init; 2068 if (Member->getType()->isDependentType() || HasDependentArg) { 2069 // Can't check initialization for a member of dependent type or when 2070 // any of the arguments are type-dependent expressions. 2071 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType()); 2072 2073 DiscardCleanupsInEvaluationContext(); 2074 } else { 2075 // Initialize the member. 2076 InitializedEntity MemberEntity = 2077 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2078 : InitializedEntity::InitializeMember(IndirectMember, 0); 2079 InitializationKind Kind = 2080 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(), 2081 Args.getEndLoc()); 2082 2083 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind); 2084 if (MemberInit.isInvalid()) 2085 return true; 2086 2087 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc()); 2088 2089 // C++0x [class.base.init]p7: 2090 // The initialization of each base and member constitutes a 2091 // full-expression. 2092 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2093 if (MemberInit.isInvalid()) 2094 return true; 2095 2096 // If we are in a dependent context, template instantiation will 2097 // perform this type-checking again. Just save the arguments that we 2098 // received in a ParenListExpr. 2099 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2100 // of the information that we have about the member 2101 // initializer. However, deconstructing the ASTs is a dicey process, 2102 // and this approach is far more likely to get the corner cases right. 2103 if (CurContext->isDependentContext()) { 2104 Init = Args.CreateInitExpr(Context, 2105 Member->getType().getNonReferenceType()); 2106 } else { 2107 Init = MemberInit.get(); 2108 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2109 } 2110 } 2111 2112 if (DirectMember) { 2113 return new (Context) CXXCtorInitializer(Context, DirectMember, 2114 IdLoc, Args.getStartLoc(), 2115 Init, Args.getEndLoc()); 2116 } else { 2117 return new (Context) CXXCtorInitializer(Context, IndirectMember, 2118 IdLoc, Args.getStartLoc(), 2119 Init, Args.getEndLoc()); 2120 } 2121} 2122 2123MemInitResult 2124Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, 2125 const MultiInitializer &Args, 2126 SourceLocation NameLoc, 2127 CXXRecordDecl *ClassDecl) { 2128 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2129 if (!LangOpts.CPlusPlus0x) 2130 return Diag(Loc, diag::err_delegation_0x_only) 2131 << TInfo->getTypeLoc().getLocalSourceRange(); 2132 2133 // Initialize the object. 2134 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2135 QualType(ClassDecl->getTypeForDecl(), 0)); 2136 InitializationKind Kind = 2137 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(), 2138 Args.getEndLoc()); 2139 2140 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind); 2141 if (DelegationInit.isInvalid()) 2142 return true; 2143 2144 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get()); 2145 CXXConstructorDecl *Constructor 2146 = ConExpr->getConstructor(); 2147 assert(Constructor && "Delegating constructor with no target?"); 2148 2149 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc()); 2150 2151 // C++0x [class.base.init]p7: 2152 // The initialization of each base and member constitutes a 2153 // full-expression. 2154 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2155 if (DelegationInit.isInvalid()) 2156 return true; 2157 2158 assert(!CurContext->isDependentContext()); 2159 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(), 2160 Constructor, 2161 DelegationInit.takeAs<Expr>(), 2162 Args.getEndLoc()); 2163} 2164 2165MemInitResult 2166Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2167 const MultiInitializer &Args, 2168 CXXRecordDecl *ClassDecl, 2169 SourceLocation EllipsisLoc) { 2170 bool HasDependentArg = Args.isTypeDependent(); 2171 2172 SourceLocation BaseLoc 2173 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2174 2175 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2176 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2177 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2178 2179 // C++ [class.base.init]p2: 2180 // [...] Unless the mem-initializer-id names a nonstatic data 2181 // member of the constructor's class or a direct or virtual base 2182 // of that class, the mem-initializer is ill-formed. A 2183 // mem-initializer-list can initialize a base class using any 2184 // name that denotes that base class type. 2185 bool Dependent = BaseType->isDependentType() || HasDependentArg; 2186 2187 if (EllipsisLoc.isValid()) { 2188 // This is a pack expansion. 2189 if (!BaseType->containsUnexpandedParameterPack()) { 2190 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2191 << SourceRange(BaseLoc, Args.getEndLoc()); 2192 2193 EllipsisLoc = SourceLocation(); 2194 } 2195 } else { 2196 // Check for any unexpanded parameter packs. 2197 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2198 return true; 2199 2200 if (Args.DiagnoseUnexpandedParameterPack(*this)) 2201 return true; 2202 } 2203 2204 // Check for direct and virtual base classes. 2205 const CXXBaseSpecifier *DirectBaseSpec = 0; 2206 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2207 if (!Dependent) { 2208 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2209 BaseType)) 2210 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl); 2211 2212 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2213 VirtualBaseSpec); 2214 2215 // C++ [base.class.init]p2: 2216 // Unless the mem-initializer-id names a nonstatic data member of the 2217 // constructor's class or a direct or virtual base of that class, the 2218 // mem-initializer is ill-formed. 2219 if (!DirectBaseSpec && !VirtualBaseSpec) { 2220 // If the class has any dependent bases, then it's possible that 2221 // one of those types will resolve to the same type as 2222 // BaseType. Therefore, just treat this as a dependent base 2223 // class initialization. FIXME: Should we try to check the 2224 // initialization anyway? It seems odd. 2225 if (ClassDecl->hasAnyDependentBases()) 2226 Dependent = true; 2227 else 2228 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2229 << BaseType << Context.getTypeDeclType(ClassDecl) 2230 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2231 } 2232 } 2233 2234 if (Dependent) { 2235 // Can't check initialization for a base of dependent type or when 2236 // any of the arguments are type-dependent expressions. 2237 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType); 2238 2239 DiscardCleanupsInEvaluationContext(); 2240 2241 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2242 /*IsVirtual=*/false, 2243 Args.getStartLoc(), BaseInit, 2244 Args.getEndLoc(), EllipsisLoc); 2245 } 2246 2247 // C++ [base.class.init]p2: 2248 // If a mem-initializer-id is ambiguous because it designates both 2249 // a direct non-virtual base class and an inherited virtual base 2250 // class, the mem-initializer is ill-formed. 2251 if (DirectBaseSpec && VirtualBaseSpec) 2252 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2253 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2254 2255 CXXBaseSpecifier *BaseSpec 2256 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2257 if (!BaseSpec) 2258 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2259 2260 // Initialize the base. 2261 InitializedEntity BaseEntity = 2262 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2263 InitializationKind Kind = 2264 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(), 2265 Args.getEndLoc()); 2266 2267 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind); 2268 if (BaseInit.isInvalid()) 2269 return true; 2270 2271 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc()); 2272 2273 // C++0x [class.base.init]p7: 2274 // The initialization of each base and member constitutes a 2275 // full-expression. 2276 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2277 if (BaseInit.isInvalid()) 2278 return true; 2279 2280 // If we are in a dependent context, template instantiation will 2281 // perform this type-checking again. Just save the arguments that we 2282 // received in a ParenListExpr. 2283 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2284 // of the information that we have about the base 2285 // initializer. However, deconstructing the ASTs is a dicey process, 2286 // and this approach is far more likely to get the corner cases right. 2287 if (CurContext->isDependentContext()) 2288 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType)); 2289 2290 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2291 BaseSpec->isVirtual(), 2292 Args.getStartLoc(), 2293 BaseInit.takeAs<Expr>(), 2294 Args.getEndLoc(), EllipsisLoc); 2295} 2296 2297// Create a static_cast\<T&&>(expr). 2298static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2299 QualType ExprType = E->getType(); 2300 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2301 SourceLocation ExprLoc = E->getLocStart(); 2302 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2303 TargetType, ExprLoc); 2304 2305 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2306 SourceRange(ExprLoc, ExprLoc), 2307 E->getSourceRange()).take(); 2308} 2309 2310/// ImplicitInitializerKind - How an implicit base or member initializer should 2311/// initialize its base or member. 2312enum ImplicitInitializerKind { 2313 IIK_Default, 2314 IIK_Copy, 2315 IIK_Move 2316}; 2317 2318static bool 2319BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2320 ImplicitInitializerKind ImplicitInitKind, 2321 CXXBaseSpecifier *BaseSpec, 2322 bool IsInheritedVirtualBase, 2323 CXXCtorInitializer *&CXXBaseInit) { 2324 InitializedEntity InitEntity 2325 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2326 IsInheritedVirtualBase); 2327 2328 ExprResult BaseInit; 2329 2330 switch (ImplicitInitKind) { 2331 case IIK_Default: { 2332 InitializationKind InitKind 2333 = InitializationKind::CreateDefault(Constructor->getLocation()); 2334 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2335 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2336 MultiExprArg(SemaRef, 0, 0)); 2337 break; 2338 } 2339 2340 case IIK_Move: 2341 case IIK_Copy: { 2342 bool Moving = ImplicitInitKind == IIK_Move; 2343 ParmVarDecl *Param = Constructor->getParamDecl(0); 2344 QualType ParamType = Param->getType().getNonReferenceType(); 2345 2346 Expr *CopyCtorArg = 2347 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 2348 Constructor->getLocation(), ParamType, 2349 VK_LValue, 0); 2350 2351 // Cast to the base class to avoid ambiguities. 2352 QualType ArgTy = 2353 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2354 ParamType.getQualifiers()); 2355 2356 if (Moving) { 2357 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2358 } 2359 2360 CXXCastPath BasePath; 2361 BasePath.push_back(BaseSpec); 2362 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2363 CK_UncheckedDerivedToBase, 2364 Moving ? VK_XValue : VK_LValue, 2365 &BasePath).take(); 2366 2367 InitializationKind InitKind 2368 = InitializationKind::CreateDirect(Constructor->getLocation(), 2369 SourceLocation(), SourceLocation()); 2370 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2371 &CopyCtorArg, 1); 2372 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2373 MultiExprArg(&CopyCtorArg, 1)); 2374 break; 2375 } 2376 } 2377 2378 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2379 if (BaseInit.isInvalid()) 2380 return true; 2381 2382 CXXBaseInit = 2383 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2384 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2385 SourceLocation()), 2386 BaseSpec->isVirtual(), 2387 SourceLocation(), 2388 BaseInit.takeAs<Expr>(), 2389 SourceLocation(), 2390 SourceLocation()); 2391 2392 return false; 2393} 2394 2395static bool RefersToRValueRef(Expr *MemRef) { 2396 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2397 return Referenced->getType()->isRValueReferenceType(); 2398} 2399 2400static bool 2401BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2402 ImplicitInitializerKind ImplicitInitKind, 2403 FieldDecl *Field, IndirectFieldDecl *Indirect, 2404 CXXCtorInitializer *&CXXMemberInit) { 2405 if (Field->isInvalidDecl()) 2406 return true; 2407 2408 SourceLocation Loc = Constructor->getLocation(); 2409 2410 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2411 bool Moving = ImplicitInitKind == IIK_Move; 2412 ParmVarDecl *Param = Constructor->getParamDecl(0); 2413 QualType ParamType = Param->getType().getNonReferenceType(); 2414 2415 // Suppress copying zero-width bitfields. 2416 if (const Expr *Width = Field->getBitWidth()) 2417 if (Width->EvaluateAsInt(SemaRef.Context) == 0) 2418 return false; 2419 2420 Expr *MemberExprBase = 2421 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 2422 Loc, ParamType, VK_LValue, 0); 2423 2424 if (Moving) { 2425 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2426 } 2427 2428 // Build a reference to this field within the parameter. 2429 CXXScopeSpec SS; 2430 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2431 Sema::LookupMemberName); 2432 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2433 : cast<ValueDecl>(Field), AS_public); 2434 MemberLookup.resolveKind(); 2435 ExprResult CtorArg 2436 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2437 ParamType, Loc, 2438 /*IsArrow=*/false, 2439 SS, 2440 /*FirstQualifierInScope=*/0, 2441 MemberLookup, 2442 /*TemplateArgs=*/0); 2443 if (CtorArg.isInvalid()) 2444 return true; 2445 2446 // C++11 [class.copy]p15: 2447 // - if a member m has rvalue reference type T&&, it is direct-initialized 2448 // with static_cast<T&&>(x.m); 2449 if (RefersToRValueRef(CtorArg.get())) { 2450 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2451 } 2452 2453 // When the field we are copying is an array, create index variables for 2454 // each dimension of the array. We use these index variables to subscript 2455 // the source array, and other clients (e.g., CodeGen) will perform the 2456 // necessary iteration with these index variables. 2457 SmallVector<VarDecl *, 4> IndexVariables; 2458 QualType BaseType = Field->getType(); 2459 QualType SizeType = SemaRef.Context.getSizeType(); 2460 bool InitializingArray = false; 2461 while (const ConstantArrayType *Array 2462 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2463 InitializingArray = true; 2464 // Create the iteration variable for this array index. 2465 IdentifierInfo *IterationVarName = 0; 2466 { 2467 llvm::SmallString<8> Str; 2468 llvm::raw_svector_ostream OS(Str); 2469 OS << "__i" << IndexVariables.size(); 2470 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2471 } 2472 VarDecl *IterationVar 2473 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2474 IterationVarName, SizeType, 2475 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2476 SC_None, SC_None); 2477 IndexVariables.push_back(IterationVar); 2478 2479 // Create a reference to the iteration variable. 2480 ExprResult IterationVarRef 2481 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 2482 assert(!IterationVarRef.isInvalid() && 2483 "Reference to invented variable cannot fail!"); 2484 2485 // Subscript the array with this iteration variable. 2486 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2487 IterationVarRef.take(), 2488 Loc); 2489 if (CtorArg.isInvalid()) 2490 return true; 2491 2492 BaseType = Array->getElementType(); 2493 } 2494 2495 // The array subscript expression is an lvalue, which is wrong for moving. 2496 if (Moving && InitializingArray) 2497 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2498 2499 // Construct the entity that we will be initializing. For an array, this 2500 // will be first element in the array, which may require several levels 2501 // of array-subscript entities. 2502 SmallVector<InitializedEntity, 4> Entities; 2503 Entities.reserve(1 + IndexVariables.size()); 2504 if (Indirect) 2505 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2506 else 2507 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2508 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2509 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2510 0, 2511 Entities.back())); 2512 2513 // Direct-initialize to use the copy constructor. 2514 InitializationKind InitKind = 2515 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2516 2517 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2518 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2519 &CtorArgE, 1); 2520 2521 ExprResult MemberInit 2522 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2523 MultiExprArg(&CtorArgE, 1)); 2524 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2525 if (MemberInit.isInvalid()) 2526 return true; 2527 2528 if (Indirect) { 2529 assert(IndexVariables.size() == 0 && 2530 "Indirect field improperly initialized"); 2531 CXXMemberInit 2532 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2533 Loc, Loc, 2534 MemberInit.takeAs<Expr>(), 2535 Loc); 2536 } else 2537 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2538 Loc, MemberInit.takeAs<Expr>(), 2539 Loc, 2540 IndexVariables.data(), 2541 IndexVariables.size()); 2542 return false; 2543 } 2544 2545 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2546 2547 QualType FieldBaseElementType = 2548 SemaRef.Context.getBaseElementType(Field->getType()); 2549 2550 if (FieldBaseElementType->isRecordType()) { 2551 InitializedEntity InitEntity 2552 = Indirect? InitializedEntity::InitializeMember(Indirect) 2553 : InitializedEntity::InitializeMember(Field); 2554 InitializationKind InitKind = 2555 InitializationKind::CreateDefault(Loc); 2556 2557 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2558 ExprResult MemberInit = 2559 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2560 2561 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2562 if (MemberInit.isInvalid()) 2563 return true; 2564 2565 if (Indirect) 2566 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2567 Indirect, Loc, 2568 Loc, 2569 MemberInit.get(), 2570 Loc); 2571 else 2572 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2573 Field, Loc, Loc, 2574 MemberInit.get(), 2575 Loc); 2576 return false; 2577 } 2578 2579 if (!Field->getParent()->isUnion()) { 2580 if (FieldBaseElementType->isReferenceType()) { 2581 SemaRef.Diag(Constructor->getLocation(), 2582 diag::err_uninitialized_member_in_ctor) 2583 << (int)Constructor->isImplicit() 2584 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2585 << 0 << Field->getDeclName(); 2586 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2587 return true; 2588 } 2589 2590 if (FieldBaseElementType.isConstQualified()) { 2591 SemaRef.Diag(Constructor->getLocation(), 2592 diag::err_uninitialized_member_in_ctor) 2593 << (int)Constructor->isImplicit() 2594 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2595 << 1 << Field->getDeclName(); 2596 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2597 return true; 2598 } 2599 } 2600 2601 if (SemaRef.getLangOptions().ObjCAutoRefCount && 2602 FieldBaseElementType->isObjCRetainableType() && 2603 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2604 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2605 // Instant objects: 2606 // Default-initialize Objective-C pointers to NULL. 2607 CXXMemberInit 2608 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2609 Loc, Loc, 2610 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2611 Loc); 2612 return false; 2613 } 2614 2615 // Nothing to initialize. 2616 CXXMemberInit = 0; 2617 return false; 2618} 2619 2620namespace { 2621struct BaseAndFieldInfo { 2622 Sema &S; 2623 CXXConstructorDecl *Ctor; 2624 bool AnyErrorsInInits; 2625 ImplicitInitializerKind IIK; 2626 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2627 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2628 2629 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2630 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2631 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2632 if (Generated && Ctor->isCopyConstructor()) 2633 IIK = IIK_Copy; 2634 else if (Generated && Ctor->isMoveConstructor()) 2635 IIK = IIK_Move; 2636 else 2637 IIK = IIK_Default; 2638 } 2639}; 2640} 2641 2642/// \brief Determine whether the given indirect field declaration is somewhere 2643/// within an anonymous union. 2644static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2645 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2646 CEnd = F->chain_end(); 2647 C != CEnd; ++C) 2648 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2649 if (Record->isUnion()) 2650 return true; 2651 2652 return false; 2653} 2654 2655static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2656 FieldDecl *Field, 2657 IndirectFieldDecl *Indirect = 0) { 2658 2659 // Overwhelmingly common case: we have a direct initializer for this field. 2660 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2661 Info.AllToInit.push_back(Init); 2662 return false; 2663 } 2664 2665 // C++0x [class.base.init]p8: if the entity is a non-static data member that 2666 // has a brace-or-equal-initializer, the entity is initialized as specified 2667 // in [dcl.init]. 2668 if (Field->hasInClassInitializer()) { 2669 CXXCtorInitializer *Init; 2670 if (Indirect) 2671 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2672 SourceLocation(), 2673 SourceLocation(), 0, 2674 SourceLocation()); 2675 else 2676 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2677 SourceLocation(), 2678 SourceLocation(), 0, 2679 SourceLocation()); 2680 Info.AllToInit.push_back(Init); 2681 return false; 2682 } 2683 2684 // Don't build an implicit initializer for union members if none was 2685 // explicitly specified. 2686 if (Field->getParent()->isUnion() || 2687 (Indirect && isWithinAnonymousUnion(Indirect))) 2688 return false; 2689 2690 // Don't try to build an implicit initializer if there were semantic 2691 // errors in any of the initializers (and therefore we might be 2692 // missing some that the user actually wrote). 2693 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2694 return false; 2695 2696 CXXCtorInitializer *Init = 0; 2697 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2698 Indirect, Init)) 2699 return true; 2700 2701 if (Init) 2702 Info.AllToInit.push_back(Init); 2703 2704 return false; 2705} 2706 2707bool 2708Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2709 CXXCtorInitializer *Initializer) { 2710 assert(Initializer->isDelegatingInitializer()); 2711 Constructor->setNumCtorInitializers(1); 2712 CXXCtorInitializer **initializer = 2713 new (Context) CXXCtorInitializer*[1]; 2714 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2715 Constructor->setCtorInitializers(initializer); 2716 2717 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2718 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor); 2719 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2720 } 2721 2722 DelegatingCtorDecls.push_back(Constructor); 2723 2724 return false; 2725} 2726 2727bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2728 CXXCtorInitializer **Initializers, 2729 unsigned NumInitializers, 2730 bool AnyErrors) { 2731 if (Constructor->isDependentContext()) { 2732 // Just store the initializers as written, they will be checked during 2733 // instantiation. 2734 if (NumInitializers > 0) { 2735 Constructor->setNumCtorInitializers(NumInitializers); 2736 CXXCtorInitializer **baseOrMemberInitializers = 2737 new (Context) CXXCtorInitializer*[NumInitializers]; 2738 memcpy(baseOrMemberInitializers, Initializers, 2739 NumInitializers * sizeof(CXXCtorInitializer*)); 2740 Constructor->setCtorInitializers(baseOrMemberInitializers); 2741 } 2742 2743 return false; 2744 } 2745 2746 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2747 2748 // We need to build the initializer AST according to order of construction 2749 // and not what user specified in the Initializers list. 2750 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2751 if (!ClassDecl) 2752 return true; 2753 2754 bool HadError = false; 2755 2756 for (unsigned i = 0; i < NumInitializers; i++) { 2757 CXXCtorInitializer *Member = Initializers[i]; 2758 2759 if (Member->isBaseInitializer()) 2760 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2761 else 2762 Info.AllBaseFields[Member->getAnyMember()] = Member; 2763 } 2764 2765 // Keep track of the direct virtual bases. 2766 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2767 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2768 E = ClassDecl->bases_end(); I != E; ++I) { 2769 if (I->isVirtual()) 2770 DirectVBases.insert(I); 2771 } 2772 2773 // Push virtual bases before others. 2774 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2775 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2776 2777 if (CXXCtorInitializer *Value 2778 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2779 Info.AllToInit.push_back(Value); 2780 } else if (!AnyErrors) { 2781 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2782 CXXCtorInitializer *CXXBaseInit; 2783 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2784 VBase, IsInheritedVirtualBase, 2785 CXXBaseInit)) { 2786 HadError = true; 2787 continue; 2788 } 2789 2790 Info.AllToInit.push_back(CXXBaseInit); 2791 } 2792 } 2793 2794 // Non-virtual bases. 2795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2796 E = ClassDecl->bases_end(); Base != E; ++Base) { 2797 // Virtuals are in the virtual base list and already constructed. 2798 if (Base->isVirtual()) 2799 continue; 2800 2801 if (CXXCtorInitializer *Value 2802 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2803 Info.AllToInit.push_back(Value); 2804 } else if (!AnyErrors) { 2805 CXXCtorInitializer *CXXBaseInit; 2806 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2807 Base, /*IsInheritedVirtualBase=*/false, 2808 CXXBaseInit)) { 2809 HadError = true; 2810 continue; 2811 } 2812 2813 Info.AllToInit.push_back(CXXBaseInit); 2814 } 2815 } 2816 2817 // Fields. 2818 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 2819 MemEnd = ClassDecl->decls_end(); 2820 Mem != MemEnd; ++Mem) { 2821 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 2822 if (F->getType()->isIncompleteArrayType()) { 2823 assert(ClassDecl->hasFlexibleArrayMember() && 2824 "Incomplete array type is not valid"); 2825 continue; 2826 } 2827 2828 // If we're not generating the implicit copy/move constructor, then we'll 2829 // handle anonymous struct/union fields based on their individual 2830 // indirect fields. 2831 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 2832 continue; 2833 2834 if (CollectFieldInitializer(*this, Info, F)) 2835 HadError = true; 2836 continue; 2837 } 2838 2839 // Beyond this point, we only consider default initialization. 2840 if (Info.IIK != IIK_Default) 2841 continue; 2842 2843 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 2844 if (F->getType()->isIncompleteArrayType()) { 2845 assert(ClassDecl->hasFlexibleArrayMember() && 2846 "Incomplete array type is not valid"); 2847 continue; 2848 } 2849 2850 // Initialize each field of an anonymous struct individually. 2851 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 2852 HadError = true; 2853 2854 continue; 2855 } 2856 } 2857 2858 NumInitializers = Info.AllToInit.size(); 2859 if (NumInitializers > 0) { 2860 Constructor->setNumCtorInitializers(NumInitializers); 2861 CXXCtorInitializer **baseOrMemberInitializers = 2862 new (Context) CXXCtorInitializer*[NumInitializers]; 2863 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2864 NumInitializers * sizeof(CXXCtorInitializer*)); 2865 Constructor->setCtorInitializers(baseOrMemberInitializers); 2866 2867 // Constructors implicitly reference the base and member 2868 // destructors. 2869 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2870 Constructor->getParent()); 2871 } 2872 2873 return HadError; 2874} 2875 2876static void *GetKeyForTopLevelField(FieldDecl *Field) { 2877 // For anonymous unions, use the class declaration as the key. 2878 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 2879 if (RT->getDecl()->isAnonymousStructOrUnion()) 2880 return static_cast<void *>(RT->getDecl()); 2881 } 2882 return static_cast<void *>(Field); 2883} 2884 2885static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 2886 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 2887} 2888 2889static void *GetKeyForMember(ASTContext &Context, 2890 CXXCtorInitializer *Member) { 2891 if (!Member->isAnyMemberInitializer()) 2892 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 2893 2894 // For fields injected into the class via declaration of an anonymous union, 2895 // use its anonymous union class declaration as the unique key. 2896 FieldDecl *Field = Member->getAnyMember(); 2897 2898 // If the field is a member of an anonymous struct or union, our key 2899 // is the anonymous record decl that's a direct child of the class. 2900 RecordDecl *RD = Field->getParent(); 2901 if (RD->isAnonymousStructOrUnion()) { 2902 while (true) { 2903 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 2904 if (Parent->isAnonymousStructOrUnion()) 2905 RD = Parent; 2906 else 2907 break; 2908 } 2909 2910 return static_cast<void *>(RD); 2911 } 2912 2913 return static_cast<void *>(Field); 2914} 2915 2916static void 2917DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 2918 const CXXConstructorDecl *Constructor, 2919 CXXCtorInitializer **Inits, 2920 unsigned NumInits) { 2921 if (Constructor->getDeclContext()->isDependentContext()) 2922 return; 2923 2924 // Don't check initializers order unless the warning is enabled at the 2925 // location of at least one initializer. 2926 bool ShouldCheckOrder = false; 2927 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2928 CXXCtorInitializer *Init = Inits[InitIndex]; 2929 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2930 Init->getSourceLocation()) 2931 != DiagnosticsEngine::Ignored) { 2932 ShouldCheckOrder = true; 2933 break; 2934 } 2935 } 2936 if (!ShouldCheckOrder) 2937 return; 2938 2939 // Build the list of bases and members in the order that they'll 2940 // actually be initialized. The explicit initializers should be in 2941 // this same order but may be missing things. 2942 SmallVector<const void*, 32> IdealInitKeys; 2943 2944 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2945 2946 // 1. Virtual bases. 2947 for (CXXRecordDecl::base_class_const_iterator VBase = 2948 ClassDecl->vbases_begin(), 2949 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2950 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2951 2952 // 2. Non-virtual bases. 2953 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2954 E = ClassDecl->bases_end(); Base != E; ++Base) { 2955 if (Base->isVirtual()) 2956 continue; 2957 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2958 } 2959 2960 // 3. Direct fields. 2961 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2962 E = ClassDecl->field_end(); Field != E; ++Field) 2963 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2964 2965 unsigned NumIdealInits = IdealInitKeys.size(); 2966 unsigned IdealIndex = 0; 2967 2968 CXXCtorInitializer *PrevInit = 0; 2969 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2970 CXXCtorInitializer *Init = Inits[InitIndex]; 2971 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2972 2973 // Scan forward to try to find this initializer in the idealized 2974 // initializers list. 2975 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2976 if (InitKey == IdealInitKeys[IdealIndex]) 2977 break; 2978 2979 // If we didn't find this initializer, it must be because we 2980 // scanned past it on a previous iteration. That can only 2981 // happen if we're out of order; emit a warning. 2982 if (IdealIndex == NumIdealInits && PrevInit) { 2983 Sema::SemaDiagnosticBuilder D = 2984 SemaRef.Diag(PrevInit->getSourceLocation(), 2985 diag::warn_initializer_out_of_order); 2986 2987 if (PrevInit->isAnyMemberInitializer()) 2988 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2989 else 2990 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2991 2992 if (Init->isAnyMemberInitializer()) 2993 D << 0 << Init->getAnyMember()->getDeclName(); 2994 else 2995 D << 1 << Init->getBaseClassInfo()->getType(); 2996 2997 // Move back to the initializer's location in the ideal list. 2998 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2999 if (InitKey == IdealInitKeys[IdealIndex]) 3000 break; 3001 3002 assert(IdealIndex != NumIdealInits && 3003 "initializer not found in initializer list"); 3004 } 3005 3006 PrevInit = Init; 3007 } 3008} 3009 3010namespace { 3011bool CheckRedundantInit(Sema &S, 3012 CXXCtorInitializer *Init, 3013 CXXCtorInitializer *&PrevInit) { 3014 if (!PrevInit) { 3015 PrevInit = Init; 3016 return false; 3017 } 3018 3019 if (FieldDecl *Field = Init->getMember()) 3020 S.Diag(Init->getSourceLocation(), 3021 diag::err_multiple_mem_initialization) 3022 << Field->getDeclName() 3023 << Init->getSourceRange(); 3024 else { 3025 const Type *BaseClass = Init->getBaseClass(); 3026 assert(BaseClass && "neither field nor base"); 3027 S.Diag(Init->getSourceLocation(), 3028 diag::err_multiple_base_initialization) 3029 << QualType(BaseClass, 0) 3030 << Init->getSourceRange(); 3031 } 3032 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3033 << 0 << PrevInit->getSourceRange(); 3034 3035 return true; 3036} 3037 3038typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3039typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3040 3041bool CheckRedundantUnionInit(Sema &S, 3042 CXXCtorInitializer *Init, 3043 RedundantUnionMap &Unions) { 3044 FieldDecl *Field = Init->getAnyMember(); 3045 RecordDecl *Parent = Field->getParent(); 3046 if (!Parent->isAnonymousStructOrUnion()) 3047 return false; 3048 3049 NamedDecl *Child = Field; 3050 do { 3051 if (Parent->isUnion()) { 3052 UnionEntry &En = Unions[Parent]; 3053 if (En.first && En.first != Child) { 3054 S.Diag(Init->getSourceLocation(), 3055 diag::err_multiple_mem_union_initialization) 3056 << Field->getDeclName() 3057 << Init->getSourceRange(); 3058 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3059 << 0 << En.second->getSourceRange(); 3060 return true; 3061 } else if (!En.first) { 3062 En.first = Child; 3063 En.second = Init; 3064 } 3065 } 3066 3067 Child = Parent; 3068 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3069 } while (Parent->isAnonymousStructOrUnion()); 3070 3071 return false; 3072} 3073} 3074 3075/// ActOnMemInitializers - Handle the member initializers for a constructor. 3076void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3077 SourceLocation ColonLoc, 3078 CXXCtorInitializer **meminits, 3079 unsigned NumMemInits, 3080 bool AnyErrors) { 3081 if (!ConstructorDecl) 3082 return; 3083 3084 AdjustDeclIfTemplate(ConstructorDecl); 3085 3086 CXXConstructorDecl *Constructor 3087 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3088 3089 if (!Constructor) { 3090 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3091 return; 3092 } 3093 3094 CXXCtorInitializer **MemInits = 3095 reinterpret_cast<CXXCtorInitializer **>(meminits); 3096 3097 // Mapping for the duplicate initializers check. 3098 // For member initializers, this is keyed with a FieldDecl*. 3099 // For base initializers, this is keyed with a Type*. 3100 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3101 3102 // Mapping for the inconsistent anonymous-union initializers check. 3103 RedundantUnionMap MemberUnions; 3104 3105 bool HadError = false; 3106 for (unsigned i = 0; i < NumMemInits; i++) { 3107 CXXCtorInitializer *Init = MemInits[i]; 3108 3109 // Set the source order index. 3110 Init->setSourceOrder(i); 3111 3112 if (Init->isAnyMemberInitializer()) { 3113 FieldDecl *Field = Init->getAnyMember(); 3114 if (CheckRedundantInit(*this, Init, Members[Field]) || 3115 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3116 HadError = true; 3117 } else if (Init->isBaseInitializer()) { 3118 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3119 if (CheckRedundantInit(*this, Init, Members[Key])) 3120 HadError = true; 3121 } else { 3122 assert(Init->isDelegatingInitializer()); 3123 // This must be the only initializer 3124 if (i != 0 || NumMemInits > 1) { 3125 Diag(MemInits[0]->getSourceLocation(), 3126 diag::err_delegating_initializer_alone) 3127 << MemInits[0]->getSourceRange(); 3128 HadError = true; 3129 // We will treat this as being the only initializer. 3130 } 3131 SetDelegatingInitializer(Constructor, MemInits[i]); 3132 // Return immediately as the initializer is set. 3133 return; 3134 } 3135 } 3136 3137 if (HadError) 3138 return; 3139 3140 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3141 3142 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3143} 3144 3145void 3146Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3147 CXXRecordDecl *ClassDecl) { 3148 // Ignore dependent contexts. Also ignore unions, since their members never 3149 // have destructors implicitly called. 3150 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3151 return; 3152 3153 // FIXME: all the access-control diagnostics are positioned on the 3154 // field/base declaration. That's probably good; that said, the 3155 // user might reasonably want to know why the destructor is being 3156 // emitted, and we currently don't say. 3157 3158 // Non-static data members. 3159 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3160 E = ClassDecl->field_end(); I != E; ++I) { 3161 FieldDecl *Field = *I; 3162 if (Field->isInvalidDecl()) 3163 continue; 3164 QualType FieldType = Context.getBaseElementType(Field->getType()); 3165 3166 const RecordType* RT = FieldType->getAs<RecordType>(); 3167 if (!RT) 3168 continue; 3169 3170 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3171 if (FieldClassDecl->isInvalidDecl()) 3172 continue; 3173 if (FieldClassDecl->hasTrivialDestructor()) 3174 continue; 3175 3176 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3177 assert(Dtor && "No dtor found for FieldClassDecl!"); 3178 CheckDestructorAccess(Field->getLocation(), Dtor, 3179 PDiag(diag::err_access_dtor_field) 3180 << Field->getDeclName() 3181 << FieldType); 3182 3183 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3184 } 3185 3186 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3187 3188 // Bases. 3189 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3190 E = ClassDecl->bases_end(); Base != E; ++Base) { 3191 // Bases are always records in a well-formed non-dependent class. 3192 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3193 3194 // Remember direct virtual bases. 3195 if (Base->isVirtual()) 3196 DirectVirtualBases.insert(RT); 3197 3198 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3199 // If our base class is invalid, we probably can't get its dtor anyway. 3200 if (BaseClassDecl->isInvalidDecl()) 3201 continue; 3202 // Ignore trivial destructors. 3203 if (BaseClassDecl->hasTrivialDestructor()) 3204 continue; 3205 3206 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3207 assert(Dtor && "No dtor found for BaseClassDecl!"); 3208 3209 // FIXME: caret should be on the start of the class name 3210 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 3211 PDiag(diag::err_access_dtor_base) 3212 << Base->getType() 3213 << Base->getSourceRange()); 3214 3215 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3216 } 3217 3218 // Virtual bases. 3219 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3220 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3221 3222 // Bases are always records in a well-formed non-dependent class. 3223 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 3224 3225 // Ignore direct virtual bases. 3226 if (DirectVirtualBases.count(RT)) 3227 continue; 3228 3229 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3230 // If our base class is invalid, we probably can't get its dtor anyway. 3231 if (BaseClassDecl->isInvalidDecl()) 3232 continue; 3233 // Ignore trivial destructors. 3234 if (BaseClassDecl->hasTrivialDestructor()) 3235 continue; 3236 3237 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3238 assert(Dtor && "No dtor found for BaseClassDecl!"); 3239 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3240 PDiag(diag::err_access_dtor_vbase) 3241 << VBase->getType()); 3242 3243 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3244 } 3245} 3246 3247void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3248 if (!CDtorDecl) 3249 return; 3250 3251 if (CXXConstructorDecl *Constructor 3252 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3253 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3254} 3255 3256bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3257 unsigned DiagID, AbstractDiagSelID SelID) { 3258 if (SelID == -1) 3259 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 3260 else 3261 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 3262} 3263 3264bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3265 const PartialDiagnostic &PD) { 3266 if (!getLangOptions().CPlusPlus) 3267 return false; 3268 3269 if (const ArrayType *AT = Context.getAsArrayType(T)) 3270 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3271 3272 if (const PointerType *PT = T->getAs<PointerType>()) { 3273 // Find the innermost pointer type. 3274 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3275 PT = T; 3276 3277 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3278 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 3279 } 3280 3281 const RecordType *RT = T->getAs<RecordType>(); 3282 if (!RT) 3283 return false; 3284 3285 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3286 3287 // We can't answer whether something is abstract until it has a 3288 // definition. If it's currently being defined, we'll walk back 3289 // over all the declarations when we have a full definition. 3290 const CXXRecordDecl *Def = RD->getDefinition(); 3291 if (!Def || Def->isBeingDefined()) 3292 return false; 3293 3294 if (!RD->isAbstract()) 3295 return false; 3296 3297 Diag(Loc, PD) << RD->getDeclName(); 3298 DiagnoseAbstractType(RD); 3299 3300 return true; 3301} 3302 3303void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3304 // Check if we've already emitted the list of pure virtual functions 3305 // for this class. 3306 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3307 return; 3308 3309 CXXFinalOverriderMap FinalOverriders; 3310 RD->getFinalOverriders(FinalOverriders); 3311 3312 // Keep a set of seen pure methods so we won't diagnose the same method 3313 // more than once. 3314 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3315 3316 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3317 MEnd = FinalOverriders.end(); 3318 M != MEnd; 3319 ++M) { 3320 for (OverridingMethods::iterator SO = M->second.begin(), 3321 SOEnd = M->second.end(); 3322 SO != SOEnd; ++SO) { 3323 // C++ [class.abstract]p4: 3324 // A class is abstract if it contains or inherits at least one 3325 // pure virtual function for which the final overrider is pure 3326 // virtual. 3327 3328 // 3329 if (SO->second.size() != 1) 3330 continue; 3331 3332 if (!SO->second.front().Method->isPure()) 3333 continue; 3334 3335 if (!SeenPureMethods.insert(SO->second.front().Method)) 3336 continue; 3337 3338 Diag(SO->second.front().Method->getLocation(), 3339 diag::note_pure_virtual_function) 3340 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3341 } 3342 } 3343 3344 if (!PureVirtualClassDiagSet) 3345 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3346 PureVirtualClassDiagSet->insert(RD); 3347} 3348 3349namespace { 3350struct AbstractUsageInfo { 3351 Sema &S; 3352 CXXRecordDecl *Record; 3353 CanQualType AbstractType; 3354 bool Invalid; 3355 3356 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3357 : S(S), Record(Record), 3358 AbstractType(S.Context.getCanonicalType( 3359 S.Context.getTypeDeclType(Record))), 3360 Invalid(false) {} 3361 3362 void DiagnoseAbstractType() { 3363 if (Invalid) return; 3364 S.DiagnoseAbstractType(Record); 3365 Invalid = true; 3366 } 3367 3368 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3369}; 3370 3371struct CheckAbstractUsage { 3372 AbstractUsageInfo &Info; 3373 const NamedDecl *Ctx; 3374 3375 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3376 : Info(Info), Ctx(Ctx) {} 3377 3378 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3379 switch (TL.getTypeLocClass()) { 3380#define ABSTRACT_TYPELOC(CLASS, PARENT) 3381#define TYPELOC(CLASS, PARENT) \ 3382 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3383#include "clang/AST/TypeLocNodes.def" 3384 } 3385 } 3386 3387 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3388 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3389 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3390 if (!TL.getArg(I)) 3391 continue; 3392 3393 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3394 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3395 } 3396 } 3397 3398 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3399 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3400 } 3401 3402 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3403 // Visit the type parameters from a permissive context. 3404 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3405 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3406 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3407 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3408 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3409 // TODO: other template argument types? 3410 } 3411 } 3412 3413 // Visit pointee types from a permissive context. 3414#define CheckPolymorphic(Type) \ 3415 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3416 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3417 } 3418 CheckPolymorphic(PointerTypeLoc) 3419 CheckPolymorphic(ReferenceTypeLoc) 3420 CheckPolymorphic(MemberPointerTypeLoc) 3421 CheckPolymorphic(BlockPointerTypeLoc) 3422 CheckPolymorphic(AtomicTypeLoc) 3423 3424 /// Handle all the types we haven't given a more specific 3425 /// implementation for above. 3426 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3427 // Every other kind of type that we haven't called out already 3428 // that has an inner type is either (1) sugar or (2) contains that 3429 // inner type in some way as a subobject. 3430 if (TypeLoc Next = TL.getNextTypeLoc()) 3431 return Visit(Next, Sel); 3432 3433 // If there's no inner type and we're in a permissive context, 3434 // don't diagnose. 3435 if (Sel == Sema::AbstractNone) return; 3436 3437 // Check whether the type matches the abstract type. 3438 QualType T = TL.getType(); 3439 if (T->isArrayType()) { 3440 Sel = Sema::AbstractArrayType; 3441 T = Info.S.Context.getBaseElementType(T); 3442 } 3443 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3444 if (CT != Info.AbstractType) return; 3445 3446 // It matched; do some magic. 3447 if (Sel == Sema::AbstractArrayType) { 3448 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3449 << T << TL.getSourceRange(); 3450 } else { 3451 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3452 << Sel << T << TL.getSourceRange(); 3453 } 3454 Info.DiagnoseAbstractType(); 3455 } 3456}; 3457 3458void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3459 Sema::AbstractDiagSelID Sel) { 3460 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3461} 3462 3463} 3464 3465/// Check for invalid uses of an abstract type in a method declaration. 3466static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3467 CXXMethodDecl *MD) { 3468 // No need to do the check on definitions, which require that 3469 // the return/param types be complete. 3470 if (MD->doesThisDeclarationHaveABody()) 3471 return; 3472 3473 // For safety's sake, just ignore it if we don't have type source 3474 // information. This should never happen for non-implicit methods, 3475 // but... 3476 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3477 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3478} 3479 3480/// Check for invalid uses of an abstract type within a class definition. 3481static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3482 CXXRecordDecl *RD) { 3483 for (CXXRecordDecl::decl_iterator 3484 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3485 Decl *D = *I; 3486 if (D->isImplicit()) continue; 3487 3488 // Methods and method templates. 3489 if (isa<CXXMethodDecl>(D)) { 3490 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3491 } else if (isa<FunctionTemplateDecl>(D)) { 3492 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3493 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3494 3495 // Fields and static variables. 3496 } else if (isa<FieldDecl>(D)) { 3497 FieldDecl *FD = cast<FieldDecl>(D); 3498 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3499 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3500 } else if (isa<VarDecl>(D)) { 3501 VarDecl *VD = cast<VarDecl>(D); 3502 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3503 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3504 3505 // Nested classes and class templates. 3506 } else if (isa<CXXRecordDecl>(D)) { 3507 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3508 } else if (isa<ClassTemplateDecl>(D)) { 3509 CheckAbstractClassUsage(Info, 3510 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3511 } 3512 } 3513} 3514 3515/// \brief Perform semantic checks on a class definition that has been 3516/// completing, introducing implicitly-declared members, checking for 3517/// abstract types, etc. 3518void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3519 if (!Record) 3520 return; 3521 3522 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3523 AbstractUsageInfo Info(*this, Record); 3524 CheckAbstractClassUsage(Info, Record); 3525 } 3526 3527 // If this is not an aggregate type and has no user-declared constructor, 3528 // complain about any non-static data members of reference or const scalar 3529 // type, since they will never get initializers. 3530 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3531 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 3532 bool Complained = false; 3533 for (RecordDecl::field_iterator F = Record->field_begin(), 3534 FEnd = Record->field_end(); 3535 F != FEnd; ++F) { 3536 if (F->hasInClassInitializer()) 3537 continue; 3538 3539 if (F->getType()->isReferenceType() || 3540 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3541 if (!Complained) { 3542 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3543 << Record->getTagKind() << Record; 3544 Complained = true; 3545 } 3546 3547 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3548 << F->getType()->isReferenceType() 3549 << F->getDeclName(); 3550 } 3551 } 3552 } 3553 3554 if (Record->isDynamicClass() && !Record->isDependentType()) 3555 DynamicClasses.push_back(Record); 3556 3557 if (Record->getIdentifier()) { 3558 // C++ [class.mem]p13: 3559 // If T is the name of a class, then each of the following shall have a 3560 // name different from T: 3561 // - every member of every anonymous union that is a member of class T. 3562 // 3563 // C++ [class.mem]p14: 3564 // In addition, if class T has a user-declared constructor (12.1), every 3565 // non-static data member of class T shall have a name different from T. 3566 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3567 R.first != R.second; ++R.first) { 3568 NamedDecl *D = *R.first; 3569 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3570 isa<IndirectFieldDecl>(D)) { 3571 Diag(D->getLocation(), diag::err_member_name_of_class) 3572 << D->getDeclName(); 3573 break; 3574 } 3575 } 3576 } 3577 3578 // Warn if the class has virtual methods but non-virtual public destructor. 3579 if (Record->isPolymorphic() && !Record->isDependentType()) { 3580 CXXDestructorDecl *dtor = Record->getDestructor(); 3581 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3582 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3583 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3584 } 3585 3586 // See if a method overloads virtual methods in a base 3587 /// class without overriding any. 3588 if (!Record->isDependentType()) { 3589 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3590 MEnd = Record->method_end(); 3591 M != MEnd; ++M) { 3592 if (!(*M)->isStatic()) 3593 DiagnoseHiddenVirtualMethods(Record, *M); 3594 } 3595 } 3596 3597 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3598 // function that is not a constructor declares that member function to be 3599 // const. [...] The class of which that function is a member shall be 3600 // a literal type. 3601 // 3602 // It's fine to diagnose constructors here too: such constructors cannot 3603 // produce a constant expression, so are ill-formed (no diagnostic required). 3604 // 3605 // If the class has virtual bases, any constexpr members will already have 3606 // been diagnosed by the checks performed on the member declaration, so 3607 // suppress this (less useful) diagnostic. 3608 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3609 !Record->isLiteral() && !Record->getNumVBases()) { 3610 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3611 MEnd = Record->method_end(); 3612 M != MEnd; ++M) { 3613 if ((*M)->isConstexpr()) { 3614 switch (Record->getTemplateSpecializationKind()) { 3615 case TSK_ImplicitInstantiation: 3616 case TSK_ExplicitInstantiationDeclaration: 3617 case TSK_ExplicitInstantiationDefinition: 3618 // If a template instantiates to a non-literal type, but its members 3619 // instantiate to constexpr functions, the template is technically 3620 // ill-formed, but we allow it for sanity. Such members are treated as 3621 // non-constexpr. 3622 (*M)->setConstexpr(false); 3623 continue; 3624 3625 case TSK_Undeclared: 3626 case TSK_ExplicitSpecialization: 3627 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record), 3628 PDiag(diag::err_constexpr_method_non_literal)); 3629 break; 3630 } 3631 3632 // Only produce one error per class. 3633 break; 3634 } 3635 } 3636 } 3637 3638 // Declare inherited constructors. We do this eagerly here because: 3639 // - The standard requires an eager diagnostic for conflicting inherited 3640 // constructors from different classes. 3641 // - The lazy declaration of the other implicit constructors is so as to not 3642 // waste space and performance on classes that are not meant to be 3643 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3644 // have inherited constructors. 3645 DeclareInheritedConstructors(Record); 3646 3647 if (!Record->isDependentType()) 3648 CheckExplicitlyDefaultedMethods(Record); 3649} 3650 3651void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3652 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3653 ME = Record->method_end(); 3654 MI != ME; ++MI) { 3655 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) { 3656 switch (getSpecialMember(*MI)) { 3657 case CXXDefaultConstructor: 3658 CheckExplicitlyDefaultedDefaultConstructor( 3659 cast<CXXConstructorDecl>(*MI)); 3660 break; 3661 3662 case CXXDestructor: 3663 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI)); 3664 break; 3665 3666 case CXXCopyConstructor: 3667 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI)); 3668 break; 3669 3670 case CXXCopyAssignment: 3671 CheckExplicitlyDefaultedCopyAssignment(*MI); 3672 break; 3673 3674 case CXXMoveConstructor: 3675 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI)); 3676 break; 3677 3678 case CXXMoveAssignment: 3679 CheckExplicitlyDefaultedMoveAssignment(*MI); 3680 break; 3681 3682 case CXXInvalid: 3683 llvm_unreachable("non-special member explicitly defaulted!"); 3684 } 3685 } 3686 } 3687 3688} 3689 3690void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) { 3691 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor()); 3692 3693 // Whether this was the first-declared instance of the constructor. 3694 // This affects whether we implicitly add an exception spec (and, eventually, 3695 // constexpr). It is also ill-formed to explicitly default a constructor such 3696 // that it would be deleted. (C++0x [decl.fct.def.default]) 3697 bool First = CD == CD->getCanonicalDecl(); 3698 3699 bool HadError = false; 3700 if (CD->getNumParams() != 0) { 3701 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params) 3702 << CD->getSourceRange(); 3703 HadError = true; 3704 } 3705 3706 ImplicitExceptionSpecification Spec 3707 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent()); 3708 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3709 if (EPI.ExceptionSpecType == EST_Delayed) { 3710 // Exception specification depends on some deferred part of the class. We'll 3711 // try again when the class's definition has been fully processed. 3712 return; 3713 } 3714 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3715 *ExceptionType = Context.getFunctionType( 3716 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3717 3718 if (CtorType->hasExceptionSpec()) { 3719 if (CheckEquivalentExceptionSpec( 3720 PDiag(diag::err_incorrect_defaulted_exception_spec) 3721 << CXXDefaultConstructor, 3722 PDiag(), 3723 ExceptionType, SourceLocation(), 3724 CtorType, CD->getLocation())) { 3725 HadError = true; 3726 } 3727 } else if (First) { 3728 // We set the declaration to have the computed exception spec here. 3729 // We know there are no parameters. 3730 EPI.ExtInfo = CtorType->getExtInfo(); 3731 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 3732 } 3733 3734 if (HadError) { 3735 CD->setInvalidDecl(); 3736 return; 3737 } 3738 3739 if (ShouldDeleteDefaultConstructor(CD)) { 3740 if (First) { 3741 CD->setDeletedAsWritten(); 3742 } else { 3743 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3744 << CXXDefaultConstructor; 3745 CD->setInvalidDecl(); 3746 } 3747 } 3748} 3749 3750void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) { 3751 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor()); 3752 3753 // Whether this was the first-declared instance of the constructor. 3754 bool First = CD == CD->getCanonicalDecl(); 3755 3756 bool HadError = false; 3757 if (CD->getNumParams() != 1) { 3758 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params) 3759 << CD->getSourceRange(); 3760 HadError = true; 3761 } 3762 3763 ImplicitExceptionSpecification Spec(Context); 3764 bool Const; 3765 llvm::tie(Spec, Const) = 3766 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent()); 3767 3768 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3769 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3770 *ExceptionType = Context.getFunctionType( 3771 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3772 3773 // Check for parameter type matching. 3774 // This is a copy ctor so we know it's a cv-qualified reference to T. 3775 QualType ArgType = CtorType->getArgType(0); 3776 if (ArgType->getPointeeType().isVolatileQualified()) { 3777 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param); 3778 HadError = true; 3779 } 3780 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3781 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param); 3782 HadError = true; 3783 } 3784 3785 if (CtorType->hasExceptionSpec()) { 3786 if (CheckEquivalentExceptionSpec( 3787 PDiag(diag::err_incorrect_defaulted_exception_spec) 3788 << CXXCopyConstructor, 3789 PDiag(), 3790 ExceptionType, SourceLocation(), 3791 CtorType, CD->getLocation())) { 3792 HadError = true; 3793 } 3794 } else if (First) { 3795 // We set the declaration to have the computed exception spec here. 3796 // We duplicate the one parameter type. 3797 EPI.ExtInfo = CtorType->getExtInfo(); 3798 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3799 } 3800 3801 if (HadError) { 3802 CD->setInvalidDecl(); 3803 return; 3804 } 3805 3806 if (ShouldDeleteCopyConstructor(CD)) { 3807 if (First) { 3808 CD->setDeletedAsWritten(); 3809 } else { 3810 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3811 << CXXCopyConstructor; 3812 CD->setInvalidDecl(); 3813 } 3814 } 3815} 3816 3817void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) { 3818 assert(MD->isExplicitlyDefaulted()); 3819 3820 // Whether this was the first-declared instance of the operator 3821 bool First = MD == MD->getCanonicalDecl(); 3822 3823 bool HadError = false; 3824 if (MD->getNumParams() != 1) { 3825 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params) 3826 << MD->getSourceRange(); 3827 HadError = true; 3828 } 3829 3830 QualType ReturnType = 3831 MD->getType()->getAs<FunctionType>()->getResultType(); 3832 if (!ReturnType->isLValueReferenceType() || 3833 !Context.hasSameType( 3834 Context.getCanonicalType(ReturnType->getPointeeType()), 3835 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 3836 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type); 3837 HadError = true; 3838 } 3839 3840 ImplicitExceptionSpecification Spec(Context); 3841 bool Const; 3842 llvm::tie(Spec, Const) = 3843 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent()); 3844 3845 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3846 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 3847 *ExceptionType = Context.getFunctionType( 3848 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3849 3850 QualType ArgType = OperType->getArgType(0); 3851 if (!ArgType->isLValueReferenceType()) { 3852 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 3853 HadError = true; 3854 } else { 3855 if (ArgType->getPointeeType().isVolatileQualified()) { 3856 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param); 3857 HadError = true; 3858 } 3859 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3860 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param); 3861 HadError = true; 3862 } 3863 } 3864 3865 if (OperType->getTypeQuals()) { 3866 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals); 3867 HadError = true; 3868 } 3869 3870 if (OperType->hasExceptionSpec()) { 3871 if (CheckEquivalentExceptionSpec( 3872 PDiag(diag::err_incorrect_defaulted_exception_spec) 3873 << CXXCopyAssignment, 3874 PDiag(), 3875 ExceptionType, SourceLocation(), 3876 OperType, MD->getLocation())) { 3877 HadError = true; 3878 } 3879 } else if (First) { 3880 // We set the declaration to have the computed exception spec here. 3881 // We duplicate the one parameter type. 3882 EPI.RefQualifier = OperType->getRefQualifier(); 3883 EPI.ExtInfo = OperType->getExtInfo(); 3884 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 3885 } 3886 3887 if (HadError) { 3888 MD->setInvalidDecl(); 3889 return; 3890 } 3891 3892 if (ShouldDeleteCopyAssignmentOperator(MD)) { 3893 if (First) { 3894 MD->setDeletedAsWritten(); 3895 } else { 3896 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 3897 << CXXCopyAssignment; 3898 MD->setInvalidDecl(); 3899 } 3900 } 3901} 3902 3903void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) { 3904 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor()); 3905 3906 // Whether this was the first-declared instance of the constructor. 3907 bool First = CD == CD->getCanonicalDecl(); 3908 3909 bool HadError = false; 3910 if (CD->getNumParams() != 1) { 3911 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params) 3912 << CD->getSourceRange(); 3913 HadError = true; 3914 } 3915 3916 ImplicitExceptionSpecification Spec( 3917 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent())); 3918 3919 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3920 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3921 *ExceptionType = Context.getFunctionType( 3922 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3923 3924 // Check for parameter type matching. 3925 // This is a move ctor so we know it's a cv-qualified rvalue reference to T. 3926 QualType ArgType = CtorType->getArgType(0); 3927 if (ArgType->getPointeeType().isVolatileQualified()) { 3928 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param); 3929 HadError = true; 3930 } 3931 if (ArgType->getPointeeType().isConstQualified()) { 3932 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param); 3933 HadError = true; 3934 } 3935 3936 if (CtorType->hasExceptionSpec()) { 3937 if (CheckEquivalentExceptionSpec( 3938 PDiag(diag::err_incorrect_defaulted_exception_spec) 3939 << CXXMoveConstructor, 3940 PDiag(), 3941 ExceptionType, SourceLocation(), 3942 CtorType, CD->getLocation())) { 3943 HadError = true; 3944 } 3945 } else if (First) { 3946 // We set the declaration to have the computed exception spec here. 3947 // We duplicate the one parameter type. 3948 EPI.ExtInfo = CtorType->getExtInfo(); 3949 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3950 } 3951 3952 if (HadError) { 3953 CD->setInvalidDecl(); 3954 return; 3955 } 3956 3957 if (ShouldDeleteMoveConstructor(CD)) { 3958 if (First) { 3959 CD->setDeletedAsWritten(); 3960 } else { 3961 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3962 << CXXMoveConstructor; 3963 CD->setInvalidDecl(); 3964 } 3965 } 3966} 3967 3968void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) { 3969 assert(MD->isExplicitlyDefaulted()); 3970 3971 // Whether this was the first-declared instance of the operator 3972 bool First = MD == MD->getCanonicalDecl(); 3973 3974 bool HadError = false; 3975 if (MD->getNumParams() != 1) { 3976 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params) 3977 << MD->getSourceRange(); 3978 HadError = true; 3979 } 3980 3981 QualType ReturnType = 3982 MD->getType()->getAs<FunctionType>()->getResultType(); 3983 if (!ReturnType->isLValueReferenceType() || 3984 !Context.hasSameType( 3985 Context.getCanonicalType(ReturnType->getPointeeType()), 3986 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 3987 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type); 3988 HadError = true; 3989 } 3990 3991 ImplicitExceptionSpecification Spec( 3992 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent())); 3993 3994 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3995 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 3996 *ExceptionType = Context.getFunctionType( 3997 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3998 3999 QualType ArgType = OperType->getArgType(0); 4000 if (!ArgType->isRValueReferenceType()) { 4001 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref); 4002 HadError = true; 4003 } else { 4004 if (ArgType->getPointeeType().isVolatileQualified()) { 4005 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param); 4006 HadError = true; 4007 } 4008 if (ArgType->getPointeeType().isConstQualified()) { 4009 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param); 4010 HadError = true; 4011 } 4012 } 4013 4014 if (OperType->getTypeQuals()) { 4015 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals); 4016 HadError = true; 4017 } 4018 4019 if (OperType->hasExceptionSpec()) { 4020 if (CheckEquivalentExceptionSpec( 4021 PDiag(diag::err_incorrect_defaulted_exception_spec) 4022 << CXXMoveAssignment, 4023 PDiag(), 4024 ExceptionType, SourceLocation(), 4025 OperType, MD->getLocation())) { 4026 HadError = true; 4027 } 4028 } else if (First) { 4029 // We set the declaration to have the computed exception spec here. 4030 // We duplicate the one parameter type. 4031 EPI.RefQualifier = OperType->getRefQualifier(); 4032 EPI.ExtInfo = OperType->getExtInfo(); 4033 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 4034 } 4035 4036 if (HadError) { 4037 MD->setInvalidDecl(); 4038 return; 4039 } 4040 4041 if (ShouldDeleteMoveAssignmentOperator(MD)) { 4042 if (First) { 4043 MD->setDeletedAsWritten(); 4044 } else { 4045 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 4046 << CXXMoveAssignment; 4047 MD->setInvalidDecl(); 4048 } 4049 } 4050} 4051 4052void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) { 4053 assert(DD->isExplicitlyDefaulted()); 4054 4055 // Whether this was the first-declared instance of the destructor. 4056 bool First = DD == DD->getCanonicalDecl(); 4057 4058 ImplicitExceptionSpecification Spec 4059 = ComputeDefaultedDtorExceptionSpec(DD->getParent()); 4060 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 4061 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(), 4062 *ExceptionType = Context.getFunctionType( 4063 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 4064 4065 if (DtorType->hasExceptionSpec()) { 4066 if (CheckEquivalentExceptionSpec( 4067 PDiag(diag::err_incorrect_defaulted_exception_spec) 4068 << CXXDestructor, 4069 PDiag(), 4070 ExceptionType, SourceLocation(), 4071 DtorType, DD->getLocation())) { 4072 DD->setInvalidDecl(); 4073 return; 4074 } 4075 } else if (First) { 4076 // We set the declaration to have the computed exception spec here. 4077 // There are no parameters. 4078 EPI.ExtInfo = DtorType->getExtInfo(); 4079 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 4080 } 4081 4082 if (ShouldDeleteDestructor(DD)) { 4083 if (First) { 4084 DD->setDeletedAsWritten(); 4085 } else { 4086 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes) 4087 << CXXDestructor; 4088 DD->setInvalidDecl(); 4089 } 4090 } 4091} 4092 4093bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) { 4094 CXXRecordDecl *RD = CD->getParent(); 4095 assert(!RD->isDependentType() && "do deletion after instantiation"); 4096 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4097 return false; 4098 4099 SourceLocation Loc = CD->getLocation(); 4100 4101 // Do access control from the constructor 4102 ContextRAII CtorContext(*this, CD); 4103 4104 bool Union = RD->isUnion(); 4105 bool AllConst = true; 4106 4107 // We do this because we should never actually use an anonymous 4108 // union's constructor. 4109 if (Union && RD->isAnonymousStructOrUnion()) 4110 return false; 4111 4112 // FIXME: We should put some diagnostic logic right into this function. 4113 4114 // C++0x [class.ctor]/5 4115 // A defaulted default constructor for class X is defined as deleted if: 4116 4117 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4118 BE = RD->bases_end(); 4119 BI != BE; ++BI) { 4120 // We'll handle this one later 4121 if (BI->isVirtual()) 4122 continue; 4123 4124 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4125 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4126 4127 // -- any [direct base class] has a type with a destructor that is 4128 // deleted or inaccessible from the defaulted default constructor 4129 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4130 if (BaseDtor->isDeleted()) 4131 return true; 4132 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4133 AR_accessible) 4134 return true; 4135 4136 // -- any [direct base class either] has no default constructor or 4137 // overload resolution as applied to [its] default constructor 4138 // results in an ambiguity or in a function that is deleted or 4139 // inaccessible from the defaulted default constructor 4140 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl); 4141 if (!BaseDefault || BaseDefault->isDeleted()) 4142 return true; 4143 4144 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(), 4145 PDiag()) != AR_accessible) 4146 return true; 4147 } 4148 4149 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4150 BE = RD->vbases_end(); 4151 BI != BE; ++BI) { 4152 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4153 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4154 4155 // -- any [virtual base class] has a type with a destructor that is 4156 // delete or inaccessible from the defaulted default constructor 4157 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4158 if (BaseDtor->isDeleted()) 4159 return true; 4160 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4161 AR_accessible) 4162 return true; 4163 4164 // -- any [virtual base class either] has no default constructor or 4165 // overload resolution as applied to [its] default constructor 4166 // results in an ambiguity or in a function that is deleted or 4167 // inaccessible from the defaulted default constructor 4168 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl); 4169 if (!BaseDefault || BaseDefault->isDeleted()) 4170 return true; 4171 4172 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(), 4173 PDiag()) != AR_accessible) 4174 return true; 4175 } 4176 4177 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4178 FE = RD->field_end(); 4179 FI != FE; ++FI) { 4180 if (FI->isInvalidDecl()) 4181 continue; 4182 4183 QualType FieldType = Context.getBaseElementType(FI->getType()); 4184 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4185 4186 // -- any non-static data member with no brace-or-equal-initializer is of 4187 // reference type 4188 if (FieldType->isReferenceType() && !FI->hasInClassInitializer()) 4189 return true; 4190 4191 // -- X is a union and all its variant members are of const-qualified type 4192 // (or array thereof) 4193 if (Union && !FieldType.isConstQualified()) 4194 AllConst = false; 4195 4196 if (FieldRecord) { 4197 // -- X is a union-like class that has a variant member with a non-trivial 4198 // default constructor 4199 if (Union && !FieldRecord->hasTrivialDefaultConstructor()) 4200 return true; 4201 4202 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4203 if (FieldDtor->isDeleted()) 4204 return true; 4205 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4206 AR_accessible) 4207 return true; 4208 4209 // -- any non-variant non-static data member of const-qualified type (or 4210 // array thereof) with no brace-or-equal-initializer does not have a 4211 // user-provided default constructor 4212 if (FieldType.isConstQualified() && 4213 !FI->hasInClassInitializer() && 4214 !FieldRecord->hasUserProvidedDefaultConstructor()) 4215 return true; 4216 4217 if (!Union && FieldRecord->isUnion() && 4218 FieldRecord->isAnonymousStructOrUnion()) { 4219 // We're okay to reuse AllConst here since we only care about the 4220 // value otherwise if we're in a union. 4221 AllConst = true; 4222 4223 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4224 UE = FieldRecord->field_end(); 4225 UI != UE; ++UI) { 4226 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4227 CXXRecordDecl *UnionFieldRecord = 4228 UnionFieldType->getAsCXXRecordDecl(); 4229 4230 if (!UnionFieldType.isConstQualified()) 4231 AllConst = false; 4232 4233 if (UnionFieldRecord && 4234 !UnionFieldRecord->hasTrivialDefaultConstructor()) 4235 return true; 4236 } 4237 4238 if (AllConst) 4239 return true; 4240 4241 // Don't try to initialize the anonymous union 4242 // This is technically non-conformant, but sanity demands it. 4243 continue; 4244 } 4245 4246 // -- any non-static data member with no brace-or-equal-initializer has 4247 // class type M (or array thereof) and either M has no default 4248 // constructor or overload resolution as applied to M's default 4249 // constructor results in an ambiguity or in a function that is deleted 4250 // or inaccessible from the defaulted default constructor. 4251 if (!FI->hasInClassInitializer()) { 4252 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord); 4253 if (!FieldDefault || FieldDefault->isDeleted()) 4254 return true; 4255 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(), 4256 PDiag()) != AR_accessible) 4257 return true; 4258 } 4259 } else if (!Union && FieldType.isConstQualified() && 4260 !FI->hasInClassInitializer()) { 4261 // -- any non-variant non-static data member of const-qualified type (or 4262 // array thereof) with no brace-or-equal-initializer does not have a 4263 // user-provided default constructor 4264 return true; 4265 } 4266 } 4267 4268 if (Union && AllConst) 4269 return true; 4270 4271 return false; 4272} 4273 4274bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) { 4275 CXXRecordDecl *RD = CD->getParent(); 4276 assert(!RD->isDependentType() && "do deletion after instantiation"); 4277 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4278 return false; 4279 4280 SourceLocation Loc = CD->getLocation(); 4281 4282 // Do access control from the constructor 4283 ContextRAII CtorContext(*this, CD); 4284 4285 bool Union = RD->isUnion(); 4286 4287 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() && 4288 "copy assignment arg has no pointee type"); 4289 unsigned ArgQuals = 4290 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 4291 Qualifiers::Const : 0; 4292 4293 // We do this because we should never actually use an anonymous 4294 // union's constructor. 4295 if (Union && RD->isAnonymousStructOrUnion()) 4296 return false; 4297 4298 // FIXME: We should put some diagnostic logic right into this function. 4299 4300 // C++0x [class.copy]/11 4301 // A defaulted [copy] constructor for class X is defined as delete if X has: 4302 4303 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4304 BE = RD->bases_end(); 4305 BI != BE; ++BI) { 4306 // We'll handle this one later 4307 if (BI->isVirtual()) 4308 continue; 4309 4310 QualType BaseType = BI->getType(); 4311 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4312 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4313 4314 // -- any [direct base class] of a type with a destructor that is deleted or 4315 // inaccessible from the defaulted constructor 4316 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4317 if (BaseDtor->isDeleted()) 4318 return true; 4319 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4320 AR_accessible) 4321 return true; 4322 4323 // -- a [direct base class] B that cannot be [copied] because overload 4324 // resolution, as applied to B's [copy] constructor, results in an 4325 // ambiguity or a function that is deleted or inaccessible from the 4326 // defaulted constructor 4327 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals); 4328 if (!BaseCtor || BaseCtor->isDeleted()) 4329 return true; 4330 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4331 AR_accessible) 4332 return true; 4333 } 4334 4335 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4336 BE = RD->vbases_end(); 4337 BI != BE; ++BI) { 4338 QualType BaseType = BI->getType(); 4339 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4340 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4341 4342 // -- any [virtual base class] of a type with a destructor that is deleted or 4343 // inaccessible from the defaulted constructor 4344 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4345 if (BaseDtor->isDeleted()) 4346 return true; 4347 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4348 AR_accessible) 4349 return true; 4350 4351 // -- a [virtual base class] B that cannot be [copied] because overload 4352 // resolution, as applied to B's [copy] constructor, results in an 4353 // ambiguity or a function that is deleted or inaccessible from the 4354 // defaulted constructor 4355 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals); 4356 if (!BaseCtor || BaseCtor->isDeleted()) 4357 return true; 4358 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4359 AR_accessible) 4360 return true; 4361 } 4362 4363 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4364 FE = RD->field_end(); 4365 FI != FE; ++FI) { 4366 QualType FieldType = Context.getBaseElementType(FI->getType()); 4367 4368 // -- for a copy constructor, a non-static data member of rvalue reference 4369 // type 4370 if (FieldType->isRValueReferenceType()) 4371 return true; 4372 4373 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4374 4375 if (FieldRecord) { 4376 // This is an anonymous union 4377 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4378 // Anonymous unions inside unions do not variant members create 4379 if (!Union) { 4380 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4381 UE = FieldRecord->field_end(); 4382 UI != UE; ++UI) { 4383 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4384 CXXRecordDecl *UnionFieldRecord = 4385 UnionFieldType->getAsCXXRecordDecl(); 4386 4387 // -- a variant member with a non-trivial [copy] constructor and X 4388 // is a union-like class 4389 if (UnionFieldRecord && 4390 !UnionFieldRecord->hasTrivialCopyConstructor()) 4391 return true; 4392 } 4393 } 4394 4395 // Don't try to initalize an anonymous union 4396 continue; 4397 } else { 4398 // -- a variant member with a non-trivial [copy] constructor and X is a 4399 // union-like class 4400 if (Union && !FieldRecord->hasTrivialCopyConstructor()) 4401 return true; 4402 4403 // -- any [non-static data member] of a type with a destructor that is 4404 // deleted or inaccessible from the defaulted constructor 4405 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4406 if (FieldDtor->isDeleted()) 4407 return true; 4408 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4409 AR_accessible) 4410 return true; 4411 } 4412 4413 // -- a [non-static data member of class type (or array thereof)] B that 4414 // cannot be [copied] because overload resolution, as applied to B's 4415 // [copy] constructor, results in an ambiguity or a function that is 4416 // deleted or inaccessible from the defaulted constructor 4417 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord, 4418 ArgQuals); 4419 if (!FieldCtor || FieldCtor->isDeleted()) 4420 return true; 4421 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4422 PDiag()) != AR_accessible) 4423 return true; 4424 } 4425 } 4426 4427 return false; 4428} 4429 4430bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) { 4431 CXXRecordDecl *RD = MD->getParent(); 4432 assert(!RD->isDependentType() && "do deletion after instantiation"); 4433 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4434 return false; 4435 4436 SourceLocation Loc = MD->getLocation(); 4437 4438 // Do access control from the constructor 4439 ContextRAII MethodContext(*this, MD); 4440 4441 bool Union = RD->isUnion(); 4442 4443 unsigned ArgQuals = 4444 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 4445 Qualifiers::Const : 0; 4446 4447 // We do this because we should never actually use an anonymous 4448 // union's constructor. 4449 if (Union && RD->isAnonymousStructOrUnion()) 4450 return false; 4451 4452 // FIXME: We should put some diagnostic logic right into this function. 4453 4454 // C++0x [class.copy]/20 4455 // A defaulted [copy] assignment operator for class X is defined as deleted 4456 // if X has: 4457 4458 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4459 BE = RD->bases_end(); 4460 BI != BE; ++BI) { 4461 // We'll handle this one later 4462 if (BI->isVirtual()) 4463 continue; 4464 4465 QualType BaseType = BI->getType(); 4466 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4467 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4468 4469 // -- a [direct base class] B that cannot be [copied] because overload 4470 // resolution, as applied to B's [copy] assignment operator, results in 4471 // an ambiguity or a function that is deleted or inaccessible from the 4472 // assignment operator 4473 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4474 0); 4475 if (!CopyOper || CopyOper->isDeleted()) 4476 return true; 4477 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4478 return true; 4479 } 4480 4481 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4482 BE = RD->vbases_end(); 4483 BI != BE; ++BI) { 4484 QualType BaseType = BI->getType(); 4485 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4486 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4487 4488 // -- a [virtual base class] B that cannot be [copied] because overload 4489 // resolution, as applied to B's [copy] assignment operator, results in 4490 // an ambiguity or a function that is deleted or inaccessible from the 4491 // assignment operator 4492 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4493 0); 4494 if (!CopyOper || CopyOper->isDeleted()) 4495 return true; 4496 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4497 return true; 4498 } 4499 4500 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4501 FE = RD->field_end(); 4502 FI != FE; ++FI) { 4503 QualType FieldType = Context.getBaseElementType(FI->getType()); 4504 4505 // -- a non-static data member of reference type 4506 if (FieldType->isReferenceType()) 4507 return true; 4508 4509 // -- a non-static data member of const non-class type (or array thereof) 4510 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4511 return true; 4512 4513 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4514 4515 if (FieldRecord) { 4516 // This is an anonymous union 4517 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4518 // Anonymous unions inside unions do not variant members create 4519 if (!Union) { 4520 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4521 UE = FieldRecord->field_end(); 4522 UI != UE; ++UI) { 4523 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4524 CXXRecordDecl *UnionFieldRecord = 4525 UnionFieldType->getAsCXXRecordDecl(); 4526 4527 // -- a variant member with a non-trivial [copy] assignment operator 4528 // and X is a union-like class 4529 if (UnionFieldRecord && 4530 !UnionFieldRecord->hasTrivialCopyAssignment()) 4531 return true; 4532 } 4533 } 4534 4535 // Don't try to initalize an anonymous union 4536 continue; 4537 // -- a variant member with a non-trivial [copy] assignment operator 4538 // and X is a union-like class 4539 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) { 4540 return true; 4541 } 4542 4543 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals, 4544 false, 0); 4545 if (!CopyOper || CopyOper->isDeleted()) 4546 return true; 4547 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4548 return true; 4549 } 4550 } 4551 4552 return false; 4553} 4554 4555bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) { 4556 CXXRecordDecl *RD = CD->getParent(); 4557 assert(!RD->isDependentType() && "do deletion after instantiation"); 4558 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4559 return false; 4560 4561 SourceLocation Loc = CD->getLocation(); 4562 4563 // Do access control from the constructor 4564 ContextRAII CtorContext(*this, CD); 4565 4566 bool Union = RD->isUnion(); 4567 4568 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() && 4569 "copy assignment arg has no pointee type"); 4570 4571 // We do this because we should never actually use an anonymous 4572 // union's constructor. 4573 if (Union && RD->isAnonymousStructOrUnion()) 4574 return false; 4575 4576 // C++0x [class.copy]/11 4577 // A defaulted [move] constructor for class X is defined as deleted 4578 // if X has: 4579 4580 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4581 BE = RD->bases_end(); 4582 BI != BE; ++BI) { 4583 // We'll handle this one later 4584 if (BI->isVirtual()) 4585 continue; 4586 4587 QualType BaseType = BI->getType(); 4588 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4589 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4590 4591 // -- any [direct base class] of a type with a destructor that is deleted or 4592 // inaccessible from the defaulted constructor 4593 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4594 if (BaseDtor->isDeleted()) 4595 return true; 4596 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4597 AR_accessible) 4598 return true; 4599 4600 // -- a [direct base class] B that cannot be [moved] because overload 4601 // resolution, as applied to B's [move] constructor, results in an 4602 // ambiguity or a function that is deleted or inaccessible from the 4603 // defaulted constructor 4604 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl); 4605 if (!BaseCtor || BaseCtor->isDeleted()) 4606 return true; 4607 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4608 AR_accessible) 4609 return true; 4610 4611 // -- for a move constructor, a [direct base class] with a type that 4612 // does not have a move constructor and is not trivially copyable. 4613 // If the field isn't a record, it's always trivially copyable. 4614 // A moving constructor could be a copy constructor instead. 4615 if (!BaseCtor->isMoveConstructor() && 4616 !BaseDecl->isTriviallyCopyable()) 4617 return true; 4618 } 4619 4620 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4621 BE = RD->vbases_end(); 4622 BI != BE; ++BI) { 4623 QualType BaseType = BI->getType(); 4624 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4625 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4626 4627 // -- any [virtual base class] of a type with a destructor that is deleted 4628 // or inaccessible from the defaulted constructor 4629 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4630 if (BaseDtor->isDeleted()) 4631 return true; 4632 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4633 AR_accessible) 4634 return true; 4635 4636 // -- a [virtual base class] B that cannot be [moved] because overload 4637 // resolution, as applied to B's [move] constructor, results in an 4638 // ambiguity or a function that is deleted or inaccessible from the 4639 // defaulted constructor 4640 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl); 4641 if (!BaseCtor || BaseCtor->isDeleted()) 4642 return true; 4643 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4644 AR_accessible) 4645 return true; 4646 4647 // -- for a move constructor, a [virtual base class] with a type that 4648 // does not have a move constructor and is not trivially copyable. 4649 // If the field isn't a record, it's always trivially copyable. 4650 // A moving constructor could be a copy constructor instead. 4651 if (!BaseCtor->isMoveConstructor() && 4652 !BaseDecl->isTriviallyCopyable()) 4653 return true; 4654 } 4655 4656 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4657 FE = RD->field_end(); 4658 FI != FE; ++FI) { 4659 QualType FieldType = Context.getBaseElementType(FI->getType()); 4660 4661 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) { 4662 // This is an anonymous union 4663 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4664 // Anonymous unions inside unions do not variant members create 4665 if (!Union) { 4666 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4667 UE = FieldRecord->field_end(); 4668 UI != UE; ++UI) { 4669 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4670 CXXRecordDecl *UnionFieldRecord = 4671 UnionFieldType->getAsCXXRecordDecl(); 4672 4673 // -- a variant member with a non-trivial [move] constructor and X 4674 // is a union-like class 4675 if (UnionFieldRecord && 4676 !UnionFieldRecord->hasTrivialMoveConstructor()) 4677 return true; 4678 } 4679 } 4680 4681 // Don't try to initalize an anonymous union 4682 continue; 4683 } else { 4684 // -- a variant member with a non-trivial [move] constructor and X is a 4685 // union-like class 4686 if (Union && !FieldRecord->hasTrivialMoveConstructor()) 4687 return true; 4688 4689 // -- any [non-static data member] of a type with a destructor that is 4690 // deleted or inaccessible from the defaulted constructor 4691 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4692 if (FieldDtor->isDeleted()) 4693 return true; 4694 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4695 AR_accessible) 4696 return true; 4697 } 4698 4699 // -- a [non-static data member of class type (or array thereof)] B that 4700 // cannot be [moved] because overload resolution, as applied to B's 4701 // [move] constructor, results in an ambiguity or a function that is 4702 // deleted or inaccessible from the defaulted constructor 4703 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord); 4704 if (!FieldCtor || FieldCtor->isDeleted()) 4705 return true; 4706 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4707 PDiag()) != AR_accessible) 4708 return true; 4709 4710 // -- for a move constructor, a [non-static data member] with a type that 4711 // does not have a move constructor and is not trivially copyable. 4712 // If the field isn't a record, it's always trivially copyable. 4713 // A moving constructor could be a copy constructor instead. 4714 if (!FieldCtor->isMoveConstructor() && 4715 !FieldRecord->isTriviallyCopyable()) 4716 return true; 4717 } 4718 } 4719 4720 return false; 4721} 4722 4723bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) { 4724 CXXRecordDecl *RD = MD->getParent(); 4725 assert(!RD->isDependentType() && "do deletion after instantiation"); 4726 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4727 return false; 4728 4729 SourceLocation Loc = MD->getLocation(); 4730 4731 // Do access control from the constructor 4732 ContextRAII MethodContext(*this, MD); 4733 4734 bool Union = RD->isUnion(); 4735 4736 // We do this because we should never actually use an anonymous 4737 // union's constructor. 4738 if (Union && RD->isAnonymousStructOrUnion()) 4739 return false; 4740 4741 // C++0x [class.copy]/20 4742 // A defaulted [move] assignment operator for class X is defined as deleted 4743 // if X has: 4744 4745 // -- for the move constructor, [...] any direct or indirect virtual base 4746 // class. 4747 if (RD->getNumVBases() != 0) 4748 return true; 4749 4750 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4751 BE = RD->bases_end(); 4752 BI != BE; ++BI) { 4753 4754 QualType BaseType = BI->getType(); 4755 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4756 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4757 4758 // -- a [direct base class] B that cannot be [moved] because overload 4759 // resolution, as applied to B's [move] assignment operator, results in 4760 // an ambiguity or a function that is deleted or inaccessible from the 4761 // assignment operator 4762 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0); 4763 if (!MoveOper || MoveOper->isDeleted()) 4764 return true; 4765 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4766 return true; 4767 4768 // -- for the move assignment operator, a [direct base class] with a type 4769 // that does not have a move assignment operator and is not trivially 4770 // copyable. 4771 if (!MoveOper->isMoveAssignmentOperator() && 4772 !BaseDecl->isTriviallyCopyable()) 4773 return true; 4774 } 4775 4776 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4777 FE = RD->field_end(); 4778 FI != FE; ++FI) { 4779 QualType FieldType = Context.getBaseElementType(FI->getType()); 4780 4781 // -- a non-static data member of reference type 4782 if (FieldType->isReferenceType()) 4783 return true; 4784 4785 // -- a non-static data member of const non-class type (or array thereof) 4786 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4787 return true; 4788 4789 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4790 4791 if (FieldRecord) { 4792 // This is an anonymous union 4793 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4794 // Anonymous unions inside unions do not variant members create 4795 if (!Union) { 4796 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4797 UE = FieldRecord->field_end(); 4798 UI != UE; ++UI) { 4799 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4800 CXXRecordDecl *UnionFieldRecord = 4801 UnionFieldType->getAsCXXRecordDecl(); 4802 4803 // -- a variant member with a non-trivial [move] assignment operator 4804 // and X is a union-like class 4805 if (UnionFieldRecord && 4806 !UnionFieldRecord->hasTrivialMoveAssignment()) 4807 return true; 4808 } 4809 } 4810 4811 // Don't try to initalize an anonymous union 4812 continue; 4813 // -- a variant member with a non-trivial [move] assignment operator 4814 // and X is a union-like class 4815 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) { 4816 return true; 4817 } 4818 4819 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0); 4820 if (!MoveOper || MoveOper->isDeleted()) 4821 return true; 4822 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4823 return true; 4824 4825 // -- for the move assignment operator, a [non-static data member] with a 4826 // type that does not have a move assignment operator and is not 4827 // trivially copyable. 4828 if (!MoveOper->isMoveAssignmentOperator() && 4829 !FieldRecord->isTriviallyCopyable()) 4830 return true; 4831 } 4832 } 4833 4834 return false; 4835} 4836 4837bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) { 4838 CXXRecordDecl *RD = DD->getParent(); 4839 assert(!RD->isDependentType() && "do deletion after instantiation"); 4840 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4841 return false; 4842 4843 SourceLocation Loc = DD->getLocation(); 4844 4845 // Do access control from the destructor 4846 ContextRAII CtorContext(*this, DD); 4847 4848 bool Union = RD->isUnion(); 4849 4850 // We do this because we should never actually use an anonymous 4851 // union's destructor. 4852 if (Union && RD->isAnonymousStructOrUnion()) 4853 return false; 4854 4855 // C++0x [class.dtor]p5 4856 // A defaulted destructor for a class X is defined as deleted if: 4857 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4858 BE = RD->bases_end(); 4859 BI != BE; ++BI) { 4860 // We'll handle this one later 4861 if (BI->isVirtual()) 4862 continue; 4863 4864 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4865 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4866 assert(BaseDtor && "base has no destructor"); 4867 4868 // -- any direct or virtual base class has a deleted destructor or 4869 // a destructor that is inaccessible from the defaulted destructor 4870 if (BaseDtor->isDeleted()) 4871 return true; 4872 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4873 AR_accessible) 4874 return true; 4875 } 4876 4877 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4878 BE = RD->vbases_end(); 4879 BI != BE; ++BI) { 4880 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4881 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4882 assert(BaseDtor && "base has no destructor"); 4883 4884 // -- any direct or virtual base class has a deleted destructor or 4885 // a destructor that is inaccessible from the defaulted destructor 4886 if (BaseDtor->isDeleted()) 4887 return true; 4888 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4889 AR_accessible) 4890 return true; 4891 } 4892 4893 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4894 FE = RD->field_end(); 4895 FI != FE; ++FI) { 4896 QualType FieldType = Context.getBaseElementType(FI->getType()); 4897 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4898 if (FieldRecord) { 4899 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4900 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4901 UE = FieldRecord->field_end(); 4902 UI != UE; ++UI) { 4903 QualType UnionFieldType = Context.getBaseElementType(FI->getType()); 4904 CXXRecordDecl *UnionFieldRecord = 4905 UnionFieldType->getAsCXXRecordDecl(); 4906 4907 // -- X is a union-like class that has a variant member with a non- 4908 // trivial destructor. 4909 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor()) 4910 return true; 4911 } 4912 // Technically we are supposed to do this next check unconditionally. 4913 // But that makes absolutely no sense. 4914 } else { 4915 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4916 4917 // -- any of the non-static data members has class type M (or array 4918 // thereof) and M has a deleted destructor or a destructor that is 4919 // inaccessible from the defaulted destructor 4920 if (FieldDtor->isDeleted()) 4921 return true; 4922 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4923 AR_accessible) 4924 return true; 4925 4926 // -- X is a union-like class that has a variant member with a non- 4927 // trivial destructor. 4928 if (Union && !FieldDtor->isTrivial()) 4929 return true; 4930 } 4931 } 4932 } 4933 4934 if (DD->isVirtual()) { 4935 FunctionDecl *OperatorDelete = 0; 4936 DeclarationName Name = 4937 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4938 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, 4939 false)) 4940 return true; 4941 } 4942 4943 4944 return false; 4945} 4946 4947/// \brief Data used with FindHiddenVirtualMethod 4948namespace { 4949 struct FindHiddenVirtualMethodData { 4950 Sema *S; 4951 CXXMethodDecl *Method; 4952 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4953 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4954 }; 4955} 4956 4957/// \brief Member lookup function that determines whether a given C++ 4958/// method overloads virtual methods in a base class without overriding any, 4959/// to be used with CXXRecordDecl::lookupInBases(). 4960static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4961 CXXBasePath &Path, 4962 void *UserData) { 4963 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4964 4965 FindHiddenVirtualMethodData &Data 4966 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4967 4968 DeclarationName Name = Data.Method->getDeclName(); 4969 assert(Name.getNameKind() == DeclarationName::Identifier); 4970 4971 bool foundSameNameMethod = false; 4972 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4973 for (Path.Decls = BaseRecord->lookup(Name); 4974 Path.Decls.first != Path.Decls.second; 4975 ++Path.Decls.first) { 4976 NamedDecl *D = *Path.Decls.first; 4977 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4978 MD = MD->getCanonicalDecl(); 4979 foundSameNameMethod = true; 4980 // Interested only in hidden virtual methods. 4981 if (!MD->isVirtual()) 4982 continue; 4983 // If the method we are checking overrides a method from its base 4984 // don't warn about the other overloaded methods. 4985 if (!Data.S->IsOverload(Data.Method, MD, false)) 4986 return true; 4987 // Collect the overload only if its hidden. 4988 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4989 overloadedMethods.push_back(MD); 4990 } 4991 } 4992 4993 if (foundSameNameMethod) 4994 Data.OverloadedMethods.append(overloadedMethods.begin(), 4995 overloadedMethods.end()); 4996 return foundSameNameMethod; 4997} 4998 4999/// \brief See if a method overloads virtual methods in a base class without 5000/// overriding any. 5001void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5002 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5003 MD->getLocation()) == DiagnosticsEngine::Ignored) 5004 return; 5005 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 5006 return; 5007 5008 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5009 /*bool RecordPaths=*/false, 5010 /*bool DetectVirtual=*/false); 5011 FindHiddenVirtualMethodData Data; 5012 Data.Method = MD; 5013 Data.S = this; 5014 5015 // Keep the base methods that were overriden or introduced in the subclass 5016 // by 'using' in a set. A base method not in this set is hidden. 5017 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 5018 res.first != res.second; ++res.first) { 5019 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 5020 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5021 E = MD->end_overridden_methods(); 5022 I != E; ++I) 5023 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 5024 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 5025 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 5026 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 5027 } 5028 5029 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5030 !Data.OverloadedMethods.empty()) { 5031 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5032 << MD << (Data.OverloadedMethods.size() > 1); 5033 5034 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5035 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5036 Diag(overloadedMD->getLocation(), 5037 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5038 } 5039 } 5040} 5041 5042void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5043 Decl *TagDecl, 5044 SourceLocation LBrac, 5045 SourceLocation RBrac, 5046 AttributeList *AttrList) { 5047 if (!TagDecl) 5048 return; 5049 5050 AdjustDeclIfTemplate(TagDecl); 5051 5052 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5053 // strict aliasing violation! 5054 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5055 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5056 5057 CheckCompletedCXXClass( 5058 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5059} 5060 5061/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5062/// special functions, such as the default constructor, copy 5063/// constructor, or destructor, to the given C++ class (C++ 5064/// [special]p1). This routine can only be executed just before the 5065/// definition of the class is complete. 5066void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5067 if (!ClassDecl->hasUserDeclaredConstructor()) 5068 ++ASTContext::NumImplicitDefaultConstructors; 5069 5070 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 5071 ++ASTContext::NumImplicitCopyConstructors; 5072 5073 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5074 ++ASTContext::NumImplicitCopyAssignmentOperators; 5075 5076 // If we have a dynamic class, then the copy assignment operator may be 5077 // virtual, so we have to declare it immediately. This ensures that, e.g., 5078 // it shows up in the right place in the vtable and that we diagnose 5079 // problems with the implicit exception specification. 5080 if (ClassDecl->isDynamicClass()) 5081 DeclareImplicitCopyAssignment(ClassDecl); 5082 } 5083 5084 if (!ClassDecl->hasUserDeclaredDestructor()) { 5085 ++ASTContext::NumImplicitDestructors; 5086 5087 // If we have a dynamic class, then the destructor may be virtual, so we 5088 // have to declare the destructor immediately. This ensures that, e.g., it 5089 // shows up in the right place in the vtable and that we diagnose problems 5090 // with the implicit exception specification. 5091 if (ClassDecl->isDynamicClass()) 5092 DeclareImplicitDestructor(ClassDecl); 5093 } 5094} 5095 5096void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5097 if (!D) 5098 return; 5099 5100 int NumParamList = D->getNumTemplateParameterLists(); 5101 for (int i = 0; i < NumParamList; i++) { 5102 TemplateParameterList* Params = D->getTemplateParameterList(i); 5103 for (TemplateParameterList::iterator Param = Params->begin(), 5104 ParamEnd = Params->end(); 5105 Param != ParamEnd; ++Param) { 5106 NamedDecl *Named = cast<NamedDecl>(*Param); 5107 if (Named->getDeclName()) { 5108 S->AddDecl(Named); 5109 IdResolver.AddDecl(Named); 5110 } 5111 } 5112 } 5113} 5114 5115void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5116 if (!D) 5117 return; 5118 5119 TemplateParameterList *Params = 0; 5120 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5121 Params = Template->getTemplateParameters(); 5122 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5123 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5124 Params = PartialSpec->getTemplateParameters(); 5125 else 5126 return; 5127 5128 for (TemplateParameterList::iterator Param = Params->begin(), 5129 ParamEnd = Params->end(); 5130 Param != ParamEnd; ++Param) { 5131 NamedDecl *Named = cast<NamedDecl>(*Param); 5132 if (Named->getDeclName()) { 5133 S->AddDecl(Named); 5134 IdResolver.AddDecl(Named); 5135 } 5136 } 5137} 5138 5139void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5140 if (!RecordD) return; 5141 AdjustDeclIfTemplate(RecordD); 5142 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5143 PushDeclContext(S, Record); 5144} 5145 5146void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5147 if (!RecordD) return; 5148 PopDeclContext(); 5149} 5150 5151/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5152/// parsing a top-level (non-nested) C++ class, and we are now 5153/// parsing those parts of the given Method declaration that could 5154/// not be parsed earlier (C++ [class.mem]p2), such as default 5155/// arguments. This action should enter the scope of the given 5156/// Method declaration as if we had just parsed the qualified method 5157/// name. However, it should not bring the parameters into scope; 5158/// that will be performed by ActOnDelayedCXXMethodParameter. 5159void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5160} 5161 5162/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5163/// C++ method declaration. We're (re-)introducing the given 5164/// function parameter into scope for use in parsing later parts of 5165/// the method declaration. For example, we could see an 5166/// ActOnParamDefaultArgument event for this parameter. 5167void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5168 if (!ParamD) 5169 return; 5170 5171 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5172 5173 // If this parameter has an unparsed default argument, clear it out 5174 // to make way for the parsed default argument. 5175 if (Param->hasUnparsedDefaultArg()) 5176 Param->setDefaultArg(0); 5177 5178 S->AddDecl(Param); 5179 if (Param->getDeclName()) 5180 IdResolver.AddDecl(Param); 5181} 5182 5183/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5184/// processing the delayed method declaration for Method. The method 5185/// declaration is now considered finished. There may be a separate 5186/// ActOnStartOfFunctionDef action later (not necessarily 5187/// immediately!) for this method, if it was also defined inside the 5188/// class body. 5189void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5190 if (!MethodD) 5191 return; 5192 5193 AdjustDeclIfTemplate(MethodD); 5194 5195 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5196 5197 // Now that we have our default arguments, check the constructor 5198 // again. It could produce additional diagnostics or affect whether 5199 // the class has implicitly-declared destructors, among other 5200 // things. 5201 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5202 CheckConstructor(Constructor); 5203 5204 // Check the default arguments, which we may have added. 5205 if (!Method->isInvalidDecl()) 5206 CheckCXXDefaultArguments(Method); 5207} 5208 5209/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5210/// the well-formedness of the constructor declarator @p D with type @p 5211/// R. If there are any errors in the declarator, this routine will 5212/// emit diagnostics and set the invalid bit to true. In any case, the type 5213/// will be updated to reflect a well-formed type for the constructor and 5214/// returned. 5215QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5216 StorageClass &SC) { 5217 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5218 5219 // C++ [class.ctor]p3: 5220 // A constructor shall not be virtual (10.3) or static (9.4). A 5221 // constructor can be invoked for a const, volatile or const 5222 // volatile object. A constructor shall not be declared const, 5223 // volatile, or const volatile (9.3.2). 5224 if (isVirtual) { 5225 if (!D.isInvalidType()) 5226 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5227 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5228 << SourceRange(D.getIdentifierLoc()); 5229 D.setInvalidType(); 5230 } 5231 if (SC == SC_Static) { 5232 if (!D.isInvalidType()) 5233 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5234 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5235 << SourceRange(D.getIdentifierLoc()); 5236 D.setInvalidType(); 5237 SC = SC_None; 5238 } 5239 5240 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5241 if (FTI.TypeQuals != 0) { 5242 if (FTI.TypeQuals & Qualifiers::Const) 5243 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5244 << "const" << SourceRange(D.getIdentifierLoc()); 5245 if (FTI.TypeQuals & Qualifiers::Volatile) 5246 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5247 << "volatile" << SourceRange(D.getIdentifierLoc()); 5248 if (FTI.TypeQuals & Qualifiers::Restrict) 5249 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5250 << "restrict" << SourceRange(D.getIdentifierLoc()); 5251 D.setInvalidType(); 5252 } 5253 5254 // C++0x [class.ctor]p4: 5255 // A constructor shall not be declared with a ref-qualifier. 5256 if (FTI.hasRefQualifier()) { 5257 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5258 << FTI.RefQualifierIsLValueRef 5259 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5260 D.setInvalidType(); 5261 } 5262 5263 // Rebuild the function type "R" without any type qualifiers (in 5264 // case any of the errors above fired) and with "void" as the 5265 // return type, since constructors don't have return types. 5266 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5267 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5268 return R; 5269 5270 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5271 EPI.TypeQuals = 0; 5272 EPI.RefQualifier = RQ_None; 5273 5274 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 5275 Proto->getNumArgs(), EPI); 5276} 5277 5278/// CheckConstructor - Checks a fully-formed constructor for 5279/// well-formedness, issuing any diagnostics required. Returns true if 5280/// the constructor declarator is invalid. 5281void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5282 CXXRecordDecl *ClassDecl 5283 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5284 if (!ClassDecl) 5285 return Constructor->setInvalidDecl(); 5286 5287 // C++ [class.copy]p3: 5288 // A declaration of a constructor for a class X is ill-formed if 5289 // its first parameter is of type (optionally cv-qualified) X and 5290 // either there are no other parameters or else all other 5291 // parameters have default arguments. 5292 if (!Constructor->isInvalidDecl() && 5293 ((Constructor->getNumParams() == 1) || 5294 (Constructor->getNumParams() > 1 && 5295 Constructor->getParamDecl(1)->hasDefaultArg())) && 5296 Constructor->getTemplateSpecializationKind() 5297 != TSK_ImplicitInstantiation) { 5298 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5299 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5300 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5301 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5302 const char *ConstRef 5303 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5304 : " const &"; 5305 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5306 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5307 5308 // FIXME: Rather that making the constructor invalid, we should endeavor 5309 // to fix the type. 5310 Constructor->setInvalidDecl(); 5311 } 5312 } 5313} 5314 5315/// CheckDestructor - Checks a fully-formed destructor definition for 5316/// well-formedness, issuing any diagnostics required. Returns true 5317/// on error. 5318bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5319 CXXRecordDecl *RD = Destructor->getParent(); 5320 5321 if (Destructor->isVirtual()) { 5322 SourceLocation Loc; 5323 5324 if (!Destructor->isImplicit()) 5325 Loc = Destructor->getLocation(); 5326 else 5327 Loc = RD->getLocation(); 5328 5329 // If we have a virtual destructor, look up the deallocation function 5330 FunctionDecl *OperatorDelete = 0; 5331 DeclarationName Name = 5332 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5333 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5334 return true; 5335 5336 MarkDeclarationReferenced(Loc, OperatorDelete); 5337 5338 Destructor->setOperatorDelete(OperatorDelete); 5339 } 5340 5341 return false; 5342} 5343 5344static inline bool 5345FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5346 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5347 FTI.ArgInfo[0].Param && 5348 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5349} 5350 5351/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5352/// the well-formednes of the destructor declarator @p D with type @p 5353/// R. If there are any errors in the declarator, this routine will 5354/// emit diagnostics and set the declarator to invalid. Even if this happens, 5355/// will be updated to reflect a well-formed type for the destructor and 5356/// returned. 5357QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5358 StorageClass& SC) { 5359 // C++ [class.dtor]p1: 5360 // [...] A typedef-name that names a class is a class-name 5361 // (7.1.3); however, a typedef-name that names a class shall not 5362 // be used as the identifier in the declarator for a destructor 5363 // declaration. 5364 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5365 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5366 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5367 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5368 else if (const TemplateSpecializationType *TST = 5369 DeclaratorType->getAs<TemplateSpecializationType>()) 5370 if (TST->isTypeAlias()) 5371 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5372 << DeclaratorType << 1; 5373 5374 // C++ [class.dtor]p2: 5375 // A destructor is used to destroy objects of its class type. A 5376 // destructor takes no parameters, and no return type can be 5377 // specified for it (not even void). The address of a destructor 5378 // shall not be taken. A destructor shall not be static. A 5379 // destructor can be invoked for a const, volatile or const 5380 // volatile object. A destructor shall not be declared const, 5381 // volatile or const volatile (9.3.2). 5382 if (SC == SC_Static) { 5383 if (!D.isInvalidType()) 5384 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5385 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5386 << SourceRange(D.getIdentifierLoc()) 5387 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5388 5389 SC = SC_None; 5390 } 5391 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5392 // Destructors don't have return types, but the parser will 5393 // happily parse something like: 5394 // 5395 // class X { 5396 // float ~X(); 5397 // }; 5398 // 5399 // The return type will be eliminated later. 5400 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5401 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5402 << SourceRange(D.getIdentifierLoc()); 5403 } 5404 5405 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5406 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5407 if (FTI.TypeQuals & Qualifiers::Const) 5408 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5409 << "const" << SourceRange(D.getIdentifierLoc()); 5410 if (FTI.TypeQuals & Qualifiers::Volatile) 5411 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5412 << "volatile" << SourceRange(D.getIdentifierLoc()); 5413 if (FTI.TypeQuals & Qualifiers::Restrict) 5414 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5415 << "restrict" << SourceRange(D.getIdentifierLoc()); 5416 D.setInvalidType(); 5417 } 5418 5419 // C++0x [class.dtor]p2: 5420 // A destructor shall not be declared with a ref-qualifier. 5421 if (FTI.hasRefQualifier()) { 5422 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5423 << FTI.RefQualifierIsLValueRef 5424 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5425 D.setInvalidType(); 5426 } 5427 5428 // Make sure we don't have any parameters. 5429 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5430 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5431 5432 // Delete the parameters. 5433 FTI.freeArgs(); 5434 D.setInvalidType(); 5435 } 5436 5437 // Make sure the destructor isn't variadic. 5438 if (FTI.isVariadic) { 5439 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5440 D.setInvalidType(); 5441 } 5442 5443 // Rebuild the function type "R" without any type qualifiers or 5444 // parameters (in case any of the errors above fired) and with 5445 // "void" as the return type, since destructors don't have return 5446 // types. 5447 if (!D.isInvalidType()) 5448 return R; 5449 5450 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5451 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5452 EPI.Variadic = false; 5453 EPI.TypeQuals = 0; 5454 EPI.RefQualifier = RQ_None; 5455 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5456} 5457 5458/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5459/// well-formednes of the conversion function declarator @p D with 5460/// type @p R. If there are any errors in the declarator, this routine 5461/// will emit diagnostics and return true. Otherwise, it will return 5462/// false. Either way, the type @p R will be updated to reflect a 5463/// well-formed type for the conversion operator. 5464void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5465 StorageClass& SC) { 5466 // C++ [class.conv.fct]p1: 5467 // Neither parameter types nor return type can be specified. The 5468 // type of a conversion function (8.3.5) is "function taking no 5469 // parameter returning conversion-type-id." 5470 if (SC == SC_Static) { 5471 if (!D.isInvalidType()) 5472 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5473 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5474 << SourceRange(D.getIdentifierLoc()); 5475 D.setInvalidType(); 5476 SC = SC_None; 5477 } 5478 5479 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5480 5481 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5482 // Conversion functions don't have return types, but the parser will 5483 // happily parse something like: 5484 // 5485 // class X { 5486 // float operator bool(); 5487 // }; 5488 // 5489 // The return type will be changed later anyway. 5490 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5491 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5492 << SourceRange(D.getIdentifierLoc()); 5493 D.setInvalidType(); 5494 } 5495 5496 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5497 5498 // Make sure we don't have any parameters. 5499 if (Proto->getNumArgs() > 0) { 5500 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5501 5502 // Delete the parameters. 5503 D.getFunctionTypeInfo().freeArgs(); 5504 D.setInvalidType(); 5505 } else if (Proto->isVariadic()) { 5506 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5507 D.setInvalidType(); 5508 } 5509 5510 // Diagnose "&operator bool()" and other such nonsense. This 5511 // is actually a gcc extension which we don't support. 5512 if (Proto->getResultType() != ConvType) { 5513 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5514 << Proto->getResultType(); 5515 D.setInvalidType(); 5516 ConvType = Proto->getResultType(); 5517 } 5518 5519 // C++ [class.conv.fct]p4: 5520 // The conversion-type-id shall not represent a function type nor 5521 // an array type. 5522 if (ConvType->isArrayType()) { 5523 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5524 ConvType = Context.getPointerType(ConvType); 5525 D.setInvalidType(); 5526 } else if (ConvType->isFunctionType()) { 5527 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5528 ConvType = Context.getPointerType(ConvType); 5529 D.setInvalidType(); 5530 } 5531 5532 // Rebuild the function type "R" without any parameters (in case any 5533 // of the errors above fired) and with the conversion type as the 5534 // return type. 5535 if (D.isInvalidType()) 5536 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5537 5538 // C++0x explicit conversion operators. 5539 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 5540 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5541 diag::warn_explicit_conversion_functions) 5542 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5543} 5544 5545/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5546/// the declaration of the given C++ conversion function. This routine 5547/// is responsible for recording the conversion function in the C++ 5548/// class, if possible. 5549Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5550 assert(Conversion && "Expected to receive a conversion function declaration"); 5551 5552 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5553 5554 // Make sure we aren't redeclaring the conversion function. 5555 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5556 5557 // C++ [class.conv.fct]p1: 5558 // [...] A conversion function is never used to convert a 5559 // (possibly cv-qualified) object to the (possibly cv-qualified) 5560 // same object type (or a reference to it), to a (possibly 5561 // cv-qualified) base class of that type (or a reference to it), 5562 // or to (possibly cv-qualified) void. 5563 // FIXME: Suppress this warning if the conversion function ends up being a 5564 // virtual function that overrides a virtual function in a base class. 5565 QualType ClassType 5566 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5567 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5568 ConvType = ConvTypeRef->getPointeeType(); 5569 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5570 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5571 /* Suppress diagnostics for instantiations. */; 5572 else if (ConvType->isRecordType()) { 5573 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5574 if (ConvType == ClassType) 5575 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5576 << ClassType; 5577 else if (IsDerivedFrom(ClassType, ConvType)) 5578 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5579 << ClassType << ConvType; 5580 } else if (ConvType->isVoidType()) { 5581 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5582 << ClassType << ConvType; 5583 } 5584 5585 if (FunctionTemplateDecl *ConversionTemplate 5586 = Conversion->getDescribedFunctionTemplate()) 5587 return ConversionTemplate; 5588 5589 return Conversion; 5590} 5591 5592//===----------------------------------------------------------------------===// 5593// Namespace Handling 5594//===----------------------------------------------------------------------===// 5595 5596 5597 5598/// ActOnStartNamespaceDef - This is called at the start of a namespace 5599/// definition. 5600Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5601 SourceLocation InlineLoc, 5602 SourceLocation NamespaceLoc, 5603 SourceLocation IdentLoc, 5604 IdentifierInfo *II, 5605 SourceLocation LBrace, 5606 AttributeList *AttrList) { 5607 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5608 // For anonymous namespace, take the location of the left brace. 5609 SourceLocation Loc = II ? IdentLoc : LBrace; 5610 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 5611 StartLoc, Loc, II); 5612 Namespc->setInline(InlineLoc.isValid()); 5613 5614 Scope *DeclRegionScope = NamespcScope->getParent(); 5615 5616 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5617 5618 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5619 PushNamespaceVisibilityAttr(Attr); 5620 5621 if (II) { 5622 // C++ [namespace.def]p2: 5623 // The identifier in an original-namespace-definition shall not 5624 // have been previously defined in the declarative region in 5625 // which the original-namespace-definition appears. The 5626 // identifier in an original-namespace-definition is the name of 5627 // the namespace. Subsequently in that declarative region, it is 5628 // treated as an original-namespace-name. 5629 // 5630 // Since namespace names are unique in their scope, and we don't 5631 // look through using directives, just look for any ordinary names. 5632 5633 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5634 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5635 Decl::IDNS_Namespace; 5636 NamedDecl *PrevDecl = 0; 5637 for (DeclContext::lookup_result R 5638 = CurContext->getRedeclContext()->lookup(II); 5639 R.first != R.second; ++R.first) { 5640 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5641 PrevDecl = *R.first; 5642 break; 5643 } 5644 } 5645 5646 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 5647 // This is an extended namespace definition. 5648 if (Namespc->isInline() != OrigNS->isInline()) { 5649 // inline-ness must match 5650 if (OrigNS->isInline()) { 5651 // The user probably just forgot the 'inline', so suggest that it 5652 // be added back. 5653 Diag(Namespc->getLocation(), 5654 diag::warn_inline_namespace_reopened_noninline) 5655 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5656 } else { 5657 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 5658 << Namespc->isInline(); 5659 } 5660 Diag(OrigNS->getLocation(), diag::note_previous_definition); 5661 5662 // Recover by ignoring the new namespace's inline status. 5663 Namespc->setInline(OrigNS->isInline()); 5664 } 5665 5666 // Attach this namespace decl to the chain of extended namespace 5667 // definitions. 5668 OrigNS->setNextNamespace(Namespc); 5669 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 5670 5671 // Remove the previous declaration from the scope. 5672 if (DeclRegionScope->isDeclScope(OrigNS)) { 5673 IdResolver.RemoveDecl(OrigNS); 5674 DeclRegionScope->RemoveDecl(OrigNS); 5675 } 5676 } else if (PrevDecl) { 5677 // This is an invalid name redefinition. 5678 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 5679 << Namespc->getDeclName(); 5680 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5681 Namespc->setInvalidDecl(); 5682 // Continue on to push Namespc as current DeclContext and return it. 5683 } else if (II->isStr("std") && 5684 CurContext->getRedeclContext()->isTranslationUnit()) { 5685 // This is the first "real" definition of the namespace "std", so update 5686 // our cache of the "std" namespace to point at this definition. 5687 if (NamespaceDecl *StdNS = getStdNamespace()) { 5688 // We had already defined a dummy namespace "std". Link this new 5689 // namespace definition to the dummy namespace "std". 5690 StdNS->setNextNamespace(Namespc); 5691 StdNS->setLocation(IdentLoc); 5692 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 5693 } 5694 5695 // Make our StdNamespace cache point at the first real definition of the 5696 // "std" namespace. 5697 StdNamespace = Namespc; 5698 5699 // Add this instance of "std" to the set of known namespaces 5700 KnownNamespaces[Namespc] = false; 5701 } else if (!Namespc->isInline()) { 5702 // Since this is an "original" namespace, add it to the known set of 5703 // namespaces if it is not an inline namespace. 5704 KnownNamespaces[Namespc] = false; 5705 } 5706 5707 PushOnScopeChains(Namespc, DeclRegionScope); 5708 } else { 5709 // Anonymous namespaces. 5710 assert(Namespc->isAnonymousNamespace()); 5711 5712 // Link the anonymous namespace into its parent. 5713 NamespaceDecl *PrevDecl; 5714 DeclContext *Parent = CurContext->getRedeclContext(); 5715 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5716 PrevDecl = TU->getAnonymousNamespace(); 5717 TU->setAnonymousNamespace(Namespc); 5718 } else { 5719 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5720 PrevDecl = ND->getAnonymousNamespace(); 5721 ND->setAnonymousNamespace(Namespc); 5722 } 5723 5724 // Link the anonymous namespace with its previous declaration. 5725 if (PrevDecl) { 5726 assert(PrevDecl->isAnonymousNamespace()); 5727 assert(!PrevDecl->getNextNamespace()); 5728 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 5729 PrevDecl->setNextNamespace(Namespc); 5730 5731 if (Namespc->isInline() != PrevDecl->isInline()) { 5732 // inline-ness must match 5733 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 5734 << Namespc->isInline(); 5735 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5736 Namespc->setInvalidDecl(); 5737 // Recover by ignoring the new namespace's inline status. 5738 Namespc->setInline(PrevDecl->isInline()); 5739 } 5740 } 5741 5742 CurContext->addDecl(Namespc); 5743 5744 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5745 // behaves as if it were replaced by 5746 // namespace unique { /* empty body */ } 5747 // using namespace unique; 5748 // namespace unique { namespace-body } 5749 // where all occurrences of 'unique' in a translation unit are 5750 // replaced by the same identifier and this identifier differs 5751 // from all other identifiers in the entire program. 5752 5753 // We just create the namespace with an empty name and then add an 5754 // implicit using declaration, just like the standard suggests. 5755 // 5756 // CodeGen enforces the "universally unique" aspect by giving all 5757 // declarations semantically contained within an anonymous 5758 // namespace internal linkage. 5759 5760 if (!PrevDecl) { 5761 UsingDirectiveDecl* UD 5762 = UsingDirectiveDecl::Create(Context, CurContext, 5763 /* 'using' */ LBrace, 5764 /* 'namespace' */ SourceLocation(), 5765 /* qualifier */ NestedNameSpecifierLoc(), 5766 /* identifier */ SourceLocation(), 5767 Namespc, 5768 /* Ancestor */ CurContext); 5769 UD->setImplicit(); 5770 CurContext->addDecl(UD); 5771 } 5772 } 5773 5774 // Although we could have an invalid decl (i.e. the namespace name is a 5775 // redefinition), push it as current DeclContext and try to continue parsing. 5776 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5777 // for the namespace has the declarations that showed up in that particular 5778 // namespace definition. 5779 PushDeclContext(NamespcScope, Namespc); 5780 return Namespc; 5781} 5782 5783/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5784/// is a namespace alias, returns the namespace it points to. 5785static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5786 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5787 return AD->getNamespace(); 5788 return dyn_cast_or_null<NamespaceDecl>(D); 5789} 5790 5791/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5792/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5793void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5794 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5795 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5796 Namespc->setRBraceLoc(RBrace); 5797 PopDeclContext(); 5798 if (Namespc->hasAttr<VisibilityAttr>()) 5799 PopPragmaVisibility(); 5800} 5801 5802CXXRecordDecl *Sema::getStdBadAlloc() const { 5803 return cast_or_null<CXXRecordDecl>( 5804 StdBadAlloc.get(Context.getExternalSource())); 5805} 5806 5807NamespaceDecl *Sema::getStdNamespace() const { 5808 return cast_or_null<NamespaceDecl>( 5809 StdNamespace.get(Context.getExternalSource())); 5810} 5811 5812/// \brief Retrieve the special "std" namespace, which may require us to 5813/// implicitly define the namespace. 5814NamespaceDecl *Sema::getOrCreateStdNamespace() { 5815 if (!StdNamespace) { 5816 // The "std" namespace has not yet been defined, so build one implicitly. 5817 StdNamespace = NamespaceDecl::Create(Context, 5818 Context.getTranslationUnitDecl(), 5819 SourceLocation(), SourceLocation(), 5820 &PP.getIdentifierTable().get("std")); 5821 getStdNamespace()->setImplicit(true); 5822 } 5823 5824 return getStdNamespace(); 5825} 5826 5827/// \brief Determine whether a using statement is in a context where it will be 5828/// apply in all contexts. 5829static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5830 switch (CurContext->getDeclKind()) { 5831 case Decl::TranslationUnit: 5832 return true; 5833 case Decl::LinkageSpec: 5834 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5835 default: 5836 return false; 5837 } 5838} 5839 5840static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 5841 CXXScopeSpec &SS, 5842 SourceLocation IdentLoc, 5843 IdentifierInfo *Ident) { 5844 R.clear(); 5845 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 5846 R.getLookupKind(), Sc, &SS, NULL, 5847 false, S.CTC_NoKeywords, NULL)) { 5848 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() || 5849 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) { 5850 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions())); 5851 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions())); 5852 if (DeclContext *DC = S.computeDeclContext(SS, false)) 5853 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 5854 << Ident << DC << CorrectedQuotedStr << SS.getRange() 5855 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5856 else 5857 S.Diag(IdentLoc, diag::err_using_directive_suggest) 5858 << Ident << CorrectedQuotedStr 5859 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5860 5861 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 5862 diag::note_namespace_defined_here) << CorrectedQuotedStr; 5863 5864 Ident = Corrected.getCorrectionAsIdentifierInfo(); 5865 R.addDecl(Corrected.getCorrectionDecl()); 5866 return true; 5867 } 5868 R.setLookupName(Ident); 5869 } 5870 return false; 5871} 5872 5873Decl *Sema::ActOnUsingDirective(Scope *S, 5874 SourceLocation UsingLoc, 5875 SourceLocation NamespcLoc, 5876 CXXScopeSpec &SS, 5877 SourceLocation IdentLoc, 5878 IdentifierInfo *NamespcName, 5879 AttributeList *AttrList) { 5880 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5881 assert(NamespcName && "Invalid NamespcName."); 5882 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 5883 5884 // This can only happen along a recovery path. 5885 while (S->getFlags() & Scope::TemplateParamScope) 5886 S = S->getParent(); 5887 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5888 5889 UsingDirectiveDecl *UDir = 0; 5890 NestedNameSpecifier *Qualifier = 0; 5891 if (SS.isSet()) 5892 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5893 5894 // Lookup namespace name. 5895 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 5896 LookupParsedName(R, S, &SS); 5897 if (R.isAmbiguous()) 5898 return 0; 5899 5900 if (R.empty()) { 5901 R.clear(); 5902 // Allow "using namespace std;" or "using namespace ::std;" even if 5903 // "std" hasn't been defined yet, for GCC compatibility. 5904 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 5905 NamespcName->isStr("std")) { 5906 Diag(IdentLoc, diag::ext_using_undefined_std); 5907 R.addDecl(getOrCreateStdNamespace()); 5908 R.resolveKind(); 5909 } 5910 // Otherwise, attempt typo correction. 5911 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 5912 } 5913 5914 if (!R.empty()) { 5915 NamedDecl *Named = R.getFoundDecl(); 5916 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 5917 && "expected namespace decl"); 5918 // C++ [namespace.udir]p1: 5919 // A using-directive specifies that the names in the nominated 5920 // namespace can be used in the scope in which the 5921 // using-directive appears after the using-directive. During 5922 // unqualified name lookup (3.4.1), the names appear as if they 5923 // were declared in the nearest enclosing namespace which 5924 // contains both the using-directive and the nominated 5925 // namespace. [Note: in this context, "contains" means "contains 5926 // directly or indirectly". ] 5927 5928 // Find enclosing context containing both using-directive and 5929 // nominated namespace. 5930 NamespaceDecl *NS = getNamespaceDecl(Named); 5931 DeclContext *CommonAncestor = cast<DeclContext>(NS); 5932 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 5933 CommonAncestor = CommonAncestor->getParent(); 5934 5935 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 5936 SS.getWithLocInContext(Context), 5937 IdentLoc, Named, CommonAncestor); 5938 5939 if (IsUsingDirectiveInToplevelContext(CurContext) && 5940 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 5941 Diag(IdentLoc, diag::warn_using_directive_in_header); 5942 } 5943 5944 PushUsingDirective(S, UDir); 5945 } else { 5946 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 5947 } 5948 5949 // FIXME: We ignore attributes for now. 5950 return UDir; 5951} 5952 5953void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 5954 // If scope has associated entity, then using directive is at namespace 5955 // or translation unit scope. We add UsingDirectiveDecls, into 5956 // it's lookup structure. 5957 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 5958 Ctx->addDecl(UDir); 5959 else 5960 // Otherwise it is block-sope. using-directives will affect lookup 5961 // only to the end of scope. 5962 S->PushUsingDirective(UDir); 5963} 5964 5965 5966Decl *Sema::ActOnUsingDeclaration(Scope *S, 5967 AccessSpecifier AS, 5968 bool HasUsingKeyword, 5969 SourceLocation UsingLoc, 5970 CXXScopeSpec &SS, 5971 UnqualifiedId &Name, 5972 AttributeList *AttrList, 5973 bool IsTypeName, 5974 SourceLocation TypenameLoc) { 5975 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5976 5977 switch (Name.getKind()) { 5978 case UnqualifiedId::IK_ImplicitSelfParam: 5979 case UnqualifiedId::IK_Identifier: 5980 case UnqualifiedId::IK_OperatorFunctionId: 5981 case UnqualifiedId::IK_LiteralOperatorId: 5982 case UnqualifiedId::IK_ConversionFunctionId: 5983 break; 5984 5985 case UnqualifiedId::IK_ConstructorName: 5986 case UnqualifiedId::IK_ConstructorTemplateId: 5987 // C++0x inherited constructors. 5988 if (getLangOptions().CPlusPlus0x) break; 5989 5990 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 5991 << SS.getRange(); 5992 return 0; 5993 5994 case UnqualifiedId::IK_DestructorName: 5995 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 5996 << SS.getRange(); 5997 return 0; 5998 5999 case UnqualifiedId::IK_TemplateId: 6000 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 6001 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6002 return 0; 6003 } 6004 6005 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6006 DeclarationName TargetName = TargetNameInfo.getName(); 6007 if (!TargetName) 6008 return 0; 6009 6010 // Warn about using declarations. 6011 // TODO: store that the declaration was written without 'using' and 6012 // talk about access decls instead of using decls in the 6013 // diagnostics. 6014 if (!HasUsingKeyword) { 6015 UsingLoc = Name.getSourceRange().getBegin(); 6016 6017 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6018 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6019 } 6020 6021 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6022 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6023 return 0; 6024 6025 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6026 TargetNameInfo, AttrList, 6027 /* IsInstantiation */ false, 6028 IsTypeName, TypenameLoc); 6029 if (UD) 6030 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6031 6032 return UD; 6033} 6034 6035/// \brief Determine whether a using declaration considers the given 6036/// declarations as "equivalent", e.g., if they are redeclarations of 6037/// the same entity or are both typedefs of the same type. 6038static bool 6039IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6040 bool &SuppressRedeclaration) { 6041 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6042 SuppressRedeclaration = false; 6043 return true; 6044 } 6045 6046 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6047 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6048 SuppressRedeclaration = true; 6049 return Context.hasSameType(TD1->getUnderlyingType(), 6050 TD2->getUnderlyingType()); 6051 } 6052 6053 return false; 6054} 6055 6056 6057/// Determines whether to create a using shadow decl for a particular 6058/// decl, given the set of decls existing prior to this using lookup. 6059bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6060 const LookupResult &Previous) { 6061 // Diagnose finding a decl which is not from a base class of the 6062 // current class. We do this now because there are cases where this 6063 // function will silently decide not to build a shadow decl, which 6064 // will pre-empt further diagnostics. 6065 // 6066 // We don't need to do this in C++0x because we do the check once on 6067 // the qualifier. 6068 // 6069 // FIXME: diagnose the following if we care enough: 6070 // struct A { int foo; }; 6071 // struct B : A { using A::foo; }; 6072 // template <class T> struct C : A {}; 6073 // template <class T> struct D : C<T> { using B::foo; } // <--- 6074 // This is invalid (during instantiation) in C++03 because B::foo 6075 // resolves to the using decl in B, which is not a base class of D<T>. 6076 // We can't diagnose it immediately because C<T> is an unknown 6077 // specialization. The UsingShadowDecl in D<T> then points directly 6078 // to A::foo, which will look well-formed when we instantiate. 6079 // The right solution is to not collapse the shadow-decl chain. 6080 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 6081 DeclContext *OrigDC = Orig->getDeclContext(); 6082 6083 // Handle enums and anonymous structs. 6084 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6085 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6086 while (OrigRec->isAnonymousStructOrUnion()) 6087 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6088 6089 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6090 if (OrigDC == CurContext) { 6091 Diag(Using->getLocation(), 6092 diag::err_using_decl_nested_name_specifier_is_current_class) 6093 << Using->getQualifierLoc().getSourceRange(); 6094 Diag(Orig->getLocation(), diag::note_using_decl_target); 6095 return true; 6096 } 6097 6098 Diag(Using->getQualifierLoc().getBeginLoc(), 6099 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6100 << Using->getQualifier() 6101 << cast<CXXRecordDecl>(CurContext) 6102 << Using->getQualifierLoc().getSourceRange(); 6103 Diag(Orig->getLocation(), diag::note_using_decl_target); 6104 return true; 6105 } 6106 } 6107 6108 if (Previous.empty()) return false; 6109 6110 NamedDecl *Target = Orig; 6111 if (isa<UsingShadowDecl>(Target)) 6112 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6113 6114 // If the target happens to be one of the previous declarations, we 6115 // don't have a conflict. 6116 // 6117 // FIXME: but we might be increasing its access, in which case we 6118 // should redeclare it. 6119 NamedDecl *NonTag = 0, *Tag = 0; 6120 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6121 I != E; ++I) { 6122 NamedDecl *D = (*I)->getUnderlyingDecl(); 6123 bool Result; 6124 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6125 return Result; 6126 6127 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6128 } 6129 6130 if (Target->isFunctionOrFunctionTemplate()) { 6131 FunctionDecl *FD; 6132 if (isa<FunctionTemplateDecl>(Target)) 6133 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6134 else 6135 FD = cast<FunctionDecl>(Target); 6136 6137 NamedDecl *OldDecl = 0; 6138 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6139 case Ovl_Overload: 6140 return false; 6141 6142 case Ovl_NonFunction: 6143 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6144 break; 6145 6146 // We found a decl with the exact signature. 6147 case Ovl_Match: 6148 // If we're in a record, we want to hide the target, so we 6149 // return true (without a diagnostic) to tell the caller not to 6150 // build a shadow decl. 6151 if (CurContext->isRecord()) 6152 return true; 6153 6154 // If we're not in a record, this is an error. 6155 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6156 break; 6157 } 6158 6159 Diag(Target->getLocation(), diag::note_using_decl_target); 6160 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6161 return true; 6162 } 6163 6164 // Target is not a function. 6165 6166 if (isa<TagDecl>(Target)) { 6167 // No conflict between a tag and a non-tag. 6168 if (!Tag) return false; 6169 6170 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6171 Diag(Target->getLocation(), diag::note_using_decl_target); 6172 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6173 return true; 6174 } 6175 6176 // No conflict between a tag and a non-tag. 6177 if (!NonTag) return false; 6178 6179 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6180 Diag(Target->getLocation(), diag::note_using_decl_target); 6181 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6182 return true; 6183} 6184 6185/// Builds a shadow declaration corresponding to a 'using' declaration. 6186UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6187 UsingDecl *UD, 6188 NamedDecl *Orig) { 6189 6190 // If we resolved to another shadow declaration, just coalesce them. 6191 NamedDecl *Target = Orig; 6192 if (isa<UsingShadowDecl>(Target)) { 6193 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6194 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6195 } 6196 6197 UsingShadowDecl *Shadow 6198 = UsingShadowDecl::Create(Context, CurContext, 6199 UD->getLocation(), UD, Target); 6200 UD->addShadowDecl(Shadow); 6201 6202 Shadow->setAccess(UD->getAccess()); 6203 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6204 Shadow->setInvalidDecl(); 6205 6206 if (S) 6207 PushOnScopeChains(Shadow, S); 6208 else 6209 CurContext->addDecl(Shadow); 6210 6211 6212 return Shadow; 6213} 6214 6215/// Hides a using shadow declaration. This is required by the current 6216/// using-decl implementation when a resolvable using declaration in a 6217/// class is followed by a declaration which would hide or override 6218/// one or more of the using decl's targets; for example: 6219/// 6220/// struct Base { void foo(int); }; 6221/// struct Derived : Base { 6222/// using Base::foo; 6223/// void foo(int); 6224/// }; 6225/// 6226/// The governing language is C++03 [namespace.udecl]p12: 6227/// 6228/// When a using-declaration brings names from a base class into a 6229/// derived class scope, member functions in the derived class 6230/// override and/or hide member functions with the same name and 6231/// parameter types in a base class (rather than conflicting). 6232/// 6233/// There are two ways to implement this: 6234/// (1) optimistically create shadow decls when they're not hidden 6235/// by existing declarations, or 6236/// (2) don't create any shadow decls (or at least don't make them 6237/// visible) until we've fully parsed/instantiated the class. 6238/// The problem with (1) is that we might have to retroactively remove 6239/// a shadow decl, which requires several O(n) operations because the 6240/// decl structures are (very reasonably) not designed for removal. 6241/// (2) avoids this but is very fiddly and phase-dependent. 6242void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6243 if (Shadow->getDeclName().getNameKind() == 6244 DeclarationName::CXXConversionFunctionName) 6245 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6246 6247 // Remove it from the DeclContext... 6248 Shadow->getDeclContext()->removeDecl(Shadow); 6249 6250 // ...and the scope, if applicable... 6251 if (S) { 6252 S->RemoveDecl(Shadow); 6253 IdResolver.RemoveDecl(Shadow); 6254 } 6255 6256 // ...and the using decl. 6257 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6258 6259 // TODO: complain somehow if Shadow was used. It shouldn't 6260 // be possible for this to happen, because...? 6261} 6262 6263/// Builds a using declaration. 6264/// 6265/// \param IsInstantiation - Whether this call arises from an 6266/// instantiation of an unresolved using declaration. We treat 6267/// the lookup differently for these declarations. 6268NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6269 SourceLocation UsingLoc, 6270 CXXScopeSpec &SS, 6271 const DeclarationNameInfo &NameInfo, 6272 AttributeList *AttrList, 6273 bool IsInstantiation, 6274 bool IsTypeName, 6275 SourceLocation TypenameLoc) { 6276 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6277 SourceLocation IdentLoc = NameInfo.getLoc(); 6278 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6279 6280 // FIXME: We ignore attributes for now. 6281 6282 if (SS.isEmpty()) { 6283 Diag(IdentLoc, diag::err_using_requires_qualname); 6284 return 0; 6285 } 6286 6287 // Do the redeclaration lookup in the current scope. 6288 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6289 ForRedeclaration); 6290 Previous.setHideTags(false); 6291 if (S) { 6292 LookupName(Previous, S); 6293 6294 // It is really dumb that we have to do this. 6295 LookupResult::Filter F = Previous.makeFilter(); 6296 while (F.hasNext()) { 6297 NamedDecl *D = F.next(); 6298 if (!isDeclInScope(D, CurContext, S)) 6299 F.erase(); 6300 } 6301 F.done(); 6302 } else { 6303 assert(IsInstantiation && "no scope in non-instantiation"); 6304 assert(CurContext->isRecord() && "scope not record in instantiation"); 6305 LookupQualifiedName(Previous, CurContext); 6306 } 6307 6308 // Check for invalid redeclarations. 6309 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6310 return 0; 6311 6312 // Check for bad qualifiers. 6313 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6314 return 0; 6315 6316 DeclContext *LookupContext = computeDeclContext(SS); 6317 NamedDecl *D; 6318 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6319 if (!LookupContext) { 6320 if (IsTypeName) { 6321 // FIXME: not all declaration name kinds are legal here 6322 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6323 UsingLoc, TypenameLoc, 6324 QualifierLoc, 6325 IdentLoc, NameInfo.getName()); 6326 } else { 6327 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6328 QualifierLoc, NameInfo); 6329 } 6330 } else { 6331 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6332 NameInfo, IsTypeName); 6333 } 6334 D->setAccess(AS); 6335 CurContext->addDecl(D); 6336 6337 if (!LookupContext) return D; 6338 UsingDecl *UD = cast<UsingDecl>(D); 6339 6340 if (RequireCompleteDeclContext(SS, LookupContext)) { 6341 UD->setInvalidDecl(); 6342 return UD; 6343 } 6344 6345 // Constructor inheriting using decls get special treatment. 6346 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6347 if (CheckInheritedConstructorUsingDecl(UD)) 6348 UD->setInvalidDecl(); 6349 return UD; 6350 } 6351 6352 // Otherwise, look up the target name. 6353 6354 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6355 6356 // Unlike most lookups, we don't always want to hide tag 6357 // declarations: tag names are visible through the using declaration 6358 // even if hidden by ordinary names, *except* in a dependent context 6359 // where it's important for the sanity of two-phase lookup. 6360 if (!IsInstantiation) 6361 R.setHideTags(false); 6362 6363 LookupQualifiedName(R, LookupContext); 6364 6365 if (R.empty()) { 6366 Diag(IdentLoc, diag::err_no_member) 6367 << NameInfo.getName() << LookupContext << SS.getRange(); 6368 UD->setInvalidDecl(); 6369 return UD; 6370 } 6371 6372 if (R.isAmbiguous()) { 6373 UD->setInvalidDecl(); 6374 return UD; 6375 } 6376 6377 if (IsTypeName) { 6378 // If we asked for a typename and got a non-type decl, error out. 6379 if (!R.getAsSingle<TypeDecl>()) { 6380 Diag(IdentLoc, diag::err_using_typename_non_type); 6381 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6382 Diag((*I)->getUnderlyingDecl()->getLocation(), 6383 diag::note_using_decl_target); 6384 UD->setInvalidDecl(); 6385 return UD; 6386 } 6387 } else { 6388 // If we asked for a non-typename and we got a type, error out, 6389 // but only if this is an instantiation of an unresolved using 6390 // decl. Otherwise just silently find the type name. 6391 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6392 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6393 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6394 UD->setInvalidDecl(); 6395 return UD; 6396 } 6397 } 6398 6399 // C++0x N2914 [namespace.udecl]p6: 6400 // A using-declaration shall not name a namespace. 6401 if (R.getAsSingle<NamespaceDecl>()) { 6402 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6403 << SS.getRange(); 6404 UD->setInvalidDecl(); 6405 return UD; 6406 } 6407 6408 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6409 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6410 BuildUsingShadowDecl(S, UD, *I); 6411 } 6412 6413 return UD; 6414} 6415 6416/// Additional checks for a using declaration referring to a constructor name. 6417bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 6418 if (UD->isTypeName()) { 6419 // FIXME: Cannot specify typename when specifying constructor 6420 return true; 6421 } 6422 6423 const Type *SourceType = UD->getQualifier()->getAsType(); 6424 assert(SourceType && 6425 "Using decl naming constructor doesn't have type in scope spec."); 6426 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6427 6428 // Check whether the named type is a direct base class. 6429 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6430 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6431 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6432 BaseIt != BaseE; ++BaseIt) { 6433 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6434 if (CanonicalSourceType == BaseType) 6435 break; 6436 } 6437 6438 if (BaseIt == BaseE) { 6439 // Did not find SourceType in the bases. 6440 Diag(UD->getUsingLocation(), 6441 diag::err_using_decl_constructor_not_in_direct_base) 6442 << UD->getNameInfo().getSourceRange() 6443 << QualType(SourceType, 0) << TargetClass; 6444 return true; 6445 } 6446 6447 BaseIt->setInheritConstructors(); 6448 6449 return false; 6450} 6451 6452/// Checks that the given using declaration is not an invalid 6453/// redeclaration. Note that this is checking only for the using decl 6454/// itself, not for any ill-formedness among the UsingShadowDecls. 6455bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6456 bool isTypeName, 6457 const CXXScopeSpec &SS, 6458 SourceLocation NameLoc, 6459 const LookupResult &Prev) { 6460 // C++03 [namespace.udecl]p8: 6461 // C++0x [namespace.udecl]p10: 6462 // A using-declaration is a declaration and can therefore be used 6463 // repeatedly where (and only where) multiple declarations are 6464 // allowed. 6465 // 6466 // That's in non-member contexts. 6467 if (!CurContext->getRedeclContext()->isRecord()) 6468 return false; 6469 6470 NestedNameSpecifier *Qual 6471 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6472 6473 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6474 NamedDecl *D = *I; 6475 6476 bool DTypename; 6477 NestedNameSpecifier *DQual; 6478 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6479 DTypename = UD->isTypeName(); 6480 DQual = UD->getQualifier(); 6481 } else if (UnresolvedUsingValueDecl *UD 6482 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6483 DTypename = false; 6484 DQual = UD->getQualifier(); 6485 } else if (UnresolvedUsingTypenameDecl *UD 6486 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6487 DTypename = true; 6488 DQual = UD->getQualifier(); 6489 } else continue; 6490 6491 // using decls differ if one says 'typename' and the other doesn't. 6492 // FIXME: non-dependent using decls? 6493 if (isTypeName != DTypename) continue; 6494 6495 // using decls differ if they name different scopes (but note that 6496 // template instantiation can cause this check to trigger when it 6497 // didn't before instantiation). 6498 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6499 Context.getCanonicalNestedNameSpecifier(DQual)) 6500 continue; 6501 6502 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6503 Diag(D->getLocation(), diag::note_using_decl) << 1; 6504 return true; 6505 } 6506 6507 return false; 6508} 6509 6510 6511/// Checks that the given nested-name qualifier used in a using decl 6512/// in the current context is appropriately related to the current 6513/// scope. If an error is found, diagnoses it and returns true. 6514bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6515 const CXXScopeSpec &SS, 6516 SourceLocation NameLoc) { 6517 DeclContext *NamedContext = computeDeclContext(SS); 6518 6519 if (!CurContext->isRecord()) { 6520 // C++03 [namespace.udecl]p3: 6521 // C++0x [namespace.udecl]p8: 6522 // A using-declaration for a class member shall be a member-declaration. 6523 6524 // If we weren't able to compute a valid scope, it must be a 6525 // dependent class scope. 6526 if (!NamedContext || NamedContext->isRecord()) { 6527 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6528 << SS.getRange(); 6529 return true; 6530 } 6531 6532 // Otherwise, everything is known to be fine. 6533 return false; 6534 } 6535 6536 // The current scope is a record. 6537 6538 // If the named context is dependent, we can't decide much. 6539 if (!NamedContext) { 6540 // FIXME: in C++0x, we can diagnose if we can prove that the 6541 // nested-name-specifier does not refer to a base class, which is 6542 // still possible in some cases. 6543 6544 // Otherwise we have to conservatively report that things might be 6545 // okay. 6546 return false; 6547 } 6548 6549 if (!NamedContext->isRecord()) { 6550 // Ideally this would point at the last name in the specifier, 6551 // but we don't have that level of source info. 6552 Diag(SS.getRange().getBegin(), 6553 diag::err_using_decl_nested_name_specifier_is_not_class) 6554 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6555 return true; 6556 } 6557 6558 if (!NamedContext->isDependentContext() && 6559 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6560 return true; 6561 6562 if (getLangOptions().CPlusPlus0x) { 6563 // C++0x [namespace.udecl]p3: 6564 // In a using-declaration used as a member-declaration, the 6565 // nested-name-specifier shall name a base class of the class 6566 // being defined. 6567 6568 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6569 cast<CXXRecordDecl>(NamedContext))) { 6570 if (CurContext == NamedContext) { 6571 Diag(NameLoc, 6572 diag::err_using_decl_nested_name_specifier_is_current_class) 6573 << SS.getRange(); 6574 return true; 6575 } 6576 6577 Diag(SS.getRange().getBegin(), 6578 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6579 << (NestedNameSpecifier*) SS.getScopeRep() 6580 << cast<CXXRecordDecl>(CurContext) 6581 << SS.getRange(); 6582 return true; 6583 } 6584 6585 return false; 6586 } 6587 6588 // C++03 [namespace.udecl]p4: 6589 // A using-declaration used as a member-declaration shall refer 6590 // to a member of a base class of the class being defined [etc.]. 6591 6592 // Salient point: SS doesn't have to name a base class as long as 6593 // lookup only finds members from base classes. Therefore we can 6594 // diagnose here only if we can prove that that can't happen, 6595 // i.e. if the class hierarchies provably don't intersect. 6596 6597 // TODO: it would be nice if "definitely valid" results were cached 6598 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6599 // need to be repeated. 6600 6601 struct UserData { 6602 llvm::DenseSet<const CXXRecordDecl*> Bases; 6603 6604 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6605 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6606 Data->Bases.insert(Base); 6607 return true; 6608 } 6609 6610 bool hasDependentBases(const CXXRecordDecl *Class) { 6611 return !Class->forallBases(collect, this); 6612 } 6613 6614 /// Returns true if the base is dependent or is one of the 6615 /// accumulated base classes. 6616 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6617 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6618 return !Data->Bases.count(Base); 6619 } 6620 6621 bool mightShareBases(const CXXRecordDecl *Class) { 6622 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6623 } 6624 }; 6625 6626 UserData Data; 6627 6628 // Returns false if we find a dependent base. 6629 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6630 return false; 6631 6632 // Returns false if the class has a dependent base or if it or one 6633 // of its bases is present in the base set of the current context. 6634 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6635 return false; 6636 6637 Diag(SS.getRange().getBegin(), 6638 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6639 << (NestedNameSpecifier*) SS.getScopeRep() 6640 << cast<CXXRecordDecl>(CurContext) 6641 << SS.getRange(); 6642 6643 return true; 6644} 6645 6646Decl *Sema::ActOnAliasDeclaration(Scope *S, 6647 AccessSpecifier AS, 6648 MultiTemplateParamsArg TemplateParamLists, 6649 SourceLocation UsingLoc, 6650 UnqualifiedId &Name, 6651 TypeResult Type) { 6652 // Skip up to the relevant declaration scope. 6653 while (S->getFlags() & Scope::TemplateParamScope) 6654 S = S->getParent(); 6655 assert((S->getFlags() & Scope::DeclScope) && 6656 "got alias-declaration outside of declaration scope"); 6657 6658 if (Type.isInvalid()) 6659 return 0; 6660 6661 bool Invalid = false; 6662 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6663 TypeSourceInfo *TInfo = 0; 6664 GetTypeFromParser(Type.get(), &TInfo); 6665 6666 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6667 return 0; 6668 6669 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6670 UPPC_DeclarationType)) { 6671 Invalid = true; 6672 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6673 TInfo->getTypeLoc().getBeginLoc()); 6674 } 6675 6676 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6677 LookupName(Previous, S); 6678 6679 // Warn about shadowing the name of a template parameter. 6680 if (Previous.isSingleResult() && 6681 Previous.getFoundDecl()->isTemplateParameter()) { 6682 if (DiagnoseTemplateParameterShadow(Name.StartLocation, 6683 Previous.getFoundDecl())) 6684 Invalid = true; 6685 Previous.clear(); 6686 } 6687 6688 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6689 "name in alias declaration must be an identifier"); 6690 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6691 Name.StartLocation, 6692 Name.Identifier, TInfo); 6693 6694 NewTD->setAccess(AS); 6695 6696 if (Invalid) 6697 NewTD->setInvalidDecl(); 6698 6699 CheckTypedefForVariablyModifiedType(S, NewTD); 6700 Invalid |= NewTD->isInvalidDecl(); 6701 6702 bool Redeclaration = false; 6703 6704 NamedDecl *NewND; 6705 if (TemplateParamLists.size()) { 6706 TypeAliasTemplateDecl *OldDecl = 0; 6707 TemplateParameterList *OldTemplateParams = 0; 6708 6709 if (TemplateParamLists.size() != 1) { 6710 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6711 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6712 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6713 } 6714 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6715 6716 // Only consider previous declarations in the same scope. 6717 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6718 /*ExplicitInstantiationOrSpecialization*/false); 6719 if (!Previous.empty()) { 6720 Redeclaration = true; 6721 6722 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6723 if (!OldDecl && !Invalid) { 6724 Diag(UsingLoc, diag::err_redefinition_different_kind) 6725 << Name.Identifier; 6726 6727 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6728 if (OldD->getLocation().isValid()) 6729 Diag(OldD->getLocation(), diag::note_previous_definition); 6730 6731 Invalid = true; 6732 } 6733 6734 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6735 if (TemplateParameterListsAreEqual(TemplateParams, 6736 OldDecl->getTemplateParameters(), 6737 /*Complain=*/true, 6738 TPL_TemplateMatch)) 6739 OldTemplateParams = OldDecl->getTemplateParameters(); 6740 else 6741 Invalid = true; 6742 6743 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6744 if (!Invalid && 6745 !Context.hasSameType(OldTD->getUnderlyingType(), 6746 NewTD->getUnderlyingType())) { 6747 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6748 // but we can't reasonably accept it. 6749 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6750 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6751 if (OldTD->getLocation().isValid()) 6752 Diag(OldTD->getLocation(), diag::note_previous_definition); 6753 Invalid = true; 6754 } 6755 } 6756 } 6757 6758 // Merge any previous default template arguments into our parameters, 6759 // and check the parameter list. 6760 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6761 TPC_TypeAliasTemplate)) 6762 return 0; 6763 6764 TypeAliasTemplateDecl *NewDecl = 6765 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6766 Name.Identifier, TemplateParams, 6767 NewTD); 6768 6769 NewDecl->setAccess(AS); 6770 6771 if (Invalid) 6772 NewDecl->setInvalidDecl(); 6773 else if (OldDecl) 6774 NewDecl->setPreviousDeclaration(OldDecl); 6775 6776 NewND = NewDecl; 6777 } else { 6778 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6779 NewND = NewTD; 6780 } 6781 6782 if (!Redeclaration) 6783 PushOnScopeChains(NewND, S); 6784 6785 return NewND; 6786} 6787 6788Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6789 SourceLocation NamespaceLoc, 6790 SourceLocation AliasLoc, 6791 IdentifierInfo *Alias, 6792 CXXScopeSpec &SS, 6793 SourceLocation IdentLoc, 6794 IdentifierInfo *Ident) { 6795 6796 // Lookup the namespace name. 6797 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6798 LookupParsedName(R, S, &SS); 6799 6800 // Check if we have a previous declaration with the same name. 6801 NamedDecl *PrevDecl 6802 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6803 ForRedeclaration); 6804 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6805 PrevDecl = 0; 6806 6807 if (PrevDecl) { 6808 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6809 // We already have an alias with the same name that points to the same 6810 // namespace, so don't create a new one. 6811 // FIXME: At some point, we'll want to create the (redundant) 6812 // declaration to maintain better source information. 6813 if (!R.isAmbiguous() && !R.empty() && 6814 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6815 return 0; 6816 } 6817 6818 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6819 diag::err_redefinition_different_kind; 6820 Diag(AliasLoc, DiagID) << Alias; 6821 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6822 return 0; 6823 } 6824 6825 if (R.isAmbiguous()) 6826 return 0; 6827 6828 if (R.empty()) { 6829 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6830 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 6831 return 0; 6832 } 6833 } 6834 6835 NamespaceAliasDecl *AliasDecl = 6836 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6837 Alias, SS.getWithLocInContext(Context), 6838 IdentLoc, R.getFoundDecl()); 6839 6840 PushOnScopeChains(AliasDecl, S); 6841 return AliasDecl; 6842} 6843 6844namespace { 6845 /// \brief Scoped object used to handle the state changes required in Sema 6846 /// to implicitly define the body of a C++ member function; 6847 class ImplicitlyDefinedFunctionScope { 6848 Sema &S; 6849 Sema::ContextRAII SavedContext; 6850 6851 public: 6852 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 6853 : S(S), SavedContext(S, Method) 6854 { 6855 S.PushFunctionScope(); 6856 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 6857 } 6858 6859 ~ImplicitlyDefinedFunctionScope() { 6860 S.PopExpressionEvaluationContext(); 6861 S.PopFunctionOrBlockScope(); 6862 } 6863 }; 6864} 6865 6866Sema::ImplicitExceptionSpecification 6867Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 6868 // C++ [except.spec]p14: 6869 // An implicitly declared special member function (Clause 12) shall have an 6870 // exception-specification. [...] 6871 ImplicitExceptionSpecification ExceptSpec(Context); 6872 if (ClassDecl->isInvalidDecl()) 6873 return ExceptSpec; 6874 6875 // Direct base-class constructors. 6876 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6877 BEnd = ClassDecl->bases_end(); 6878 B != BEnd; ++B) { 6879 if (B->isVirtual()) // Handled below. 6880 continue; 6881 6882 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6883 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6884 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6885 // If this is a deleted function, add it anyway. This might be conformant 6886 // with the standard. This might not. I'm not sure. It might not matter. 6887 if (Constructor) 6888 ExceptSpec.CalledDecl(Constructor); 6889 } 6890 } 6891 6892 // Virtual base-class constructors. 6893 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6894 BEnd = ClassDecl->vbases_end(); 6895 B != BEnd; ++B) { 6896 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6897 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6898 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6899 // If this is a deleted function, add it anyway. This might be conformant 6900 // with the standard. This might not. I'm not sure. It might not matter. 6901 if (Constructor) 6902 ExceptSpec.CalledDecl(Constructor); 6903 } 6904 } 6905 6906 // Field constructors. 6907 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6908 FEnd = ClassDecl->field_end(); 6909 F != FEnd; ++F) { 6910 if (F->hasInClassInitializer()) { 6911 if (Expr *E = F->getInClassInitializer()) 6912 ExceptSpec.CalledExpr(E); 6913 else if (!F->isInvalidDecl()) 6914 ExceptSpec.SetDelayed(); 6915 } else if (const RecordType *RecordTy 6916 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 6917 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6918 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 6919 // If this is a deleted function, add it anyway. This might be conformant 6920 // with the standard. This might not. I'm not sure. It might not matter. 6921 // In particular, the problem is that this function never gets called. It 6922 // might just be ill-formed because this function attempts to refer to 6923 // a deleted function here. 6924 if (Constructor) 6925 ExceptSpec.CalledDecl(Constructor); 6926 } 6927 } 6928 6929 return ExceptSpec; 6930} 6931 6932CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 6933 CXXRecordDecl *ClassDecl) { 6934 // C++ [class.ctor]p5: 6935 // A default constructor for a class X is a constructor of class X 6936 // that can be called without an argument. If there is no 6937 // user-declared constructor for class X, a default constructor is 6938 // implicitly declared. An implicitly-declared default constructor 6939 // is an inline public member of its class. 6940 assert(!ClassDecl->hasUserDeclaredConstructor() && 6941 "Should not build implicit default constructor!"); 6942 6943 ImplicitExceptionSpecification Spec = 6944 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 6945 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6946 6947 // Create the actual constructor declaration. 6948 CanQualType ClassType 6949 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6950 SourceLocation ClassLoc = ClassDecl->getLocation(); 6951 DeclarationName Name 6952 = Context.DeclarationNames.getCXXConstructorName(ClassType); 6953 DeclarationNameInfo NameInfo(Name, ClassLoc); 6954 CXXConstructorDecl *DefaultCon 6955 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 6956 Context.getFunctionType(Context.VoidTy, 6957 0, 0, EPI), 6958 /*TInfo=*/0, 6959 /*isExplicit=*/false, 6960 /*isInline=*/true, 6961 /*isImplicitlyDeclared=*/true, 6962 // FIXME: apply the rules for definitions here 6963 /*isConstexpr=*/false); 6964 DefaultCon->setAccess(AS_public); 6965 DefaultCon->setDefaulted(); 6966 DefaultCon->setImplicit(); 6967 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6968 6969 // Note that we have declared this constructor. 6970 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6971 6972 if (Scope *S = getScopeForContext(ClassDecl)) 6973 PushOnScopeChains(DefaultCon, S, false); 6974 ClassDecl->addDecl(DefaultCon); 6975 6976 if (ShouldDeleteDefaultConstructor(DefaultCon)) 6977 DefaultCon->setDeletedAsWritten(); 6978 6979 return DefaultCon; 6980} 6981 6982void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6983 CXXConstructorDecl *Constructor) { 6984 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6985 !Constructor->doesThisDeclarationHaveABody() && 6986 !Constructor->isDeleted()) && 6987 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6988 6989 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6990 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6991 6992 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6993 DiagnosticErrorTrap Trap(Diags); 6994 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6995 Trap.hasErrorOccurred()) { 6996 Diag(CurrentLocation, diag::note_member_synthesized_at) 6997 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6998 Constructor->setInvalidDecl(); 6999 return; 7000 } 7001 7002 SourceLocation Loc = Constructor->getLocation(); 7003 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7004 7005 Constructor->setUsed(); 7006 MarkVTableUsed(CurrentLocation, ClassDecl); 7007 7008 if (ASTMutationListener *L = getASTMutationListener()) { 7009 L->CompletedImplicitDefinition(Constructor); 7010 } 7011} 7012 7013/// Get any existing defaulted default constructor for the given class. Do not 7014/// implicitly define one if it does not exist. 7015static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self, 7016 CXXRecordDecl *D) { 7017 ASTContext &Context = Self.Context; 7018 QualType ClassType = Context.getTypeDeclType(D); 7019 DeclarationName ConstructorName 7020 = Context.DeclarationNames.getCXXConstructorName( 7021 Context.getCanonicalType(ClassType.getUnqualifiedType())); 7022 7023 DeclContext::lookup_const_iterator Con, ConEnd; 7024 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 7025 Con != ConEnd; ++Con) { 7026 // A function template cannot be defaulted. 7027 if (isa<FunctionTemplateDecl>(*Con)) 7028 continue; 7029 7030 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 7031 if (Constructor->isDefaultConstructor()) 7032 return Constructor->isDefaulted() ? Constructor : 0; 7033 } 7034 return 0; 7035} 7036 7037void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7038 if (!D) return; 7039 AdjustDeclIfTemplate(D); 7040 7041 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 7042 CXXConstructorDecl *CtorDecl 7043 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl); 7044 7045 if (!CtorDecl) return; 7046 7047 // Compute the exception specification for the default constructor. 7048 const FunctionProtoType *CtorTy = 7049 CtorDecl->getType()->castAs<FunctionProtoType>(); 7050 if (CtorTy->getExceptionSpecType() == EST_Delayed) { 7051 ImplicitExceptionSpecification Spec = 7052 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 7053 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7054 assert(EPI.ExceptionSpecType != EST_Delayed); 7055 7056 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7057 } 7058 7059 // If the default constructor is explicitly defaulted, checking the exception 7060 // specification is deferred until now. 7061 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() && 7062 !ClassDecl->isDependentType()) 7063 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl); 7064} 7065 7066void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 7067 // We start with an initial pass over the base classes to collect those that 7068 // inherit constructors from. If there are none, we can forgo all further 7069 // processing. 7070 typedef SmallVector<const RecordType *, 4> BasesVector; 7071 BasesVector BasesToInheritFrom; 7072 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 7073 BaseE = ClassDecl->bases_end(); 7074 BaseIt != BaseE; ++BaseIt) { 7075 if (BaseIt->getInheritConstructors()) { 7076 QualType Base = BaseIt->getType(); 7077 if (Base->isDependentType()) { 7078 // If we inherit constructors from anything that is dependent, just 7079 // abort processing altogether. We'll get another chance for the 7080 // instantiations. 7081 return; 7082 } 7083 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 7084 } 7085 } 7086 if (BasesToInheritFrom.empty()) 7087 return; 7088 7089 // Now collect the constructors that we already have in the current class. 7090 // Those take precedence over inherited constructors. 7091 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7092 // unless there is a user-declared constructor with the same signature in 7093 // the class where the using-declaration appears. 7094 llvm::SmallSet<const Type *, 8> ExistingConstructors; 7095 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 7096 CtorE = ClassDecl->ctor_end(); 7097 CtorIt != CtorE; ++CtorIt) { 7098 ExistingConstructors.insert( 7099 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 7100 } 7101 7102 Scope *S = getScopeForContext(ClassDecl); 7103 DeclarationName CreatedCtorName = 7104 Context.DeclarationNames.getCXXConstructorName( 7105 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 7106 7107 // Now comes the true work. 7108 // First, we keep a map from constructor types to the base that introduced 7109 // them. Needed for finding conflicting constructors. We also keep the 7110 // actually inserted declarations in there, for pretty diagnostics. 7111 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 7112 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 7113 ConstructorToSourceMap InheritedConstructors; 7114 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 7115 BaseE = BasesToInheritFrom.end(); 7116 BaseIt != BaseE; ++BaseIt) { 7117 const RecordType *Base = *BaseIt; 7118 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 7119 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 7120 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 7121 CtorE = BaseDecl->ctor_end(); 7122 CtorIt != CtorE; ++CtorIt) { 7123 // Find the using declaration for inheriting this base's constructors. 7124 DeclarationName Name = 7125 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 7126 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 7127 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 7128 SourceLocation UsingLoc = UD ? UD->getLocation() : 7129 ClassDecl->getLocation(); 7130 7131 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 7132 // from the class X named in the using-declaration consists of actual 7133 // constructors and notional constructors that result from the 7134 // transformation of defaulted parameters as follows: 7135 // - all non-template default constructors of X, and 7136 // - for each non-template constructor of X that has at least one 7137 // parameter with a default argument, the set of constructors that 7138 // results from omitting any ellipsis parameter specification and 7139 // successively omitting parameters with a default argument from the 7140 // end of the parameter-type-list. 7141 CXXConstructorDecl *BaseCtor = *CtorIt; 7142 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 7143 const FunctionProtoType *BaseCtorType = 7144 BaseCtor->getType()->getAs<FunctionProtoType>(); 7145 7146 for (unsigned params = BaseCtor->getMinRequiredArguments(), 7147 maxParams = BaseCtor->getNumParams(); 7148 params <= maxParams; ++params) { 7149 // Skip default constructors. They're never inherited. 7150 if (params == 0) 7151 continue; 7152 // Skip copy and move constructors for the same reason. 7153 if (CanBeCopyOrMove && params == 1) 7154 continue; 7155 7156 // Build up a function type for this particular constructor. 7157 // FIXME: The working paper does not consider that the exception spec 7158 // for the inheriting constructor might be larger than that of the 7159 // source. This code doesn't yet, either. When it does, this code will 7160 // need to be delayed until after exception specifications and in-class 7161 // member initializers are attached. 7162 const Type *NewCtorType; 7163 if (params == maxParams) 7164 NewCtorType = BaseCtorType; 7165 else { 7166 SmallVector<QualType, 16> Args; 7167 for (unsigned i = 0; i < params; ++i) { 7168 Args.push_back(BaseCtorType->getArgType(i)); 7169 } 7170 FunctionProtoType::ExtProtoInfo ExtInfo = 7171 BaseCtorType->getExtProtoInfo(); 7172 ExtInfo.Variadic = false; 7173 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7174 Args.data(), params, ExtInfo) 7175 .getTypePtr(); 7176 } 7177 const Type *CanonicalNewCtorType = 7178 Context.getCanonicalType(NewCtorType); 7179 7180 // Now that we have the type, first check if the class already has a 7181 // constructor with this signature. 7182 if (ExistingConstructors.count(CanonicalNewCtorType)) 7183 continue; 7184 7185 // Then we check if we have already declared an inherited constructor 7186 // with this signature. 7187 std::pair<ConstructorToSourceMap::iterator, bool> result = 7188 InheritedConstructors.insert(std::make_pair( 7189 CanonicalNewCtorType, 7190 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7191 if (!result.second) { 7192 // Already in the map. If it came from a different class, that's an 7193 // error. Not if it's from the same. 7194 CanQualType PreviousBase = result.first->second.first; 7195 if (CanonicalBase != PreviousBase) { 7196 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7197 const CXXConstructorDecl *PrevBaseCtor = 7198 PrevCtor->getInheritedConstructor(); 7199 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7200 7201 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7202 Diag(BaseCtor->getLocation(), 7203 diag::note_using_decl_constructor_conflict_current_ctor); 7204 Diag(PrevBaseCtor->getLocation(), 7205 diag::note_using_decl_constructor_conflict_previous_ctor); 7206 Diag(PrevCtor->getLocation(), 7207 diag::note_using_decl_constructor_conflict_previous_using); 7208 } 7209 continue; 7210 } 7211 7212 // OK, we're there, now add the constructor. 7213 // C++0x [class.inhctor]p8: [...] that would be performed by a 7214 // user-written inline constructor [...] 7215 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7216 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7217 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7218 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7219 /*ImplicitlyDeclared=*/true, 7220 // FIXME: Due to a defect in the standard, we treat inherited 7221 // constructors as constexpr even if that makes them ill-formed. 7222 /*Constexpr=*/BaseCtor->isConstexpr()); 7223 NewCtor->setAccess(BaseCtor->getAccess()); 7224 7225 // Build up the parameter decls and add them. 7226 SmallVector<ParmVarDecl *, 16> ParamDecls; 7227 for (unsigned i = 0; i < params; ++i) { 7228 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7229 UsingLoc, UsingLoc, 7230 /*IdentifierInfo=*/0, 7231 BaseCtorType->getArgType(i), 7232 /*TInfo=*/0, SC_None, 7233 SC_None, /*DefaultArg=*/0)); 7234 } 7235 NewCtor->setParams(ParamDecls); 7236 NewCtor->setInheritedConstructor(BaseCtor); 7237 7238 PushOnScopeChains(NewCtor, S, false); 7239 ClassDecl->addDecl(NewCtor); 7240 result.first->second.second = NewCtor; 7241 } 7242 } 7243 } 7244} 7245 7246Sema::ImplicitExceptionSpecification 7247Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) { 7248 // C++ [except.spec]p14: 7249 // An implicitly declared special member function (Clause 12) shall have 7250 // an exception-specification. 7251 ImplicitExceptionSpecification ExceptSpec(Context); 7252 if (ClassDecl->isInvalidDecl()) 7253 return ExceptSpec; 7254 7255 // Direct base-class destructors. 7256 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7257 BEnd = ClassDecl->bases_end(); 7258 B != BEnd; ++B) { 7259 if (B->isVirtual()) // Handled below. 7260 continue; 7261 7262 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7263 ExceptSpec.CalledDecl( 7264 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7265 } 7266 7267 // Virtual base-class destructors. 7268 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7269 BEnd = ClassDecl->vbases_end(); 7270 B != BEnd; ++B) { 7271 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7272 ExceptSpec.CalledDecl( 7273 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7274 } 7275 7276 // Field destructors. 7277 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7278 FEnd = ClassDecl->field_end(); 7279 F != FEnd; ++F) { 7280 if (const RecordType *RecordTy 7281 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7282 ExceptSpec.CalledDecl( 7283 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7284 } 7285 7286 return ExceptSpec; 7287} 7288 7289CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7290 // C++ [class.dtor]p2: 7291 // If a class has no user-declared destructor, a destructor is 7292 // declared implicitly. An implicitly-declared destructor is an 7293 // inline public member of its class. 7294 7295 ImplicitExceptionSpecification Spec = 7296 ComputeDefaultedDtorExceptionSpec(ClassDecl); 7297 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7298 7299 // Create the actual destructor declaration. 7300 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 7301 7302 CanQualType ClassType 7303 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7304 SourceLocation ClassLoc = ClassDecl->getLocation(); 7305 DeclarationName Name 7306 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7307 DeclarationNameInfo NameInfo(Name, ClassLoc); 7308 CXXDestructorDecl *Destructor 7309 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 7310 /*isInline=*/true, 7311 /*isImplicitlyDeclared=*/true); 7312 Destructor->setAccess(AS_public); 7313 Destructor->setDefaulted(); 7314 Destructor->setImplicit(); 7315 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7316 7317 // Note that we have declared this destructor. 7318 ++ASTContext::NumImplicitDestructorsDeclared; 7319 7320 // Introduce this destructor into its scope. 7321 if (Scope *S = getScopeForContext(ClassDecl)) 7322 PushOnScopeChains(Destructor, S, false); 7323 ClassDecl->addDecl(Destructor); 7324 7325 // This could be uniqued if it ever proves significant. 7326 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 7327 7328 if (ShouldDeleteDestructor(Destructor)) 7329 Destructor->setDeletedAsWritten(); 7330 7331 AddOverriddenMethods(ClassDecl, Destructor); 7332 7333 return Destructor; 7334} 7335 7336void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7337 CXXDestructorDecl *Destructor) { 7338 assert((Destructor->isDefaulted() && 7339 !Destructor->doesThisDeclarationHaveABody()) && 7340 "DefineImplicitDestructor - call it for implicit default dtor"); 7341 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7342 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7343 7344 if (Destructor->isInvalidDecl()) 7345 return; 7346 7347 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7348 7349 DiagnosticErrorTrap Trap(Diags); 7350 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7351 Destructor->getParent()); 7352 7353 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7354 Diag(CurrentLocation, diag::note_member_synthesized_at) 7355 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7356 7357 Destructor->setInvalidDecl(); 7358 return; 7359 } 7360 7361 SourceLocation Loc = Destructor->getLocation(); 7362 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 7363 Destructor->setImplicitlyDefined(true); 7364 Destructor->setUsed(); 7365 MarkVTableUsed(CurrentLocation, ClassDecl); 7366 7367 if (ASTMutationListener *L = getASTMutationListener()) { 7368 L->CompletedImplicitDefinition(Destructor); 7369 } 7370} 7371 7372void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl, 7373 CXXDestructorDecl *destructor) { 7374 // C++11 [class.dtor]p3: 7375 // A declaration of a destructor that does not have an exception- 7376 // specification is implicitly considered to have the same exception- 7377 // specification as an implicit declaration. 7378 const FunctionProtoType *dtorType = destructor->getType()-> 7379 getAs<FunctionProtoType>(); 7380 if (dtorType->hasExceptionSpec()) 7381 return; 7382 7383 ImplicitExceptionSpecification exceptSpec = 7384 ComputeDefaultedDtorExceptionSpec(classDecl); 7385 7386 // Replace the destructor's type, building off the existing one. Fortunately, 7387 // the only thing of interest in the destructor type is its extended info. 7388 // The return and arguments are fixed. 7389 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo(); 7390 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType(); 7391 epi.NumExceptions = exceptSpec.size(); 7392 epi.Exceptions = exceptSpec.data(); 7393 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi); 7394 7395 destructor->setType(ty); 7396 7397 // FIXME: If the destructor has a body that could throw, and the newly created 7398 // spec doesn't allow exceptions, we should emit a warning, because this 7399 // change in behavior can break conforming C++03 programs at runtime. 7400 // However, we don't have a body yet, so it needs to be done somewhere else. 7401} 7402 7403/// \brief Builds a statement that copies/moves the given entity from \p From to 7404/// \c To. 7405/// 7406/// This routine is used to copy/move the members of a class with an 7407/// implicitly-declared copy/move assignment operator. When the entities being 7408/// copied are arrays, this routine builds for loops to copy them. 7409/// 7410/// \param S The Sema object used for type-checking. 7411/// 7412/// \param Loc The location where the implicit copy/move is being generated. 7413/// 7414/// \param T The type of the expressions being copied/moved. Both expressions 7415/// must have this type. 7416/// 7417/// \param To The expression we are copying/moving to. 7418/// 7419/// \param From The expression we are copying/moving from. 7420/// 7421/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7422/// Otherwise, it's a non-static member subobject. 7423/// 7424/// \param Copying Whether we're copying or moving. 7425/// 7426/// \param Depth Internal parameter recording the depth of the recursion. 7427/// 7428/// \returns A statement or a loop that copies the expressions. 7429static StmtResult 7430BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7431 Expr *To, Expr *From, 7432 bool CopyingBaseSubobject, bool Copying, 7433 unsigned Depth = 0) { 7434 // C++0x [class.copy]p28: 7435 // Each subobject is assigned in the manner appropriate to its type: 7436 // 7437 // - if the subobject is of class type, as if by a call to operator= with 7438 // the subobject as the object expression and the corresponding 7439 // subobject of x as a single function argument (as if by explicit 7440 // qualification; that is, ignoring any possible virtual overriding 7441 // functions in more derived classes); 7442 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7443 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7444 7445 // Look for operator=. 7446 DeclarationName Name 7447 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7448 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7449 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7450 7451 // Filter out any result that isn't a copy/move-assignment operator. 7452 LookupResult::Filter F = OpLookup.makeFilter(); 7453 while (F.hasNext()) { 7454 NamedDecl *D = F.next(); 7455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7456 if (Copying ? Method->isCopyAssignmentOperator() : 7457 Method->isMoveAssignmentOperator()) 7458 continue; 7459 7460 F.erase(); 7461 } 7462 F.done(); 7463 7464 // Suppress the protected check (C++ [class.protected]) for each of the 7465 // assignment operators we found. This strange dance is required when 7466 // we're assigning via a base classes's copy-assignment operator. To 7467 // ensure that we're getting the right base class subobject (without 7468 // ambiguities), we need to cast "this" to that subobject type; to 7469 // ensure that we don't go through the virtual call mechanism, we need 7470 // to qualify the operator= name with the base class (see below). However, 7471 // this means that if the base class has a protected copy assignment 7472 // operator, the protected member access check will fail. So, we 7473 // rewrite "protected" access to "public" access in this case, since we 7474 // know by construction that we're calling from a derived class. 7475 if (CopyingBaseSubobject) { 7476 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7477 L != LEnd; ++L) { 7478 if (L.getAccess() == AS_protected) 7479 L.setAccess(AS_public); 7480 } 7481 } 7482 7483 // Create the nested-name-specifier that will be used to qualify the 7484 // reference to operator=; this is required to suppress the virtual 7485 // call mechanism. 7486 CXXScopeSpec SS; 7487 SS.MakeTrivial(S.Context, 7488 NestedNameSpecifier::Create(S.Context, 0, false, 7489 T.getTypePtr()), 7490 Loc); 7491 7492 // Create the reference to operator=. 7493 ExprResult OpEqualRef 7494 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7495 /*FirstQualifierInScope=*/0, OpLookup, 7496 /*TemplateArgs=*/0, 7497 /*SuppressQualifierCheck=*/true); 7498 if (OpEqualRef.isInvalid()) 7499 return StmtError(); 7500 7501 // Build the call to the assignment operator. 7502 7503 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7504 OpEqualRef.takeAs<Expr>(), 7505 Loc, &From, 1, Loc); 7506 if (Call.isInvalid()) 7507 return StmtError(); 7508 7509 return S.Owned(Call.takeAs<Stmt>()); 7510 } 7511 7512 // - if the subobject is of scalar type, the built-in assignment 7513 // operator is used. 7514 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7515 if (!ArrayTy) { 7516 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7517 if (Assignment.isInvalid()) 7518 return StmtError(); 7519 7520 return S.Owned(Assignment.takeAs<Stmt>()); 7521 } 7522 7523 // - if the subobject is an array, each element is assigned, in the 7524 // manner appropriate to the element type; 7525 7526 // Construct a loop over the array bounds, e.g., 7527 // 7528 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7529 // 7530 // that will copy each of the array elements. 7531 QualType SizeType = S.Context.getSizeType(); 7532 7533 // Create the iteration variable. 7534 IdentifierInfo *IterationVarName = 0; 7535 { 7536 llvm::SmallString<8> Str; 7537 llvm::raw_svector_ostream OS(Str); 7538 OS << "__i" << Depth; 7539 IterationVarName = &S.Context.Idents.get(OS.str()); 7540 } 7541 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7542 IterationVarName, SizeType, 7543 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7544 SC_None, SC_None); 7545 7546 // Initialize the iteration variable to zero. 7547 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7548 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7549 7550 // Create a reference to the iteration variable; we'll use this several 7551 // times throughout. 7552 Expr *IterationVarRef 7553 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 7554 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7555 7556 // Create the DeclStmt that holds the iteration variable. 7557 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7558 7559 // Create the comparison against the array bound. 7560 llvm::APInt Upper 7561 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7562 Expr *Comparison 7563 = new (S.Context) BinaryOperator(IterationVarRef, 7564 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7565 BO_NE, S.Context.BoolTy, 7566 VK_RValue, OK_Ordinary, Loc); 7567 7568 // Create the pre-increment of the iteration variable. 7569 Expr *Increment 7570 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7571 VK_LValue, OK_Ordinary, Loc); 7572 7573 // Subscript the "from" and "to" expressions with the iteration variable. 7574 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7575 IterationVarRef, Loc)); 7576 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7577 IterationVarRef, Loc)); 7578 if (!Copying) // Cast to rvalue 7579 From = CastForMoving(S, From); 7580 7581 // Build the copy/move for an individual element of the array. 7582 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7583 To, From, CopyingBaseSubobject, 7584 Copying, Depth + 1); 7585 if (Copy.isInvalid()) 7586 return StmtError(); 7587 7588 // Construct the loop that copies all elements of this array. 7589 return S.ActOnForStmt(Loc, Loc, InitStmt, 7590 S.MakeFullExpr(Comparison), 7591 0, S.MakeFullExpr(Increment), 7592 Loc, Copy.take()); 7593} 7594 7595std::pair<Sema::ImplicitExceptionSpecification, bool> 7596Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst( 7597 CXXRecordDecl *ClassDecl) { 7598 if (ClassDecl->isInvalidDecl()) 7599 return std::make_pair(ImplicitExceptionSpecification(Context), false); 7600 7601 // C++ [class.copy]p10: 7602 // If the class definition does not explicitly declare a copy 7603 // assignment operator, one is declared implicitly. 7604 // The implicitly-defined copy assignment operator for a class X 7605 // will have the form 7606 // 7607 // X& X::operator=(const X&) 7608 // 7609 // if 7610 bool HasConstCopyAssignment = true; 7611 7612 // -- each direct base class B of X has a copy assignment operator 7613 // whose parameter is of type const B&, const volatile B& or B, 7614 // and 7615 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7616 BaseEnd = ClassDecl->bases_end(); 7617 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7618 // We'll handle this below 7619 if (LangOpts.CPlusPlus0x && Base->isVirtual()) 7620 continue; 7621 7622 assert(!Base->getType()->isDependentType() && 7623 "Cannot generate implicit members for class with dependent bases."); 7624 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7625 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7626 &HasConstCopyAssignment); 7627 } 7628 7629 // In C++0x, the above citation has "or virtual added" 7630 if (LangOpts.CPlusPlus0x) { 7631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7632 BaseEnd = ClassDecl->vbases_end(); 7633 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7634 assert(!Base->getType()->isDependentType() && 7635 "Cannot generate implicit members for class with dependent bases."); 7636 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7637 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7638 &HasConstCopyAssignment); 7639 } 7640 } 7641 7642 // -- for all the nonstatic data members of X that are of a class 7643 // type M (or array thereof), each such class type has a copy 7644 // assignment operator whose parameter is of type const M&, 7645 // const volatile M& or M. 7646 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7647 FieldEnd = ClassDecl->field_end(); 7648 HasConstCopyAssignment && Field != FieldEnd; 7649 ++Field) { 7650 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7651 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7652 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0, 7653 &HasConstCopyAssignment); 7654 } 7655 } 7656 7657 // Otherwise, the implicitly declared copy assignment operator will 7658 // have the form 7659 // 7660 // X& X::operator=(X&) 7661 7662 // C++ [except.spec]p14: 7663 // An implicitly declared special member function (Clause 12) shall have an 7664 // exception-specification. [...] 7665 7666 // It is unspecified whether or not an implicit copy assignment operator 7667 // attempts to deduplicate calls to assignment operators of virtual bases are 7668 // made. As such, this exception specification is effectively unspecified. 7669 // Based on a similar decision made for constness in C++0x, we're erring on 7670 // the side of assuming such calls to be made regardless of whether they 7671 // actually happen. 7672 ImplicitExceptionSpecification ExceptSpec(Context); 7673 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0; 7674 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7675 BaseEnd = ClassDecl->bases_end(); 7676 Base != BaseEnd; ++Base) { 7677 if (Base->isVirtual()) 7678 continue; 7679 7680 CXXRecordDecl *BaseClassDecl 7681 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7682 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7683 ArgQuals, false, 0)) 7684 ExceptSpec.CalledDecl(CopyAssign); 7685 } 7686 7687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7688 BaseEnd = ClassDecl->vbases_end(); 7689 Base != BaseEnd; ++Base) { 7690 CXXRecordDecl *BaseClassDecl 7691 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7692 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7693 ArgQuals, false, 0)) 7694 ExceptSpec.CalledDecl(CopyAssign); 7695 } 7696 7697 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7698 FieldEnd = ClassDecl->field_end(); 7699 Field != FieldEnd; 7700 ++Field) { 7701 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7702 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7703 if (CXXMethodDecl *CopyAssign = 7704 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0)) 7705 ExceptSpec.CalledDecl(CopyAssign); 7706 } 7707 } 7708 7709 return std::make_pair(ExceptSpec, HasConstCopyAssignment); 7710} 7711 7712CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7713 // Note: The following rules are largely analoguous to the copy 7714 // constructor rules. Note that virtual bases are not taken into account 7715 // for determining the argument type of the operator. Note also that 7716 // operators taking an object instead of a reference are allowed. 7717 7718 ImplicitExceptionSpecification Spec(Context); 7719 bool Const; 7720 llvm::tie(Spec, Const) = 7721 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl); 7722 7723 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7724 QualType RetType = Context.getLValueReferenceType(ArgType); 7725 if (Const) 7726 ArgType = ArgType.withConst(); 7727 ArgType = Context.getLValueReferenceType(ArgType); 7728 7729 // An implicitly-declared copy assignment operator is an inline public 7730 // member of its class. 7731 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7732 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7733 SourceLocation ClassLoc = ClassDecl->getLocation(); 7734 DeclarationNameInfo NameInfo(Name, ClassLoc); 7735 CXXMethodDecl *CopyAssignment 7736 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7737 Context.getFunctionType(RetType, &ArgType, 1, EPI), 7738 /*TInfo=*/0, /*isStatic=*/false, 7739 /*StorageClassAsWritten=*/SC_None, 7740 /*isInline=*/true, /*isConstexpr=*/false, 7741 SourceLocation()); 7742 CopyAssignment->setAccess(AS_public); 7743 CopyAssignment->setDefaulted(); 7744 CopyAssignment->setImplicit(); 7745 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7746 7747 // Add the parameter to the operator. 7748 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7749 ClassLoc, ClassLoc, /*Id=*/0, 7750 ArgType, /*TInfo=*/0, 7751 SC_None, 7752 SC_None, 0); 7753 CopyAssignment->setParams(FromParam); 7754 7755 // Note that we have added this copy-assignment operator. 7756 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7757 7758 if (Scope *S = getScopeForContext(ClassDecl)) 7759 PushOnScopeChains(CopyAssignment, S, false); 7760 ClassDecl->addDecl(CopyAssignment); 7761 7762 // C++0x [class.copy]p18: 7763 // ... If the class definition declares a move constructor or move 7764 // assignment operator, the implicitly declared copy assignment operator is 7765 // defined as deleted; ... 7766 if (ClassDecl->hasUserDeclaredMoveConstructor() || 7767 ClassDecl->hasUserDeclaredMoveAssignment() || 7768 ShouldDeleteCopyAssignmentOperator(CopyAssignment)) 7769 CopyAssignment->setDeletedAsWritten(); 7770 7771 AddOverriddenMethods(ClassDecl, CopyAssignment); 7772 return CopyAssignment; 7773} 7774 7775void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7776 CXXMethodDecl *CopyAssignOperator) { 7777 assert((CopyAssignOperator->isDefaulted() && 7778 CopyAssignOperator->isOverloadedOperator() && 7779 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7780 !CopyAssignOperator->doesThisDeclarationHaveABody()) && 7781 "DefineImplicitCopyAssignment called for wrong function"); 7782 7783 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7784 7785 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7786 CopyAssignOperator->setInvalidDecl(); 7787 return; 7788 } 7789 7790 CopyAssignOperator->setUsed(); 7791 7792 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7793 DiagnosticErrorTrap Trap(Diags); 7794 7795 // C++0x [class.copy]p30: 7796 // The implicitly-defined or explicitly-defaulted copy assignment operator 7797 // for a non-union class X performs memberwise copy assignment of its 7798 // subobjects. The direct base classes of X are assigned first, in the 7799 // order of their declaration in the base-specifier-list, and then the 7800 // immediate non-static data members of X are assigned, in the order in 7801 // which they were declared in the class definition. 7802 7803 // The statements that form the synthesized function body. 7804 ASTOwningVector<Stmt*> Statements(*this); 7805 7806 // The parameter for the "other" object, which we are copying from. 7807 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7808 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7809 QualType OtherRefType = Other->getType(); 7810 if (const LValueReferenceType *OtherRef 7811 = OtherRefType->getAs<LValueReferenceType>()) { 7812 OtherRefType = OtherRef->getPointeeType(); 7813 OtherQuals = OtherRefType.getQualifiers(); 7814 } 7815 7816 // Our location for everything implicitly-generated. 7817 SourceLocation Loc = CopyAssignOperator->getLocation(); 7818 7819 // Construct a reference to the "other" object. We'll be using this 7820 // throughout the generated ASTs. 7821 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7822 assert(OtherRef && "Reference to parameter cannot fail!"); 7823 7824 // Construct the "this" pointer. We'll be using this throughout the generated 7825 // ASTs. 7826 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7827 assert(This && "Reference to this cannot fail!"); 7828 7829 // Assign base classes. 7830 bool Invalid = false; 7831 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7832 E = ClassDecl->bases_end(); Base != E; ++Base) { 7833 // Form the assignment: 7834 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 7835 QualType BaseType = Base->getType().getUnqualifiedType(); 7836 if (!BaseType->isRecordType()) { 7837 Invalid = true; 7838 continue; 7839 } 7840 7841 CXXCastPath BasePath; 7842 BasePath.push_back(Base); 7843 7844 // Construct the "from" expression, which is an implicit cast to the 7845 // appropriately-qualified base type. 7846 Expr *From = OtherRef; 7847 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 7848 CK_UncheckedDerivedToBase, 7849 VK_LValue, &BasePath).take(); 7850 7851 // Dereference "this". 7852 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7853 7854 // Implicitly cast "this" to the appropriately-qualified base type. 7855 To = ImpCastExprToType(To.take(), 7856 Context.getCVRQualifiedType(BaseType, 7857 CopyAssignOperator->getTypeQualifiers()), 7858 CK_UncheckedDerivedToBase, 7859 VK_LValue, &BasePath); 7860 7861 // Build the copy. 7862 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 7863 To.get(), From, 7864 /*CopyingBaseSubobject=*/true, 7865 /*Copying=*/true); 7866 if (Copy.isInvalid()) { 7867 Diag(CurrentLocation, diag::note_member_synthesized_at) 7868 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7869 CopyAssignOperator->setInvalidDecl(); 7870 return; 7871 } 7872 7873 // Success! Record the copy. 7874 Statements.push_back(Copy.takeAs<Expr>()); 7875 } 7876 7877 // \brief Reference to the __builtin_memcpy function. 7878 Expr *BuiltinMemCpyRef = 0; 7879 // \brief Reference to the __builtin_objc_memmove_collectable function. 7880 Expr *CollectableMemCpyRef = 0; 7881 7882 // Assign non-static members. 7883 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7884 FieldEnd = ClassDecl->field_end(); 7885 Field != FieldEnd; ++Field) { 7886 // Check for members of reference type; we can't copy those. 7887 if (Field->getType()->isReferenceType()) { 7888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7889 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7890 Diag(Field->getLocation(), diag::note_declared_at); 7891 Diag(CurrentLocation, diag::note_member_synthesized_at) 7892 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7893 Invalid = true; 7894 continue; 7895 } 7896 7897 // Check for members of const-qualified, non-class type. 7898 QualType BaseType = Context.getBaseElementType(Field->getType()); 7899 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7900 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7901 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7902 Diag(Field->getLocation(), diag::note_declared_at); 7903 Diag(CurrentLocation, diag::note_member_synthesized_at) 7904 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7905 Invalid = true; 7906 continue; 7907 } 7908 7909 // Suppress assigning zero-width bitfields. 7910 if (const Expr *Width = Field->getBitWidth()) 7911 if (Width->EvaluateAsInt(Context) == 0) 7912 continue; 7913 7914 QualType FieldType = Field->getType().getNonReferenceType(); 7915 if (FieldType->isIncompleteArrayType()) { 7916 assert(ClassDecl->hasFlexibleArrayMember() && 7917 "Incomplete array type is not valid"); 7918 continue; 7919 } 7920 7921 // Build references to the field in the object we're copying from and to. 7922 CXXScopeSpec SS; // Intentionally empty 7923 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7924 LookupMemberName); 7925 MemberLookup.addDecl(*Field); 7926 MemberLookup.resolveKind(); 7927 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7928 Loc, /*IsArrow=*/false, 7929 SS, 0, MemberLookup, 0); 7930 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7931 Loc, /*IsArrow=*/true, 7932 SS, 0, MemberLookup, 0); 7933 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7934 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7935 7936 // If the field should be copied with __builtin_memcpy rather than via 7937 // explicit assignments, do so. This optimization only applies for arrays 7938 // of scalars and arrays of class type with trivial copy-assignment 7939 // operators. 7940 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7941 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 7942 // Compute the size of the memory buffer to be copied. 7943 QualType SizeType = Context.getSizeType(); 7944 llvm::APInt Size(Context.getTypeSize(SizeType), 7945 Context.getTypeSizeInChars(BaseType).getQuantity()); 7946 for (const ConstantArrayType *Array 7947 = Context.getAsConstantArrayType(FieldType); 7948 Array; 7949 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7950 llvm::APInt ArraySize 7951 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7952 Size *= ArraySize; 7953 } 7954 7955 // Take the address of the field references for "from" and "to". 7956 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 7957 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 7958 7959 bool NeedsCollectableMemCpy = 7960 (BaseType->isRecordType() && 7961 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7962 7963 if (NeedsCollectableMemCpy) { 7964 if (!CollectableMemCpyRef) { 7965 // Create a reference to the __builtin_objc_memmove_collectable function. 7966 LookupResult R(*this, 7967 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7968 Loc, LookupOrdinaryName); 7969 LookupName(R, TUScope, true); 7970 7971 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7972 if (!CollectableMemCpy) { 7973 // Something went horribly wrong earlier, and we will have 7974 // complained about it. 7975 Invalid = true; 7976 continue; 7977 } 7978 7979 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7980 CollectableMemCpy->getType(), 7981 VK_LValue, Loc, 0).take(); 7982 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7983 } 7984 } 7985 // Create a reference to the __builtin_memcpy builtin function. 7986 else if (!BuiltinMemCpyRef) { 7987 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7988 LookupOrdinaryName); 7989 LookupName(R, TUScope, true); 7990 7991 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 7992 if (!BuiltinMemCpy) { 7993 // Something went horribly wrong earlier, and we will have complained 7994 // about it. 7995 Invalid = true; 7996 continue; 7997 } 7998 7999 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8000 BuiltinMemCpy->getType(), 8001 VK_LValue, Loc, 0).take(); 8002 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8003 } 8004 8005 ASTOwningVector<Expr*> CallArgs(*this); 8006 CallArgs.push_back(To.takeAs<Expr>()); 8007 CallArgs.push_back(From.takeAs<Expr>()); 8008 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8009 ExprResult Call = ExprError(); 8010 if (NeedsCollectableMemCpy) 8011 Call = ActOnCallExpr(/*Scope=*/0, 8012 CollectableMemCpyRef, 8013 Loc, move_arg(CallArgs), 8014 Loc); 8015 else 8016 Call = ActOnCallExpr(/*Scope=*/0, 8017 BuiltinMemCpyRef, 8018 Loc, move_arg(CallArgs), 8019 Loc); 8020 8021 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8022 Statements.push_back(Call.takeAs<Expr>()); 8023 continue; 8024 } 8025 8026 // Build the copy of this field. 8027 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 8028 To.get(), From.get(), 8029 /*CopyingBaseSubobject=*/false, 8030 /*Copying=*/true); 8031 if (Copy.isInvalid()) { 8032 Diag(CurrentLocation, diag::note_member_synthesized_at) 8033 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8034 CopyAssignOperator->setInvalidDecl(); 8035 return; 8036 } 8037 8038 // Success! Record the copy. 8039 Statements.push_back(Copy.takeAs<Stmt>()); 8040 } 8041 8042 if (!Invalid) { 8043 // Add a "return *this;" 8044 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8045 8046 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8047 if (Return.isInvalid()) 8048 Invalid = true; 8049 else { 8050 Statements.push_back(Return.takeAs<Stmt>()); 8051 8052 if (Trap.hasErrorOccurred()) { 8053 Diag(CurrentLocation, diag::note_member_synthesized_at) 8054 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8055 Invalid = true; 8056 } 8057 } 8058 } 8059 8060 if (Invalid) { 8061 CopyAssignOperator->setInvalidDecl(); 8062 return; 8063 } 8064 8065 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8066 /*isStmtExpr=*/false); 8067 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8068 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 8069 8070 if (ASTMutationListener *L = getASTMutationListener()) { 8071 L->CompletedImplicitDefinition(CopyAssignOperator); 8072 } 8073} 8074 8075Sema::ImplicitExceptionSpecification 8076Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) { 8077 ImplicitExceptionSpecification ExceptSpec(Context); 8078 8079 if (ClassDecl->isInvalidDecl()) 8080 return ExceptSpec; 8081 8082 // C++0x [except.spec]p14: 8083 // An implicitly declared special member function (Clause 12) shall have an 8084 // exception-specification. [...] 8085 8086 // It is unspecified whether or not an implicit move assignment operator 8087 // attempts to deduplicate calls to assignment operators of virtual bases are 8088 // made. As such, this exception specification is effectively unspecified. 8089 // Based on a similar decision made for constness in C++0x, we're erring on 8090 // the side of assuming such calls to be made regardless of whether they 8091 // actually happen. 8092 // Note that a move constructor is not implicitly declared when there are 8093 // virtual bases, but it can still be user-declared and explicitly defaulted. 8094 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8095 BaseEnd = ClassDecl->bases_end(); 8096 Base != BaseEnd; ++Base) { 8097 if (Base->isVirtual()) 8098 continue; 8099 8100 CXXRecordDecl *BaseClassDecl 8101 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8102 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8103 false, 0)) 8104 ExceptSpec.CalledDecl(MoveAssign); 8105 } 8106 8107 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8108 BaseEnd = ClassDecl->vbases_end(); 8109 Base != BaseEnd; ++Base) { 8110 CXXRecordDecl *BaseClassDecl 8111 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8112 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 8113 false, 0)) 8114 ExceptSpec.CalledDecl(MoveAssign); 8115 } 8116 8117 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8118 FieldEnd = ClassDecl->field_end(); 8119 Field != FieldEnd; 8120 ++Field) { 8121 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8122 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8123 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl, 8124 false, 0)) 8125 ExceptSpec.CalledDecl(MoveAssign); 8126 } 8127 } 8128 8129 return ExceptSpec; 8130} 8131 8132CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8133 // Note: The following rules are largely analoguous to the move 8134 // constructor rules. 8135 8136 ImplicitExceptionSpecification Spec( 8137 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl)); 8138 8139 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8140 QualType RetType = Context.getLValueReferenceType(ArgType); 8141 ArgType = Context.getRValueReferenceType(ArgType); 8142 8143 // An implicitly-declared move assignment operator is an inline public 8144 // member of its class. 8145 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8146 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8147 SourceLocation ClassLoc = ClassDecl->getLocation(); 8148 DeclarationNameInfo NameInfo(Name, ClassLoc); 8149 CXXMethodDecl *MoveAssignment 8150 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8151 Context.getFunctionType(RetType, &ArgType, 1, EPI), 8152 /*TInfo=*/0, /*isStatic=*/false, 8153 /*StorageClassAsWritten=*/SC_None, 8154 /*isInline=*/true, 8155 /*isConstexpr=*/false, 8156 SourceLocation()); 8157 MoveAssignment->setAccess(AS_public); 8158 MoveAssignment->setDefaulted(); 8159 MoveAssignment->setImplicit(); 8160 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8161 8162 // Add the parameter to the operator. 8163 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8164 ClassLoc, ClassLoc, /*Id=*/0, 8165 ArgType, /*TInfo=*/0, 8166 SC_None, 8167 SC_None, 0); 8168 MoveAssignment->setParams(FromParam); 8169 8170 // Note that we have added this copy-assignment operator. 8171 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8172 8173 // C++0x [class.copy]p9: 8174 // If the definition of a class X does not explicitly declare a move 8175 // assignment operator, one will be implicitly declared as defaulted if and 8176 // only if: 8177 // [...] 8178 // - the move assignment operator would not be implicitly defined as 8179 // deleted. 8180 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) { 8181 // Cache this result so that we don't try to generate this over and over 8182 // on every lookup, leaking memory and wasting time. 8183 ClassDecl->setFailedImplicitMoveAssignment(); 8184 return 0; 8185 } 8186 8187 if (Scope *S = getScopeForContext(ClassDecl)) 8188 PushOnScopeChains(MoveAssignment, S, false); 8189 ClassDecl->addDecl(MoveAssignment); 8190 8191 AddOverriddenMethods(ClassDecl, MoveAssignment); 8192 return MoveAssignment; 8193} 8194 8195void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8196 CXXMethodDecl *MoveAssignOperator) { 8197 assert((MoveAssignOperator->isDefaulted() && 8198 MoveAssignOperator->isOverloadedOperator() && 8199 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8200 !MoveAssignOperator->doesThisDeclarationHaveABody()) && 8201 "DefineImplicitMoveAssignment called for wrong function"); 8202 8203 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8204 8205 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8206 MoveAssignOperator->setInvalidDecl(); 8207 return; 8208 } 8209 8210 MoveAssignOperator->setUsed(); 8211 8212 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8213 DiagnosticErrorTrap Trap(Diags); 8214 8215 // C++0x [class.copy]p28: 8216 // The implicitly-defined or move assignment operator for a non-union class 8217 // X performs memberwise move assignment of its subobjects. The direct base 8218 // classes of X are assigned first, in the order of their declaration in the 8219 // base-specifier-list, and then the immediate non-static data members of X 8220 // are assigned, in the order in which they were declared in the class 8221 // definition. 8222 8223 // The statements that form the synthesized function body. 8224 ASTOwningVector<Stmt*> Statements(*this); 8225 8226 // The parameter for the "other" object, which we are move from. 8227 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8228 QualType OtherRefType = Other->getType()-> 8229 getAs<RValueReferenceType>()->getPointeeType(); 8230 assert(OtherRefType.getQualifiers() == 0 && 8231 "Bad argument type of defaulted move assignment"); 8232 8233 // Our location for everything implicitly-generated. 8234 SourceLocation Loc = MoveAssignOperator->getLocation(); 8235 8236 // Construct a reference to the "other" object. We'll be using this 8237 // throughout the generated ASTs. 8238 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8239 assert(OtherRef && "Reference to parameter cannot fail!"); 8240 // Cast to rvalue. 8241 OtherRef = CastForMoving(*this, OtherRef); 8242 8243 // Construct the "this" pointer. We'll be using this throughout the generated 8244 // ASTs. 8245 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8246 assert(This && "Reference to this cannot fail!"); 8247 8248 // Assign base classes. 8249 bool Invalid = false; 8250 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8251 E = ClassDecl->bases_end(); Base != E; ++Base) { 8252 // Form the assignment: 8253 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8254 QualType BaseType = Base->getType().getUnqualifiedType(); 8255 if (!BaseType->isRecordType()) { 8256 Invalid = true; 8257 continue; 8258 } 8259 8260 CXXCastPath BasePath; 8261 BasePath.push_back(Base); 8262 8263 // Construct the "from" expression, which is an implicit cast to the 8264 // appropriately-qualified base type. 8265 Expr *From = OtherRef; 8266 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8267 VK_XValue, &BasePath).take(); 8268 8269 // Dereference "this". 8270 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8271 8272 // Implicitly cast "this" to the appropriately-qualified base type. 8273 To = ImpCastExprToType(To.take(), 8274 Context.getCVRQualifiedType(BaseType, 8275 MoveAssignOperator->getTypeQualifiers()), 8276 CK_UncheckedDerivedToBase, 8277 VK_LValue, &BasePath); 8278 8279 // Build the move. 8280 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8281 To.get(), From, 8282 /*CopyingBaseSubobject=*/true, 8283 /*Copying=*/false); 8284 if (Move.isInvalid()) { 8285 Diag(CurrentLocation, diag::note_member_synthesized_at) 8286 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8287 MoveAssignOperator->setInvalidDecl(); 8288 return; 8289 } 8290 8291 // Success! Record the move. 8292 Statements.push_back(Move.takeAs<Expr>()); 8293 } 8294 8295 // \brief Reference to the __builtin_memcpy function. 8296 Expr *BuiltinMemCpyRef = 0; 8297 // \brief Reference to the __builtin_objc_memmove_collectable function. 8298 Expr *CollectableMemCpyRef = 0; 8299 8300 // Assign non-static members. 8301 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8302 FieldEnd = ClassDecl->field_end(); 8303 Field != FieldEnd; ++Field) { 8304 // Check for members of reference type; we can't move those. 8305 if (Field->getType()->isReferenceType()) { 8306 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8307 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8308 Diag(Field->getLocation(), diag::note_declared_at); 8309 Diag(CurrentLocation, diag::note_member_synthesized_at) 8310 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8311 Invalid = true; 8312 continue; 8313 } 8314 8315 // Check for members of const-qualified, non-class type. 8316 QualType BaseType = Context.getBaseElementType(Field->getType()); 8317 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8318 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8319 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8320 Diag(Field->getLocation(), diag::note_declared_at); 8321 Diag(CurrentLocation, diag::note_member_synthesized_at) 8322 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8323 Invalid = true; 8324 continue; 8325 } 8326 8327 // Suppress assigning zero-width bitfields. 8328 if (const Expr *Width = Field->getBitWidth()) 8329 if (Width->EvaluateAsInt(Context) == 0) 8330 continue; 8331 8332 QualType FieldType = Field->getType().getNonReferenceType(); 8333 if (FieldType->isIncompleteArrayType()) { 8334 assert(ClassDecl->hasFlexibleArrayMember() && 8335 "Incomplete array type is not valid"); 8336 continue; 8337 } 8338 8339 // Build references to the field in the object we're copying from and to. 8340 CXXScopeSpec SS; // Intentionally empty 8341 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8342 LookupMemberName); 8343 MemberLookup.addDecl(*Field); 8344 MemberLookup.resolveKind(); 8345 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8346 Loc, /*IsArrow=*/false, 8347 SS, 0, MemberLookup, 0); 8348 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8349 Loc, /*IsArrow=*/true, 8350 SS, 0, MemberLookup, 0); 8351 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8352 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8353 8354 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8355 "Member reference with rvalue base must be rvalue except for reference " 8356 "members, which aren't allowed for move assignment."); 8357 8358 // If the field should be copied with __builtin_memcpy rather than via 8359 // explicit assignments, do so. This optimization only applies for arrays 8360 // of scalars and arrays of class type with trivial move-assignment 8361 // operators. 8362 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8363 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8364 // Compute the size of the memory buffer to be copied. 8365 QualType SizeType = Context.getSizeType(); 8366 llvm::APInt Size(Context.getTypeSize(SizeType), 8367 Context.getTypeSizeInChars(BaseType).getQuantity()); 8368 for (const ConstantArrayType *Array 8369 = Context.getAsConstantArrayType(FieldType); 8370 Array; 8371 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8372 llvm::APInt ArraySize 8373 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8374 Size *= ArraySize; 8375 } 8376 8377 // Take the address of the field references for "from" and "to". We 8378 // directly construct UnaryOperators here because semantic analysis 8379 // does not permit us to take the address of an xvalue. 8380 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8381 Context.getPointerType(From.get()->getType()), 8382 VK_RValue, OK_Ordinary, Loc); 8383 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8384 Context.getPointerType(To.get()->getType()), 8385 VK_RValue, OK_Ordinary, Loc); 8386 8387 bool NeedsCollectableMemCpy = 8388 (BaseType->isRecordType() && 8389 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8390 8391 if (NeedsCollectableMemCpy) { 8392 if (!CollectableMemCpyRef) { 8393 // Create a reference to the __builtin_objc_memmove_collectable function. 8394 LookupResult R(*this, 8395 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8396 Loc, LookupOrdinaryName); 8397 LookupName(R, TUScope, true); 8398 8399 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8400 if (!CollectableMemCpy) { 8401 // Something went horribly wrong earlier, and we will have 8402 // complained about it. 8403 Invalid = true; 8404 continue; 8405 } 8406 8407 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8408 CollectableMemCpy->getType(), 8409 VK_LValue, Loc, 0).take(); 8410 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8411 } 8412 } 8413 // Create a reference to the __builtin_memcpy builtin function. 8414 else if (!BuiltinMemCpyRef) { 8415 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8416 LookupOrdinaryName); 8417 LookupName(R, TUScope, true); 8418 8419 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8420 if (!BuiltinMemCpy) { 8421 // Something went horribly wrong earlier, and we will have complained 8422 // about it. 8423 Invalid = true; 8424 continue; 8425 } 8426 8427 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8428 BuiltinMemCpy->getType(), 8429 VK_LValue, Loc, 0).take(); 8430 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8431 } 8432 8433 ASTOwningVector<Expr*> CallArgs(*this); 8434 CallArgs.push_back(To.takeAs<Expr>()); 8435 CallArgs.push_back(From.takeAs<Expr>()); 8436 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8437 ExprResult Call = ExprError(); 8438 if (NeedsCollectableMemCpy) 8439 Call = ActOnCallExpr(/*Scope=*/0, 8440 CollectableMemCpyRef, 8441 Loc, move_arg(CallArgs), 8442 Loc); 8443 else 8444 Call = ActOnCallExpr(/*Scope=*/0, 8445 BuiltinMemCpyRef, 8446 Loc, move_arg(CallArgs), 8447 Loc); 8448 8449 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8450 Statements.push_back(Call.takeAs<Expr>()); 8451 continue; 8452 } 8453 8454 // Build the move of this field. 8455 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8456 To.get(), From.get(), 8457 /*CopyingBaseSubobject=*/false, 8458 /*Copying=*/false); 8459 if (Move.isInvalid()) { 8460 Diag(CurrentLocation, diag::note_member_synthesized_at) 8461 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8462 MoveAssignOperator->setInvalidDecl(); 8463 return; 8464 } 8465 8466 // Success! Record the copy. 8467 Statements.push_back(Move.takeAs<Stmt>()); 8468 } 8469 8470 if (!Invalid) { 8471 // Add a "return *this;" 8472 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8473 8474 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8475 if (Return.isInvalid()) 8476 Invalid = true; 8477 else { 8478 Statements.push_back(Return.takeAs<Stmt>()); 8479 8480 if (Trap.hasErrorOccurred()) { 8481 Diag(CurrentLocation, diag::note_member_synthesized_at) 8482 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8483 Invalid = true; 8484 } 8485 } 8486 } 8487 8488 if (Invalid) { 8489 MoveAssignOperator->setInvalidDecl(); 8490 return; 8491 } 8492 8493 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8494 /*isStmtExpr=*/false); 8495 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8496 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8497 8498 if (ASTMutationListener *L = getASTMutationListener()) { 8499 L->CompletedImplicitDefinition(MoveAssignOperator); 8500 } 8501} 8502 8503std::pair<Sema::ImplicitExceptionSpecification, bool> 8504Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) { 8505 if (ClassDecl->isInvalidDecl()) 8506 return std::make_pair(ImplicitExceptionSpecification(Context), false); 8507 8508 // C++ [class.copy]p5: 8509 // The implicitly-declared copy constructor for a class X will 8510 // have the form 8511 // 8512 // X::X(const X&) 8513 // 8514 // if 8515 // FIXME: It ought to be possible to store this on the record. 8516 bool HasConstCopyConstructor = true; 8517 8518 // -- each direct or virtual base class B of X has a copy 8519 // constructor whose first parameter is of type const B& or 8520 // const volatile B&, and 8521 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8522 BaseEnd = ClassDecl->bases_end(); 8523 HasConstCopyConstructor && Base != BaseEnd; 8524 ++Base) { 8525 // Virtual bases are handled below. 8526 if (Base->isVirtual()) 8527 continue; 8528 8529 CXXRecordDecl *BaseClassDecl 8530 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8531 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8532 &HasConstCopyConstructor); 8533 } 8534 8535 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8536 BaseEnd = ClassDecl->vbases_end(); 8537 HasConstCopyConstructor && Base != BaseEnd; 8538 ++Base) { 8539 CXXRecordDecl *BaseClassDecl 8540 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8541 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8542 &HasConstCopyConstructor); 8543 } 8544 8545 // -- for all the nonstatic data members of X that are of a 8546 // class type M (or array thereof), each such class type 8547 // has a copy constructor whose first parameter is of type 8548 // const M& or const volatile M&. 8549 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8550 FieldEnd = ClassDecl->field_end(); 8551 HasConstCopyConstructor && Field != FieldEnd; 8552 ++Field) { 8553 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8554 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8555 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const, 8556 &HasConstCopyConstructor); 8557 } 8558 } 8559 // Otherwise, the implicitly declared copy constructor will have 8560 // the form 8561 // 8562 // X::X(X&) 8563 8564 // C++ [except.spec]p14: 8565 // An implicitly declared special member function (Clause 12) shall have an 8566 // exception-specification. [...] 8567 ImplicitExceptionSpecification ExceptSpec(Context); 8568 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 8569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8570 BaseEnd = ClassDecl->bases_end(); 8571 Base != BaseEnd; 8572 ++Base) { 8573 // Virtual bases are handled below. 8574 if (Base->isVirtual()) 8575 continue; 8576 8577 CXXRecordDecl *BaseClassDecl 8578 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8579 if (CXXConstructorDecl *CopyConstructor = 8580 LookupCopyingConstructor(BaseClassDecl, Quals)) 8581 ExceptSpec.CalledDecl(CopyConstructor); 8582 } 8583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8584 BaseEnd = ClassDecl->vbases_end(); 8585 Base != BaseEnd; 8586 ++Base) { 8587 CXXRecordDecl *BaseClassDecl 8588 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8589 if (CXXConstructorDecl *CopyConstructor = 8590 LookupCopyingConstructor(BaseClassDecl, Quals)) 8591 ExceptSpec.CalledDecl(CopyConstructor); 8592 } 8593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8594 FieldEnd = ClassDecl->field_end(); 8595 Field != FieldEnd; 8596 ++Field) { 8597 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8598 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8599 if (CXXConstructorDecl *CopyConstructor = 8600 LookupCopyingConstructor(FieldClassDecl, Quals)) 8601 ExceptSpec.CalledDecl(CopyConstructor); 8602 } 8603 } 8604 8605 return std::make_pair(ExceptSpec, HasConstCopyConstructor); 8606} 8607 8608CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8609 CXXRecordDecl *ClassDecl) { 8610 // C++ [class.copy]p4: 8611 // If the class definition does not explicitly declare a copy 8612 // constructor, one is declared implicitly. 8613 8614 ImplicitExceptionSpecification Spec(Context); 8615 bool Const; 8616 llvm::tie(Spec, Const) = 8617 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl); 8618 8619 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8620 QualType ArgType = ClassType; 8621 if (Const) 8622 ArgType = ArgType.withConst(); 8623 ArgType = Context.getLValueReferenceType(ArgType); 8624 8625 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8626 8627 DeclarationName Name 8628 = Context.DeclarationNames.getCXXConstructorName( 8629 Context.getCanonicalType(ClassType)); 8630 SourceLocation ClassLoc = ClassDecl->getLocation(); 8631 DeclarationNameInfo NameInfo(Name, ClassLoc); 8632 8633 // An implicitly-declared copy constructor is an inline public 8634 // member of its class. 8635 CXXConstructorDecl *CopyConstructor 8636 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8637 Context.getFunctionType(Context.VoidTy, 8638 &ArgType, 1, EPI), 8639 /*TInfo=*/0, 8640 /*isExplicit=*/false, 8641 /*isInline=*/true, 8642 /*isImplicitlyDeclared=*/true, 8643 // FIXME: apply the rules for definitions here 8644 /*isConstexpr=*/false); 8645 CopyConstructor->setAccess(AS_public); 8646 CopyConstructor->setDefaulted(); 8647 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8648 8649 // Note that we have declared this constructor. 8650 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8651 8652 // Add the parameter to the constructor. 8653 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8654 ClassLoc, ClassLoc, 8655 /*IdentifierInfo=*/0, 8656 ArgType, /*TInfo=*/0, 8657 SC_None, 8658 SC_None, 0); 8659 CopyConstructor->setParams(FromParam); 8660 8661 if (Scope *S = getScopeForContext(ClassDecl)) 8662 PushOnScopeChains(CopyConstructor, S, false); 8663 ClassDecl->addDecl(CopyConstructor); 8664 8665 // C++0x [class.copy]p7: 8666 // ... If the class definition declares a move constructor or move 8667 // assignment operator, the implicitly declared constructor is defined as 8668 // deleted; ... 8669 if (ClassDecl->hasUserDeclaredMoveConstructor() || 8670 ClassDecl->hasUserDeclaredMoveAssignment() || 8671 ShouldDeleteCopyConstructor(CopyConstructor)) 8672 CopyConstructor->setDeletedAsWritten(); 8673 8674 return CopyConstructor; 8675} 8676 8677void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8678 CXXConstructorDecl *CopyConstructor) { 8679 assert((CopyConstructor->isDefaulted() && 8680 CopyConstructor->isCopyConstructor() && 8681 !CopyConstructor->doesThisDeclarationHaveABody()) && 8682 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8683 8684 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8685 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8686 8687 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8688 DiagnosticErrorTrap Trap(Diags); 8689 8690 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8691 Trap.hasErrorOccurred()) { 8692 Diag(CurrentLocation, diag::note_member_synthesized_at) 8693 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8694 CopyConstructor->setInvalidDecl(); 8695 } else { 8696 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8697 CopyConstructor->getLocation(), 8698 MultiStmtArg(*this, 0, 0), 8699 /*isStmtExpr=*/false) 8700 .takeAs<Stmt>()); 8701 CopyConstructor->setImplicitlyDefined(true); 8702 } 8703 8704 CopyConstructor->setUsed(); 8705 if (ASTMutationListener *L = getASTMutationListener()) { 8706 L->CompletedImplicitDefinition(CopyConstructor); 8707 } 8708} 8709 8710Sema::ImplicitExceptionSpecification 8711Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 8712 // C++ [except.spec]p14: 8713 // An implicitly declared special member function (Clause 12) shall have an 8714 // exception-specification. [...] 8715 ImplicitExceptionSpecification ExceptSpec(Context); 8716 if (ClassDecl->isInvalidDecl()) 8717 return ExceptSpec; 8718 8719 // Direct base-class constructors. 8720 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8721 BEnd = ClassDecl->bases_end(); 8722 B != BEnd; ++B) { 8723 if (B->isVirtual()) // Handled below. 8724 continue; 8725 8726 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8727 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8728 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8729 // If this is a deleted function, add it anyway. This might be conformant 8730 // with the standard. This might not. I'm not sure. It might not matter. 8731 if (Constructor) 8732 ExceptSpec.CalledDecl(Constructor); 8733 } 8734 } 8735 8736 // Virtual base-class constructors. 8737 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8738 BEnd = ClassDecl->vbases_end(); 8739 B != BEnd; ++B) { 8740 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8741 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8742 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8743 // If this is a deleted function, add it anyway. This might be conformant 8744 // with the standard. This might not. I'm not sure. It might not matter. 8745 if (Constructor) 8746 ExceptSpec.CalledDecl(Constructor); 8747 } 8748 } 8749 8750 // Field constructors. 8751 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8752 FEnd = ClassDecl->field_end(); 8753 F != FEnd; ++F) { 8754 if (F->hasInClassInitializer()) { 8755 if (Expr *E = F->getInClassInitializer()) 8756 ExceptSpec.CalledExpr(E); 8757 else if (!F->isInvalidDecl()) 8758 ExceptSpec.SetDelayed(); 8759 } else if (const RecordType *RecordTy 8760 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8761 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8762 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl); 8763 // If this is a deleted function, add it anyway. This might be conformant 8764 // with the standard. This might not. I'm not sure. It might not matter. 8765 // In particular, the problem is that this function never gets called. It 8766 // might just be ill-formed because this function attempts to refer to 8767 // a deleted function here. 8768 if (Constructor) 8769 ExceptSpec.CalledDecl(Constructor); 8770 } 8771 } 8772 8773 return ExceptSpec; 8774} 8775 8776CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8777 CXXRecordDecl *ClassDecl) { 8778 ImplicitExceptionSpecification Spec( 8779 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl)); 8780 8781 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8782 QualType ArgType = Context.getRValueReferenceType(ClassType); 8783 8784 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8785 8786 DeclarationName Name 8787 = Context.DeclarationNames.getCXXConstructorName( 8788 Context.getCanonicalType(ClassType)); 8789 SourceLocation ClassLoc = ClassDecl->getLocation(); 8790 DeclarationNameInfo NameInfo(Name, ClassLoc); 8791 8792 // C++0x [class.copy]p11: 8793 // An implicitly-declared copy/move constructor is an inline public 8794 // member of its class. 8795 CXXConstructorDecl *MoveConstructor 8796 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8797 Context.getFunctionType(Context.VoidTy, 8798 &ArgType, 1, EPI), 8799 /*TInfo=*/0, 8800 /*isExplicit=*/false, 8801 /*isInline=*/true, 8802 /*isImplicitlyDeclared=*/true, 8803 // FIXME: apply the rules for definitions here 8804 /*isConstexpr=*/false); 8805 MoveConstructor->setAccess(AS_public); 8806 MoveConstructor->setDefaulted(); 8807 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8808 8809 // Add the parameter to the constructor. 8810 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8811 ClassLoc, ClassLoc, 8812 /*IdentifierInfo=*/0, 8813 ArgType, /*TInfo=*/0, 8814 SC_None, 8815 SC_None, 0); 8816 MoveConstructor->setParams(FromParam); 8817 8818 // C++0x [class.copy]p9: 8819 // If the definition of a class X does not explicitly declare a move 8820 // constructor, one will be implicitly declared as defaulted if and only if: 8821 // [...] 8822 // - the move constructor would not be implicitly defined as deleted. 8823 if (ShouldDeleteMoveConstructor(MoveConstructor)) { 8824 // Cache this result so that we don't try to generate this over and over 8825 // on every lookup, leaking memory and wasting time. 8826 ClassDecl->setFailedImplicitMoveConstructor(); 8827 return 0; 8828 } 8829 8830 // Note that we have declared this constructor. 8831 ++ASTContext::NumImplicitMoveConstructorsDeclared; 8832 8833 if (Scope *S = getScopeForContext(ClassDecl)) 8834 PushOnScopeChains(MoveConstructor, S, false); 8835 ClassDecl->addDecl(MoveConstructor); 8836 8837 return MoveConstructor; 8838} 8839 8840void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 8841 CXXConstructorDecl *MoveConstructor) { 8842 assert((MoveConstructor->isDefaulted() && 8843 MoveConstructor->isMoveConstructor() && 8844 !MoveConstructor->doesThisDeclarationHaveABody()) && 8845 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 8846 8847 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 8848 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 8849 8850 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 8851 DiagnosticErrorTrap Trap(Diags); 8852 8853 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 8854 Trap.hasErrorOccurred()) { 8855 Diag(CurrentLocation, diag::note_member_synthesized_at) 8856 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 8857 MoveConstructor->setInvalidDecl(); 8858 } else { 8859 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 8860 MoveConstructor->getLocation(), 8861 MultiStmtArg(*this, 0, 0), 8862 /*isStmtExpr=*/false) 8863 .takeAs<Stmt>()); 8864 MoveConstructor->setImplicitlyDefined(true); 8865 } 8866 8867 MoveConstructor->setUsed(); 8868 8869 if (ASTMutationListener *L = getASTMutationListener()) { 8870 L->CompletedImplicitDefinition(MoveConstructor); 8871 } 8872} 8873 8874ExprResult 8875Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 8876 CXXConstructorDecl *Constructor, 8877 MultiExprArg ExprArgs, 8878 bool HadMultipleCandidates, 8879 bool RequiresZeroInit, 8880 unsigned ConstructKind, 8881 SourceRange ParenRange) { 8882 bool Elidable = false; 8883 8884 // C++0x [class.copy]p34: 8885 // When certain criteria are met, an implementation is allowed to 8886 // omit the copy/move construction of a class object, even if the 8887 // copy/move constructor and/or destructor for the object have 8888 // side effects. [...] 8889 // - when a temporary class object that has not been bound to a 8890 // reference (12.2) would be copied/moved to a class object 8891 // with the same cv-unqualified type, the copy/move operation 8892 // can be omitted by constructing the temporary object 8893 // directly into the target of the omitted copy/move 8894 if (ConstructKind == CXXConstructExpr::CK_Complete && 8895 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 8896 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 8897 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 8898 } 8899 8900 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 8901 Elidable, move(ExprArgs), HadMultipleCandidates, 8902 RequiresZeroInit, ConstructKind, ParenRange); 8903} 8904 8905/// BuildCXXConstructExpr - Creates a complete call to a constructor, 8906/// including handling of its default argument expressions. 8907ExprResult 8908Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 8909 CXXConstructorDecl *Constructor, bool Elidable, 8910 MultiExprArg ExprArgs, 8911 bool HadMultipleCandidates, 8912 bool RequiresZeroInit, 8913 unsigned ConstructKind, 8914 SourceRange ParenRange) { 8915 unsigned NumExprs = ExprArgs.size(); 8916 Expr **Exprs = (Expr **)ExprArgs.release(); 8917 8918 for (specific_attr_iterator<NonNullAttr> 8919 i = Constructor->specific_attr_begin<NonNullAttr>(), 8920 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 8921 const NonNullAttr *NonNull = *i; 8922 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 8923 } 8924 8925 MarkDeclarationReferenced(ConstructLoc, Constructor); 8926 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 8927 Constructor, Elidable, Exprs, NumExprs, 8928 HadMultipleCandidates, RequiresZeroInit, 8929 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 8930 ParenRange)); 8931} 8932 8933bool Sema::InitializeVarWithConstructor(VarDecl *VD, 8934 CXXConstructorDecl *Constructor, 8935 MultiExprArg Exprs, 8936 bool HadMultipleCandidates) { 8937 // FIXME: Provide the correct paren SourceRange when available. 8938 ExprResult TempResult = 8939 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 8940 move(Exprs), HadMultipleCandidates, false, 8941 CXXConstructExpr::CK_Complete, SourceRange()); 8942 if (TempResult.isInvalid()) 8943 return true; 8944 8945 Expr *Temp = TempResult.takeAs<Expr>(); 8946 CheckImplicitConversions(Temp, VD->getLocation()); 8947 MarkDeclarationReferenced(VD->getLocation(), Constructor); 8948 Temp = MaybeCreateExprWithCleanups(Temp); 8949 VD->setInit(Temp); 8950 8951 return false; 8952} 8953 8954void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 8955 if (VD->isInvalidDecl()) return; 8956 8957 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 8958 if (ClassDecl->isInvalidDecl()) return; 8959 if (ClassDecl->hasTrivialDestructor()) return; 8960 if (ClassDecl->isDependentContext()) return; 8961 8962 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 8963 MarkDeclarationReferenced(VD->getLocation(), Destructor); 8964 CheckDestructorAccess(VD->getLocation(), Destructor, 8965 PDiag(diag::err_access_dtor_var) 8966 << VD->getDeclName() 8967 << VD->getType()); 8968 8969 if (!VD->hasGlobalStorage()) return; 8970 8971 // Emit warning for non-trivial dtor in global scope (a real global, 8972 // class-static, function-static). 8973 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 8974 8975 // TODO: this should be re-enabled for static locals by !CXAAtExit 8976 if (!VD->isStaticLocal()) 8977 Diag(VD->getLocation(), diag::warn_global_destructor); 8978} 8979 8980/// AddCXXDirectInitializerToDecl - This action is called immediately after 8981/// ActOnDeclarator, when a C++ direct initializer is present. 8982/// e.g: "int x(1);" 8983void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 8984 SourceLocation LParenLoc, 8985 MultiExprArg Exprs, 8986 SourceLocation RParenLoc, 8987 bool TypeMayContainAuto) { 8988 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 8989 8990 // If there is no declaration, there was an error parsing it. Just ignore 8991 // the initializer. 8992 if (RealDecl == 0) 8993 return; 8994 8995 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8996 if (!VDecl) { 8997 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8998 RealDecl->setInvalidDecl(); 8999 return; 9000 } 9001 9002 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9003 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 9004 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 9005 if (Exprs.size() > 1) { 9006 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 9007 diag::err_auto_var_init_multiple_expressions) 9008 << VDecl->getDeclName() << VDecl->getType() 9009 << VDecl->getSourceRange(); 9010 RealDecl->setInvalidDecl(); 9011 return; 9012 } 9013 9014 Expr *Init = Exprs.get()[0]; 9015 TypeSourceInfo *DeducedType = 0; 9016 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 9017 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 9018 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 9019 << Init->getSourceRange(); 9020 if (!DeducedType) { 9021 RealDecl->setInvalidDecl(); 9022 return; 9023 } 9024 VDecl->setTypeSourceInfo(DeducedType); 9025 VDecl->setType(DeducedType->getType()); 9026 9027 // In ARC, infer lifetime. 9028 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9029 VDecl->setInvalidDecl(); 9030 9031 // If this is a redeclaration, check that the type we just deduced matches 9032 // the previously declared type. 9033 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 9034 MergeVarDeclTypes(VDecl, Old); 9035 } 9036 9037 // We will represent direct-initialization similarly to copy-initialization: 9038 // int x(1); -as-> int x = 1; 9039 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9040 // 9041 // Clients that want to distinguish between the two forms, can check for 9042 // direct initializer using VarDecl::hasCXXDirectInitializer(). 9043 // A major benefit is that clients that don't particularly care about which 9044 // exactly form was it (like the CodeGen) can handle both cases without 9045 // special case code. 9046 9047 // C++ 8.5p11: 9048 // The form of initialization (using parentheses or '=') is generally 9049 // insignificant, but does matter when the entity being initialized has a 9050 // class type. 9051 9052 if (!VDecl->getType()->isDependentType() && 9053 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 9054 diag::err_typecheck_decl_incomplete_type)) { 9055 VDecl->setInvalidDecl(); 9056 return; 9057 } 9058 9059 // The variable can not have an abstract class type. 9060 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9061 diag::err_abstract_type_in_decl, 9062 AbstractVariableType)) 9063 VDecl->setInvalidDecl(); 9064 9065 const VarDecl *Def; 9066 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 9067 Diag(VDecl->getLocation(), diag::err_redefinition) 9068 << VDecl->getDeclName(); 9069 Diag(Def->getLocation(), diag::note_previous_definition); 9070 VDecl->setInvalidDecl(); 9071 return; 9072 } 9073 9074 // C++ [class.static.data]p4 9075 // If a static data member is of const integral or const 9076 // enumeration type, its declaration in the class definition can 9077 // specify a constant-initializer which shall be an integral 9078 // constant expression (5.19). In that case, the member can appear 9079 // in integral constant expressions. The member shall still be 9080 // defined in a namespace scope if it is used in the program and the 9081 // namespace scope definition shall not contain an initializer. 9082 // 9083 // We already performed a redefinition check above, but for static 9084 // data members we also need to check whether there was an in-class 9085 // declaration with an initializer. 9086 const VarDecl* PrevInit = 0; 9087 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 9088 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 9089 Diag(PrevInit->getLocation(), diag::note_previous_definition); 9090 return; 9091 } 9092 9093 bool IsDependent = false; 9094 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 9095 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 9096 VDecl->setInvalidDecl(); 9097 return; 9098 } 9099 9100 if (Exprs.get()[I]->isTypeDependent()) 9101 IsDependent = true; 9102 } 9103 9104 // If either the declaration has a dependent type or if any of the 9105 // expressions is type-dependent, we represent the initialization 9106 // via a ParenListExpr for later use during template instantiation. 9107 if (VDecl->getType()->isDependentType() || IsDependent) { 9108 // Let clients know that initialization was done with a direct initializer. 9109 VDecl->setCXXDirectInitializer(true); 9110 9111 // Store the initialization expressions as a ParenListExpr. 9112 unsigned NumExprs = Exprs.size(); 9113 VDecl->setInit(new (Context) ParenListExpr( 9114 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc, 9115 VDecl->getType().getNonReferenceType())); 9116 return; 9117 } 9118 9119 // Capture the variable that is being initialized and the style of 9120 // initialization. 9121 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9122 9123 // FIXME: Poor source location information. 9124 InitializationKind Kind 9125 = InitializationKind::CreateDirect(VDecl->getLocation(), 9126 LParenLoc, RParenLoc); 9127 9128 InitializationSequence InitSeq(*this, Entity, Kind, 9129 Exprs.get(), Exprs.size()); 9130 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 9131 if (Result.isInvalid()) { 9132 VDecl->setInvalidDecl(); 9133 return; 9134 } 9135 9136 Expr *Init = Result.get(); 9137 CheckImplicitConversions(Init, LParenLoc); 9138 9139 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() && 9140 !Init->isValueDependent() && 9141 !Init->isConstantInitializer(Context, 9142 VDecl->getType()->isReferenceType())) { 9143 // FIXME: Improve this diagnostic to explain why the initializer is not 9144 // a constant expression. 9145 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init) 9146 << VDecl << Init->getSourceRange(); 9147 } 9148 9149 Init = MaybeCreateExprWithCleanups(Init); 9150 VDecl->setInit(Init); 9151 VDecl->setCXXDirectInitializer(true); 9152 9153 CheckCompleteVariableDeclaration(VDecl); 9154} 9155 9156/// \brief Given a constructor and the set of arguments provided for the 9157/// constructor, convert the arguments and add any required default arguments 9158/// to form a proper call to this constructor. 9159/// 9160/// \returns true if an error occurred, false otherwise. 9161bool 9162Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9163 MultiExprArg ArgsPtr, 9164 SourceLocation Loc, 9165 ASTOwningVector<Expr*> &ConvertedArgs) { 9166 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9167 unsigned NumArgs = ArgsPtr.size(); 9168 Expr **Args = (Expr **)ArgsPtr.get(); 9169 9170 const FunctionProtoType *Proto 9171 = Constructor->getType()->getAs<FunctionProtoType>(); 9172 assert(Proto && "Constructor without a prototype?"); 9173 unsigned NumArgsInProto = Proto->getNumArgs(); 9174 9175 // If too few arguments are available, we'll fill in the rest with defaults. 9176 if (NumArgs < NumArgsInProto) 9177 ConvertedArgs.reserve(NumArgsInProto); 9178 else 9179 ConvertedArgs.reserve(NumArgs); 9180 9181 VariadicCallType CallType = 9182 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9183 SmallVector<Expr *, 8> AllArgs; 9184 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9185 Proto, 0, Args, NumArgs, AllArgs, 9186 CallType); 9187 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 9188 ConvertedArgs.push_back(AllArgs[i]); 9189 return Invalid; 9190} 9191 9192static inline bool 9193CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9194 const FunctionDecl *FnDecl) { 9195 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9196 if (isa<NamespaceDecl>(DC)) { 9197 return SemaRef.Diag(FnDecl->getLocation(), 9198 diag::err_operator_new_delete_declared_in_namespace) 9199 << FnDecl->getDeclName(); 9200 } 9201 9202 if (isa<TranslationUnitDecl>(DC) && 9203 FnDecl->getStorageClass() == SC_Static) { 9204 return SemaRef.Diag(FnDecl->getLocation(), 9205 diag::err_operator_new_delete_declared_static) 9206 << FnDecl->getDeclName(); 9207 } 9208 9209 return false; 9210} 9211 9212static inline bool 9213CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9214 CanQualType ExpectedResultType, 9215 CanQualType ExpectedFirstParamType, 9216 unsigned DependentParamTypeDiag, 9217 unsigned InvalidParamTypeDiag) { 9218 QualType ResultType = 9219 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9220 9221 // Check that the result type is not dependent. 9222 if (ResultType->isDependentType()) 9223 return SemaRef.Diag(FnDecl->getLocation(), 9224 diag::err_operator_new_delete_dependent_result_type) 9225 << FnDecl->getDeclName() << ExpectedResultType; 9226 9227 // Check that the result type is what we expect. 9228 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9229 return SemaRef.Diag(FnDecl->getLocation(), 9230 diag::err_operator_new_delete_invalid_result_type) 9231 << FnDecl->getDeclName() << ExpectedResultType; 9232 9233 // A function template must have at least 2 parameters. 9234 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9235 return SemaRef.Diag(FnDecl->getLocation(), 9236 diag::err_operator_new_delete_template_too_few_parameters) 9237 << FnDecl->getDeclName(); 9238 9239 // The function decl must have at least 1 parameter. 9240 if (FnDecl->getNumParams() == 0) 9241 return SemaRef.Diag(FnDecl->getLocation(), 9242 diag::err_operator_new_delete_too_few_parameters) 9243 << FnDecl->getDeclName(); 9244 9245 // Check the the first parameter type is not dependent. 9246 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9247 if (FirstParamType->isDependentType()) 9248 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9249 << FnDecl->getDeclName() << ExpectedFirstParamType; 9250 9251 // Check that the first parameter type is what we expect. 9252 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9253 ExpectedFirstParamType) 9254 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9255 << FnDecl->getDeclName() << ExpectedFirstParamType; 9256 9257 return false; 9258} 9259 9260static bool 9261CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9262 // C++ [basic.stc.dynamic.allocation]p1: 9263 // A program is ill-formed if an allocation function is declared in a 9264 // namespace scope other than global scope or declared static in global 9265 // scope. 9266 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9267 return true; 9268 9269 CanQualType SizeTy = 9270 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9271 9272 // C++ [basic.stc.dynamic.allocation]p1: 9273 // The return type shall be void*. The first parameter shall have type 9274 // std::size_t. 9275 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9276 SizeTy, 9277 diag::err_operator_new_dependent_param_type, 9278 diag::err_operator_new_param_type)) 9279 return true; 9280 9281 // C++ [basic.stc.dynamic.allocation]p1: 9282 // The first parameter shall not have an associated default argument. 9283 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9284 return SemaRef.Diag(FnDecl->getLocation(), 9285 diag::err_operator_new_default_arg) 9286 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9287 9288 return false; 9289} 9290 9291static bool 9292CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9293 // C++ [basic.stc.dynamic.deallocation]p1: 9294 // A program is ill-formed if deallocation functions are declared in a 9295 // namespace scope other than global scope or declared static in global 9296 // scope. 9297 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9298 return true; 9299 9300 // C++ [basic.stc.dynamic.deallocation]p2: 9301 // Each deallocation function shall return void and its first parameter 9302 // shall be void*. 9303 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9304 SemaRef.Context.VoidPtrTy, 9305 diag::err_operator_delete_dependent_param_type, 9306 diag::err_operator_delete_param_type)) 9307 return true; 9308 9309 return false; 9310} 9311 9312/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9313/// of this overloaded operator is well-formed. If so, returns false; 9314/// otherwise, emits appropriate diagnostics and returns true. 9315bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9316 assert(FnDecl && FnDecl->isOverloadedOperator() && 9317 "Expected an overloaded operator declaration"); 9318 9319 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9320 9321 // C++ [over.oper]p5: 9322 // The allocation and deallocation functions, operator new, 9323 // operator new[], operator delete and operator delete[], are 9324 // described completely in 3.7.3. The attributes and restrictions 9325 // found in the rest of this subclause do not apply to them unless 9326 // explicitly stated in 3.7.3. 9327 if (Op == OO_Delete || Op == OO_Array_Delete) 9328 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9329 9330 if (Op == OO_New || Op == OO_Array_New) 9331 return CheckOperatorNewDeclaration(*this, FnDecl); 9332 9333 // C++ [over.oper]p6: 9334 // An operator function shall either be a non-static member 9335 // function or be a non-member function and have at least one 9336 // parameter whose type is a class, a reference to a class, an 9337 // enumeration, or a reference to an enumeration. 9338 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9339 if (MethodDecl->isStatic()) 9340 return Diag(FnDecl->getLocation(), 9341 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9342 } else { 9343 bool ClassOrEnumParam = false; 9344 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9345 ParamEnd = FnDecl->param_end(); 9346 Param != ParamEnd; ++Param) { 9347 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9348 if (ParamType->isDependentType() || ParamType->isRecordType() || 9349 ParamType->isEnumeralType()) { 9350 ClassOrEnumParam = true; 9351 break; 9352 } 9353 } 9354 9355 if (!ClassOrEnumParam) 9356 return Diag(FnDecl->getLocation(), 9357 diag::err_operator_overload_needs_class_or_enum) 9358 << FnDecl->getDeclName(); 9359 } 9360 9361 // C++ [over.oper]p8: 9362 // An operator function cannot have default arguments (8.3.6), 9363 // except where explicitly stated below. 9364 // 9365 // Only the function-call operator allows default arguments 9366 // (C++ [over.call]p1). 9367 if (Op != OO_Call) { 9368 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9369 Param != FnDecl->param_end(); ++Param) { 9370 if ((*Param)->hasDefaultArg()) 9371 return Diag((*Param)->getLocation(), 9372 diag::err_operator_overload_default_arg) 9373 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9374 } 9375 } 9376 9377 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9378 { false, false, false } 9379#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9380 , { Unary, Binary, MemberOnly } 9381#include "clang/Basic/OperatorKinds.def" 9382 }; 9383 9384 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9385 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9386 bool MustBeMemberOperator = OperatorUses[Op][2]; 9387 9388 // C++ [over.oper]p8: 9389 // [...] Operator functions cannot have more or fewer parameters 9390 // than the number required for the corresponding operator, as 9391 // described in the rest of this subclause. 9392 unsigned NumParams = FnDecl->getNumParams() 9393 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9394 if (Op != OO_Call && 9395 ((NumParams == 1 && !CanBeUnaryOperator) || 9396 (NumParams == 2 && !CanBeBinaryOperator) || 9397 (NumParams < 1) || (NumParams > 2))) { 9398 // We have the wrong number of parameters. 9399 unsigned ErrorKind; 9400 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9401 ErrorKind = 2; // 2 -> unary or binary. 9402 } else if (CanBeUnaryOperator) { 9403 ErrorKind = 0; // 0 -> unary 9404 } else { 9405 assert(CanBeBinaryOperator && 9406 "All non-call overloaded operators are unary or binary!"); 9407 ErrorKind = 1; // 1 -> binary 9408 } 9409 9410 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9411 << FnDecl->getDeclName() << NumParams << ErrorKind; 9412 } 9413 9414 // Overloaded operators other than operator() cannot be variadic. 9415 if (Op != OO_Call && 9416 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9417 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9418 << FnDecl->getDeclName(); 9419 } 9420 9421 // Some operators must be non-static member functions. 9422 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9423 return Diag(FnDecl->getLocation(), 9424 diag::err_operator_overload_must_be_member) 9425 << FnDecl->getDeclName(); 9426 } 9427 9428 // C++ [over.inc]p1: 9429 // The user-defined function called operator++ implements the 9430 // prefix and postfix ++ operator. If this function is a member 9431 // function with no parameters, or a non-member function with one 9432 // parameter of class or enumeration type, it defines the prefix 9433 // increment operator ++ for objects of that type. If the function 9434 // is a member function with one parameter (which shall be of type 9435 // int) or a non-member function with two parameters (the second 9436 // of which shall be of type int), it defines the postfix 9437 // increment operator ++ for objects of that type. 9438 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9439 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9440 bool ParamIsInt = false; 9441 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9442 ParamIsInt = BT->getKind() == BuiltinType::Int; 9443 9444 if (!ParamIsInt) 9445 return Diag(LastParam->getLocation(), 9446 diag::err_operator_overload_post_incdec_must_be_int) 9447 << LastParam->getType() << (Op == OO_MinusMinus); 9448 } 9449 9450 return false; 9451} 9452 9453/// CheckLiteralOperatorDeclaration - Check whether the declaration 9454/// of this literal operator function is well-formed. If so, returns 9455/// false; otherwise, emits appropriate diagnostics and returns true. 9456bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9457 DeclContext *DC = FnDecl->getDeclContext(); 9458 Decl::Kind Kind = DC->getDeclKind(); 9459 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 9460 Kind != Decl::LinkageSpec) { 9461 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9462 << FnDecl->getDeclName(); 9463 return true; 9464 } 9465 9466 bool Valid = false; 9467 9468 // template <char...> type operator "" name() is the only valid template 9469 // signature, and the only valid signature with no parameters. 9470 if (FnDecl->param_size() == 0) { 9471 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 9472 // Must have only one template parameter 9473 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9474 if (Params->size() == 1) { 9475 NonTypeTemplateParmDecl *PmDecl = 9476 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9477 9478 // The template parameter must be a char parameter pack. 9479 if (PmDecl && PmDecl->isTemplateParameterPack() && 9480 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9481 Valid = true; 9482 } 9483 } 9484 } else { 9485 // Check the first parameter 9486 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9487 9488 QualType T = (*Param)->getType(); 9489 9490 // unsigned long long int, long double, and any character type are allowed 9491 // as the only parameters. 9492 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9493 Context.hasSameType(T, Context.LongDoubleTy) || 9494 Context.hasSameType(T, Context.CharTy) || 9495 Context.hasSameType(T, Context.WCharTy) || 9496 Context.hasSameType(T, Context.Char16Ty) || 9497 Context.hasSameType(T, Context.Char32Ty)) { 9498 if (++Param == FnDecl->param_end()) 9499 Valid = true; 9500 goto FinishedParams; 9501 } 9502 9503 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9504 const PointerType *PT = T->getAs<PointerType>(); 9505 if (!PT) 9506 goto FinishedParams; 9507 T = PT->getPointeeType(); 9508 if (!T.isConstQualified()) 9509 goto FinishedParams; 9510 T = T.getUnqualifiedType(); 9511 9512 // Move on to the second parameter; 9513 ++Param; 9514 9515 // If there is no second parameter, the first must be a const char * 9516 if (Param == FnDecl->param_end()) { 9517 if (Context.hasSameType(T, Context.CharTy)) 9518 Valid = true; 9519 goto FinishedParams; 9520 } 9521 9522 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9523 // are allowed as the first parameter to a two-parameter function 9524 if (!(Context.hasSameType(T, Context.CharTy) || 9525 Context.hasSameType(T, Context.WCharTy) || 9526 Context.hasSameType(T, Context.Char16Ty) || 9527 Context.hasSameType(T, Context.Char32Ty))) 9528 goto FinishedParams; 9529 9530 // The second and final parameter must be an std::size_t 9531 T = (*Param)->getType().getUnqualifiedType(); 9532 if (Context.hasSameType(T, Context.getSizeType()) && 9533 ++Param == FnDecl->param_end()) 9534 Valid = true; 9535 } 9536 9537 // FIXME: This diagnostic is absolutely terrible. 9538FinishedParams: 9539 if (!Valid) { 9540 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9541 << FnDecl->getDeclName(); 9542 return true; 9543 } 9544 9545 StringRef LiteralName 9546 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9547 if (LiteralName[0] != '_') { 9548 // C++0x [usrlit.suffix]p1: 9549 // Literal suffix identifiers that do not start with an underscore are 9550 // reserved for future standardization. 9551 bool IsHexFloat = true; 9552 if (LiteralName.size() > 1 && 9553 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) { 9554 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) { 9555 if (!isdigit(LiteralName[I])) { 9556 IsHexFloat = false; 9557 break; 9558 } 9559 } 9560 } 9561 9562 if (IsHexFloat) 9563 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat) 9564 << LiteralName; 9565 else 9566 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9567 } 9568 9569 return false; 9570} 9571 9572/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9573/// linkage specification, including the language and (if present) 9574/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9575/// the location of the language string literal, which is provided 9576/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9577/// the '{' brace. Otherwise, this linkage specification does not 9578/// have any braces. 9579Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9580 SourceLocation LangLoc, 9581 StringRef Lang, 9582 SourceLocation LBraceLoc) { 9583 LinkageSpecDecl::LanguageIDs Language; 9584 if (Lang == "\"C\"") 9585 Language = LinkageSpecDecl::lang_c; 9586 else if (Lang == "\"C++\"") 9587 Language = LinkageSpecDecl::lang_cxx; 9588 else { 9589 Diag(LangLoc, diag::err_bad_language); 9590 return 0; 9591 } 9592 9593 // FIXME: Add all the various semantics of linkage specifications 9594 9595 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9596 ExternLoc, LangLoc, Language); 9597 CurContext->addDecl(D); 9598 PushDeclContext(S, D); 9599 return D; 9600} 9601 9602/// ActOnFinishLinkageSpecification - Complete the definition of 9603/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9604/// valid, it's the position of the closing '}' brace in a linkage 9605/// specification that uses braces. 9606Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9607 Decl *LinkageSpec, 9608 SourceLocation RBraceLoc) { 9609 if (LinkageSpec) { 9610 if (RBraceLoc.isValid()) { 9611 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9612 LSDecl->setRBraceLoc(RBraceLoc); 9613 } 9614 PopDeclContext(); 9615 } 9616 return LinkageSpec; 9617} 9618 9619/// \brief Perform semantic analysis for the variable declaration that 9620/// occurs within a C++ catch clause, returning the newly-created 9621/// variable. 9622VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9623 TypeSourceInfo *TInfo, 9624 SourceLocation StartLoc, 9625 SourceLocation Loc, 9626 IdentifierInfo *Name) { 9627 bool Invalid = false; 9628 QualType ExDeclType = TInfo->getType(); 9629 9630 // Arrays and functions decay. 9631 if (ExDeclType->isArrayType()) 9632 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9633 else if (ExDeclType->isFunctionType()) 9634 ExDeclType = Context.getPointerType(ExDeclType); 9635 9636 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9637 // The exception-declaration shall not denote a pointer or reference to an 9638 // incomplete type, other than [cv] void*. 9639 // N2844 forbids rvalue references. 9640 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9641 Diag(Loc, diag::err_catch_rvalue_ref); 9642 Invalid = true; 9643 } 9644 9645 // GCC allows catching pointers and references to incomplete types 9646 // as an extension; so do we, but we warn by default. 9647 9648 QualType BaseType = ExDeclType; 9649 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9650 unsigned DK = diag::err_catch_incomplete; 9651 bool IncompleteCatchIsInvalid = true; 9652 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9653 BaseType = Ptr->getPointeeType(); 9654 Mode = 1; 9655 DK = diag::ext_catch_incomplete_ptr; 9656 IncompleteCatchIsInvalid = false; 9657 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9658 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9659 BaseType = Ref->getPointeeType(); 9660 Mode = 2; 9661 DK = diag::ext_catch_incomplete_ref; 9662 IncompleteCatchIsInvalid = false; 9663 } 9664 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9665 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 9666 IncompleteCatchIsInvalid) 9667 Invalid = true; 9668 9669 if (!Invalid && !ExDeclType->isDependentType() && 9670 RequireNonAbstractType(Loc, ExDeclType, 9671 diag::err_abstract_type_in_decl, 9672 AbstractVariableType)) 9673 Invalid = true; 9674 9675 // Only the non-fragile NeXT runtime currently supports C++ catches 9676 // of ObjC types, and no runtime supports catching ObjC types by value. 9677 if (!Invalid && getLangOptions().ObjC1) { 9678 QualType T = ExDeclType; 9679 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9680 T = RT->getPointeeType(); 9681 9682 if (T->isObjCObjectType()) { 9683 Diag(Loc, diag::err_objc_object_catch); 9684 Invalid = true; 9685 } else if (T->isObjCObjectPointerType()) { 9686 if (!getLangOptions().ObjCNonFragileABI) 9687 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9688 } 9689 } 9690 9691 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9692 ExDeclType, TInfo, SC_None, SC_None); 9693 ExDecl->setExceptionVariable(true); 9694 9695 if (!Invalid && !ExDeclType->isDependentType()) { 9696 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9697 // C++ [except.handle]p16: 9698 // The object declared in an exception-declaration or, if the 9699 // exception-declaration does not specify a name, a temporary (12.2) is 9700 // copy-initialized (8.5) from the exception object. [...] 9701 // The object is destroyed when the handler exits, after the destruction 9702 // of any automatic objects initialized within the handler. 9703 // 9704 // We just pretend to initialize the object with itself, then make sure 9705 // it can be destroyed later. 9706 QualType initType = ExDeclType; 9707 9708 InitializedEntity entity = 9709 InitializedEntity::InitializeVariable(ExDecl); 9710 InitializationKind initKind = 9711 InitializationKind::CreateCopy(Loc, SourceLocation()); 9712 9713 Expr *opaqueValue = 9714 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9715 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9716 ExprResult result = sequence.Perform(*this, entity, initKind, 9717 MultiExprArg(&opaqueValue, 1)); 9718 if (result.isInvalid()) 9719 Invalid = true; 9720 else { 9721 // If the constructor used was non-trivial, set this as the 9722 // "initializer". 9723 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9724 if (!construct->getConstructor()->isTrivial()) { 9725 Expr *init = MaybeCreateExprWithCleanups(construct); 9726 ExDecl->setInit(init); 9727 } 9728 9729 // And make sure it's destructable. 9730 FinalizeVarWithDestructor(ExDecl, recordType); 9731 } 9732 } 9733 } 9734 9735 if (Invalid) 9736 ExDecl->setInvalidDecl(); 9737 9738 return ExDecl; 9739} 9740 9741/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9742/// handler. 9743Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9744 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9745 bool Invalid = D.isInvalidType(); 9746 9747 // Check for unexpanded parameter packs. 9748 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9749 UPPC_ExceptionType)) { 9750 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9751 D.getIdentifierLoc()); 9752 Invalid = true; 9753 } 9754 9755 IdentifierInfo *II = D.getIdentifier(); 9756 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9757 LookupOrdinaryName, 9758 ForRedeclaration)) { 9759 // The scope should be freshly made just for us. There is just no way 9760 // it contains any previous declaration. 9761 assert(!S->isDeclScope(PrevDecl)); 9762 if (PrevDecl->isTemplateParameter()) { 9763 // Maybe we will complain about the shadowed template parameter. 9764 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9765 } 9766 } 9767 9768 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9769 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9770 << D.getCXXScopeSpec().getRange(); 9771 Invalid = true; 9772 } 9773 9774 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9775 D.getSourceRange().getBegin(), 9776 D.getIdentifierLoc(), 9777 D.getIdentifier()); 9778 if (Invalid) 9779 ExDecl->setInvalidDecl(); 9780 9781 // Add the exception declaration into this scope. 9782 if (II) 9783 PushOnScopeChains(ExDecl, S); 9784 else 9785 CurContext->addDecl(ExDecl); 9786 9787 ProcessDeclAttributes(S, ExDecl, D); 9788 return ExDecl; 9789} 9790 9791Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9792 Expr *AssertExpr, 9793 Expr *AssertMessageExpr_, 9794 SourceLocation RParenLoc) { 9795 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 9796 9797 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 9798 llvm::APSInt Value(32); 9799 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 9800 Diag(StaticAssertLoc, 9801 diag::err_static_assert_expression_is_not_constant) << 9802 AssertExpr->getSourceRange(); 9803 return 0; 9804 } 9805 9806 if (Value == 0) { 9807 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9808 << AssertMessage->getString() << AssertExpr->getSourceRange(); 9809 } 9810 } 9811 9812 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9813 return 0; 9814 9815 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9816 AssertExpr, AssertMessage, RParenLoc); 9817 9818 CurContext->addDecl(Decl); 9819 return Decl; 9820} 9821 9822/// \brief Perform semantic analysis of the given friend type declaration. 9823/// 9824/// \returns A friend declaration that. 9825FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 9826 TypeSourceInfo *TSInfo) { 9827 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9828 9829 QualType T = TSInfo->getType(); 9830 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9831 9832 if (!getLangOptions().CPlusPlus0x) { 9833 // C++03 [class.friend]p2: 9834 // An elaborated-type-specifier shall be used in a friend declaration 9835 // for a class.* 9836 // 9837 // * The class-key of the elaborated-type-specifier is required. 9838 if (!ActiveTemplateInstantiations.empty()) { 9839 // Do not complain about the form of friend template types during 9840 // template instantiation; we will already have complained when the 9841 // template was declared. 9842 } else if (!T->isElaboratedTypeSpecifier()) { 9843 // If we evaluated the type to a record type, suggest putting 9844 // a tag in front. 9845 if (const RecordType *RT = T->getAs<RecordType>()) { 9846 RecordDecl *RD = RT->getDecl(); 9847 9848 std::string InsertionText = std::string(" ") + RD->getKindName(); 9849 9850 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 9851 << (unsigned) RD->getTagKind() 9852 << T 9853 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9854 InsertionText); 9855 } else { 9856 Diag(FriendLoc, diag::ext_nonclass_type_friend) 9857 << T 9858 << SourceRange(FriendLoc, TypeRange.getEnd()); 9859 } 9860 } else if (T->getAs<EnumType>()) { 9861 Diag(FriendLoc, diag::ext_enum_friend) 9862 << T 9863 << SourceRange(FriendLoc, TypeRange.getEnd()); 9864 } 9865 } 9866 9867 // C++0x [class.friend]p3: 9868 // If the type specifier in a friend declaration designates a (possibly 9869 // cv-qualified) class type, that class is declared as a friend; otherwise, 9870 // the friend declaration is ignored. 9871 9872 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9873 // in [class.friend]p3 that we do not implement. 9874 9875 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 9876} 9877 9878/// Handle a friend tag declaration where the scope specifier was 9879/// templated. 9880Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9881 unsigned TagSpec, SourceLocation TagLoc, 9882 CXXScopeSpec &SS, 9883 IdentifierInfo *Name, SourceLocation NameLoc, 9884 AttributeList *Attr, 9885 MultiTemplateParamsArg TempParamLists) { 9886 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9887 9888 bool isExplicitSpecialization = false; 9889 bool Invalid = false; 9890 9891 if (TemplateParameterList *TemplateParams 9892 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9893 TempParamLists.get(), 9894 TempParamLists.size(), 9895 /*friend*/ true, 9896 isExplicitSpecialization, 9897 Invalid)) { 9898 if (TemplateParams->size() > 0) { 9899 // This is a declaration of a class template. 9900 if (Invalid) 9901 return 0; 9902 9903 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9904 SS, Name, NameLoc, Attr, 9905 TemplateParams, AS_public, 9906 /*ModulePrivateLoc=*/SourceLocation(), 9907 TempParamLists.size() - 1, 9908 (TemplateParameterList**) TempParamLists.release()).take(); 9909 } else { 9910 // The "template<>" header is extraneous. 9911 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9912 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9913 isExplicitSpecialization = true; 9914 } 9915 } 9916 9917 if (Invalid) return 0; 9918 9919 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 9920 9921 bool isAllExplicitSpecializations = true; 9922 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9923 if (TempParamLists.get()[I]->size()) { 9924 isAllExplicitSpecializations = false; 9925 break; 9926 } 9927 } 9928 9929 // FIXME: don't ignore attributes. 9930 9931 // If it's explicit specializations all the way down, just forget 9932 // about the template header and build an appropriate non-templated 9933 // friend. TODO: for source fidelity, remember the headers. 9934 if (isAllExplicitSpecializations) { 9935 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9936 ElaboratedTypeKeyword Keyword 9937 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9938 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9939 *Name, NameLoc); 9940 if (T.isNull()) 9941 return 0; 9942 9943 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9944 if (isa<DependentNameType>(T)) { 9945 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9946 TL.setKeywordLoc(TagLoc); 9947 TL.setQualifierLoc(QualifierLoc); 9948 TL.setNameLoc(NameLoc); 9949 } else { 9950 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9951 TL.setKeywordLoc(TagLoc); 9952 TL.setQualifierLoc(QualifierLoc); 9953 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9954 } 9955 9956 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9957 TSI, FriendLoc); 9958 Friend->setAccess(AS_public); 9959 CurContext->addDecl(Friend); 9960 return Friend; 9961 } 9962 9963 // Handle the case of a templated-scope friend class. e.g. 9964 // template <class T> class A<T>::B; 9965 // FIXME: we don't support these right now. 9966 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9967 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 9968 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9969 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9970 TL.setKeywordLoc(TagLoc); 9971 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9972 TL.setNameLoc(NameLoc); 9973 9974 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9975 TSI, FriendLoc); 9976 Friend->setAccess(AS_public); 9977 Friend->setUnsupportedFriend(true); 9978 CurContext->addDecl(Friend); 9979 return Friend; 9980} 9981 9982 9983/// Handle a friend type declaration. This works in tandem with 9984/// ActOnTag. 9985/// 9986/// Notes on friend class templates: 9987/// 9988/// We generally treat friend class declarations as if they were 9989/// declaring a class. So, for example, the elaborated type specifier 9990/// in a friend declaration is required to obey the restrictions of a 9991/// class-head (i.e. no typedefs in the scope chain), template 9992/// parameters are required to match up with simple template-ids, &c. 9993/// However, unlike when declaring a template specialization, it's 9994/// okay to refer to a template specialization without an empty 9995/// template parameter declaration, e.g. 9996/// friend class A<T>::B<unsigned>; 9997/// We permit this as a special case; if there are any template 9998/// parameters present at all, require proper matching, i.e. 9999/// template <> template <class T> friend class A<int>::B; 10000Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10001 MultiTemplateParamsArg TempParams) { 10002 SourceLocation Loc = DS.getSourceRange().getBegin(); 10003 10004 assert(DS.isFriendSpecified()); 10005 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10006 10007 // Try to convert the decl specifier to a type. This works for 10008 // friend templates because ActOnTag never produces a ClassTemplateDecl 10009 // for a TUK_Friend. 10010 Declarator TheDeclarator(DS, Declarator::MemberContext); 10011 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10012 QualType T = TSI->getType(); 10013 if (TheDeclarator.isInvalidType()) 10014 return 0; 10015 10016 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10017 return 0; 10018 10019 // This is definitely an error in C++98. It's probably meant to 10020 // be forbidden in C++0x, too, but the specification is just 10021 // poorly written. 10022 // 10023 // The problem is with declarations like the following: 10024 // template <T> friend A<T>::foo; 10025 // where deciding whether a class C is a friend or not now hinges 10026 // on whether there exists an instantiation of A that causes 10027 // 'foo' to equal C. There are restrictions on class-heads 10028 // (which we declare (by fiat) elaborated friend declarations to 10029 // be) that makes this tractable. 10030 // 10031 // FIXME: handle "template <> friend class A<T>;", which 10032 // is possibly well-formed? Who even knows? 10033 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10034 Diag(Loc, diag::err_tagless_friend_type_template) 10035 << DS.getSourceRange(); 10036 return 0; 10037 } 10038 10039 // C++98 [class.friend]p1: A friend of a class is a function 10040 // or class that is not a member of the class . . . 10041 // This is fixed in DR77, which just barely didn't make the C++03 10042 // deadline. It's also a very silly restriction that seriously 10043 // affects inner classes and which nobody else seems to implement; 10044 // thus we never diagnose it, not even in -pedantic. 10045 // 10046 // But note that we could warn about it: it's always useless to 10047 // friend one of your own members (it's not, however, worthless to 10048 // friend a member of an arbitrary specialization of your template). 10049 10050 Decl *D; 10051 if (unsigned NumTempParamLists = TempParams.size()) 10052 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10053 NumTempParamLists, 10054 TempParams.release(), 10055 TSI, 10056 DS.getFriendSpecLoc()); 10057 else 10058 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 10059 10060 if (!D) 10061 return 0; 10062 10063 D->setAccess(AS_public); 10064 CurContext->addDecl(D); 10065 10066 return D; 10067} 10068 10069Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 10070 MultiTemplateParamsArg TemplateParams) { 10071 const DeclSpec &DS = D.getDeclSpec(); 10072 10073 assert(DS.isFriendSpecified()); 10074 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10075 10076 SourceLocation Loc = D.getIdentifierLoc(); 10077 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10078 QualType T = TInfo->getType(); 10079 10080 // C++ [class.friend]p1 10081 // A friend of a class is a function or class.... 10082 // Note that this sees through typedefs, which is intended. 10083 // It *doesn't* see through dependent types, which is correct 10084 // according to [temp.arg.type]p3: 10085 // If a declaration acquires a function type through a 10086 // type dependent on a template-parameter and this causes 10087 // a declaration that does not use the syntactic form of a 10088 // function declarator to have a function type, the program 10089 // is ill-formed. 10090 if (!T->isFunctionType()) { 10091 Diag(Loc, diag::err_unexpected_friend); 10092 10093 // It might be worthwhile to try to recover by creating an 10094 // appropriate declaration. 10095 return 0; 10096 } 10097 10098 // C++ [namespace.memdef]p3 10099 // - If a friend declaration in a non-local class first declares a 10100 // class or function, the friend class or function is a member 10101 // of the innermost enclosing namespace. 10102 // - The name of the friend is not found by simple name lookup 10103 // until a matching declaration is provided in that namespace 10104 // scope (either before or after the class declaration granting 10105 // friendship). 10106 // - If a friend function is called, its name may be found by the 10107 // name lookup that considers functions from namespaces and 10108 // classes associated with the types of the function arguments. 10109 // - When looking for a prior declaration of a class or a function 10110 // declared as a friend, scopes outside the innermost enclosing 10111 // namespace scope are not considered. 10112 10113 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10114 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10115 DeclarationName Name = NameInfo.getName(); 10116 assert(Name); 10117 10118 // Check for unexpanded parameter packs. 10119 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10120 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10121 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10122 return 0; 10123 10124 // The context we found the declaration in, or in which we should 10125 // create the declaration. 10126 DeclContext *DC; 10127 Scope *DCScope = S; 10128 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10129 ForRedeclaration); 10130 10131 // FIXME: there are different rules in local classes 10132 10133 // There are four cases here. 10134 // - There's no scope specifier, in which case we just go to the 10135 // appropriate scope and look for a function or function template 10136 // there as appropriate. 10137 // Recover from invalid scope qualifiers as if they just weren't there. 10138 if (SS.isInvalid() || !SS.isSet()) { 10139 // C++0x [namespace.memdef]p3: 10140 // If the name in a friend declaration is neither qualified nor 10141 // a template-id and the declaration is a function or an 10142 // elaborated-type-specifier, the lookup to determine whether 10143 // the entity has been previously declared shall not consider 10144 // any scopes outside the innermost enclosing namespace. 10145 // C++0x [class.friend]p11: 10146 // If a friend declaration appears in a local class and the name 10147 // specified is an unqualified name, a prior declaration is 10148 // looked up without considering scopes that are outside the 10149 // innermost enclosing non-class scope. For a friend function 10150 // declaration, if there is no prior declaration, the program is 10151 // ill-formed. 10152 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10153 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10154 10155 // Find the appropriate context according to the above. 10156 DC = CurContext; 10157 while (true) { 10158 // Skip class contexts. If someone can cite chapter and verse 10159 // for this behavior, that would be nice --- it's what GCC and 10160 // EDG do, and it seems like a reasonable intent, but the spec 10161 // really only says that checks for unqualified existing 10162 // declarations should stop at the nearest enclosing namespace, 10163 // not that they should only consider the nearest enclosing 10164 // namespace. 10165 while (DC->isRecord()) 10166 DC = DC->getParent(); 10167 10168 LookupQualifiedName(Previous, DC); 10169 10170 // TODO: decide what we think about using declarations. 10171 if (isLocal || !Previous.empty()) 10172 break; 10173 10174 if (isTemplateId) { 10175 if (isa<TranslationUnitDecl>(DC)) break; 10176 } else { 10177 if (DC->isFileContext()) break; 10178 } 10179 DC = DC->getParent(); 10180 } 10181 10182 // C++ [class.friend]p1: A friend of a class is a function or 10183 // class that is not a member of the class . . . 10184 // C++0x changes this for both friend types and functions. 10185 // Most C++ 98 compilers do seem to give an error here, so 10186 // we do, too. 10187 if (!Previous.empty() && DC->Equals(CurContext) 10188 && !getLangOptions().CPlusPlus0x) 10189 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 10190 10191 DCScope = getScopeForDeclContext(S, DC); 10192 10193 // - There's a non-dependent scope specifier, in which case we 10194 // compute it and do a previous lookup there for a function 10195 // or function template. 10196 } else if (!SS.getScopeRep()->isDependent()) { 10197 DC = computeDeclContext(SS); 10198 if (!DC) return 0; 10199 10200 if (RequireCompleteDeclContext(SS, DC)) return 0; 10201 10202 LookupQualifiedName(Previous, DC); 10203 10204 // Ignore things found implicitly in the wrong scope. 10205 // TODO: better diagnostics for this case. Suggesting the right 10206 // qualified scope would be nice... 10207 LookupResult::Filter F = Previous.makeFilter(); 10208 while (F.hasNext()) { 10209 NamedDecl *D = F.next(); 10210 if (!DC->InEnclosingNamespaceSetOf( 10211 D->getDeclContext()->getRedeclContext())) 10212 F.erase(); 10213 } 10214 F.done(); 10215 10216 if (Previous.empty()) { 10217 D.setInvalidType(); 10218 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 10219 return 0; 10220 } 10221 10222 // C++ [class.friend]p1: A friend of a class is a function or 10223 // class that is not a member of the class . . . 10224 if (DC->Equals(CurContext)) 10225 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 10226 10227 // - There's a scope specifier that does not match any template 10228 // parameter lists, in which case we use some arbitrary context, 10229 // create a method or method template, and wait for instantiation. 10230 // - There's a scope specifier that does match some template 10231 // parameter lists, which we don't handle right now. 10232 } else { 10233 DC = CurContext; 10234 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10235 } 10236 10237 if (!DC->isRecord()) { 10238 // This implies that it has to be an operator or function. 10239 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10240 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10241 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10242 Diag(Loc, diag::err_introducing_special_friend) << 10243 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10244 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10245 return 0; 10246 } 10247 } 10248 10249 bool Redeclaration = false; 10250 bool AddToScope = true; 10251 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 10252 move(TemplateParams), 10253 IsDefinition, 10254 Redeclaration, AddToScope); 10255 if (!ND) return 0; 10256 10257 assert(ND->getDeclContext() == DC); 10258 assert(ND->getLexicalDeclContext() == CurContext); 10259 10260 // Add the function declaration to the appropriate lookup tables, 10261 // adjusting the redeclarations list as necessary. We don't 10262 // want to do this yet if the friending class is dependent. 10263 // 10264 // Also update the scope-based lookup if the target context's 10265 // lookup context is in lexical scope. 10266 if (!CurContext->isDependentContext()) { 10267 DC = DC->getRedeclContext(); 10268 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 10269 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10270 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10271 } 10272 10273 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10274 D.getIdentifierLoc(), ND, 10275 DS.getFriendSpecLoc()); 10276 FrD->setAccess(AS_public); 10277 CurContext->addDecl(FrD); 10278 10279 if (ND->isInvalidDecl()) 10280 FrD->setInvalidDecl(); 10281 else { 10282 FunctionDecl *FD; 10283 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10284 FD = FTD->getTemplatedDecl(); 10285 else 10286 FD = cast<FunctionDecl>(ND); 10287 10288 // Mark templated-scope function declarations as unsupported. 10289 if (FD->getNumTemplateParameterLists()) 10290 FrD->setUnsupportedFriend(true); 10291 } 10292 10293 return ND; 10294} 10295 10296void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10297 AdjustDeclIfTemplate(Dcl); 10298 10299 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10300 if (!Fn) { 10301 Diag(DelLoc, diag::err_deleted_non_function); 10302 return; 10303 } 10304 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 10305 Diag(DelLoc, diag::err_deleted_decl_not_first); 10306 Diag(Prev->getLocation(), diag::note_previous_declaration); 10307 // If the declaration wasn't the first, we delete the function anyway for 10308 // recovery. 10309 } 10310 Fn->setDeletedAsWritten(); 10311} 10312 10313void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10315 10316 if (MD) { 10317 if (MD->getParent()->isDependentType()) { 10318 MD->setDefaulted(); 10319 MD->setExplicitlyDefaulted(); 10320 return; 10321 } 10322 10323 CXXSpecialMember Member = getSpecialMember(MD); 10324 if (Member == CXXInvalid) { 10325 Diag(DefaultLoc, diag::err_default_special_members); 10326 return; 10327 } 10328 10329 MD->setDefaulted(); 10330 MD->setExplicitlyDefaulted(); 10331 10332 // If this definition appears within the record, do the checking when 10333 // the record is complete. 10334 const FunctionDecl *Primary = MD; 10335 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 10336 // Find the uninstantiated declaration that actually had the '= default' 10337 // on it. 10338 MD->getTemplateInstantiationPattern()->isDefined(Primary); 10339 10340 if (Primary == Primary->getCanonicalDecl()) 10341 return; 10342 10343 switch (Member) { 10344 case CXXDefaultConstructor: { 10345 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10346 CheckExplicitlyDefaultedDefaultConstructor(CD); 10347 if (!CD->isInvalidDecl()) 10348 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10349 break; 10350 } 10351 10352 case CXXCopyConstructor: { 10353 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10354 CheckExplicitlyDefaultedCopyConstructor(CD); 10355 if (!CD->isInvalidDecl()) 10356 DefineImplicitCopyConstructor(DefaultLoc, CD); 10357 break; 10358 } 10359 10360 case CXXCopyAssignment: { 10361 CheckExplicitlyDefaultedCopyAssignment(MD); 10362 if (!MD->isInvalidDecl()) 10363 DefineImplicitCopyAssignment(DefaultLoc, MD); 10364 break; 10365 } 10366 10367 case CXXDestructor: { 10368 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10369 CheckExplicitlyDefaultedDestructor(DD); 10370 if (!DD->isInvalidDecl()) 10371 DefineImplicitDestructor(DefaultLoc, DD); 10372 break; 10373 } 10374 10375 case CXXMoveConstructor: { 10376 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10377 CheckExplicitlyDefaultedMoveConstructor(CD); 10378 if (!CD->isInvalidDecl()) 10379 DefineImplicitMoveConstructor(DefaultLoc, CD); 10380 break; 10381 } 10382 10383 case CXXMoveAssignment: { 10384 CheckExplicitlyDefaultedMoveAssignment(MD); 10385 if (!MD->isInvalidDecl()) 10386 DefineImplicitMoveAssignment(DefaultLoc, MD); 10387 break; 10388 } 10389 10390 case CXXInvalid: 10391 llvm_unreachable("Invalid special member."); 10392 } 10393 } else { 10394 Diag(DefaultLoc, diag::err_default_special_members); 10395 } 10396} 10397 10398static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10399 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10400 Stmt *SubStmt = *CI; 10401 if (!SubStmt) 10402 continue; 10403 if (isa<ReturnStmt>(SubStmt)) 10404 Self.Diag(SubStmt->getSourceRange().getBegin(), 10405 diag::err_return_in_constructor_handler); 10406 if (!isa<Expr>(SubStmt)) 10407 SearchForReturnInStmt(Self, SubStmt); 10408 } 10409} 10410 10411void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10412 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10413 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10414 SearchForReturnInStmt(*this, Handler); 10415 } 10416} 10417 10418bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10419 const CXXMethodDecl *Old) { 10420 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10421 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10422 10423 if (Context.hasSameType(NewTy, OldTy) || 10424 NewTy->isDependentType() || OldTy->isDependentType()) 10425 return false; 10426 10427 // Check if the return types are covariant 10428 QualType NewClassTy, OldClassTy; 10429 10430 /// Both types must be pointers or references to classes. 10431 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10432 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10433 NewClassTy = NewPT->getPointeeType(); 10434 OldClassTy = OldPT->getPointeeType(); 10435 } 10436 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10437 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10438 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10439 NewClassTy = NewRT->getPointeeType(); 10440 OldClassTy = OldRT->getPointeeType(); 10441 } 10442 } 10443 } 10444 10445 // The return types aren't either both pointers or references to a class type. 10446 if (NewClassTy.isNull()) { 10447 Diag(New->getLocation(), 10448 diag::err_different_return_type_for_overriding_virtual_function) 10449 << New->getDeclName() << NewTy << OldTy; 10450 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10451 10452 return true; 10453 } 10454 10455 // C++ [class.virtual]p6: 10456 // If the return type of D::f differs from the return type of B::f, the 10457 // class type in the return type of D::f shall be complete at the point of 10458 // declaration of D::f or shall be the class type D. 10459 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10460 if (!RT->isBeingDefined() && 10461 RequireCompleteType(New->getLocation(), NewClassTy, 10462 PDiag(diag::err_covariant_return_incomplete) 10463 << New->getDeclName())) 10464 return true; 10465 } 10466 10467 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10468 // Check if the new class derives from the old class. 10469 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10470 Diag(New->getLocation(), 10471 diag::err_covariant_return_not_derived) 10472 << New->getDeclName() << NewTy << OldTy; 10473 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10474 return true; 10475 } 10476 10477 // Check if we the conversion from derived to base is valid. 10478 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10479 diag::err_covariant_return_inaccessible_base, 10480 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10481 // FIXME: Should this point to the return type? 10482 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10483 // FIXME: this note won't trigger for delayed access control 10484 // diagnostics, and it's impossible to get an undelayed error 10485 // here from access control during the original parse because 10486 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10487 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10488 return true; 10489 } 10490 } 10491 10492 // The qualifiers of the return types must be the same. 10493 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10494 Diag(New->getLocation(), 10495 diag::err_covariant_return_type_different_qualifications) 10496 << New->getDeclName() << NewTy << OldTy; 10497 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10498 return true; 10499 }; 10500 10501 10502 // The new class type must have the same or less qualifiers as the old type. 10503 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10504 Diag(New->getLocation(), 10505 diag::err_covariant_return_type_class_type_more_qualified) 10506 << New->getDeclName() << NewTy << OldTy; 10507 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10508 return true; 10509 }; 10510 10511 return false; 10512} 10513 10514/// \brief Mark the given method pure. 10515/// 10516/// \param Method the method to be marked pure. 10517/// 10518/// \param InitRange the source range that covers the "0" initializer. 10519bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10520 SourceLocation EndLoc = InitRange.getEnd(); 10521 if (EndLoc.isValid()) 10522 Method->setRangeEnd(EndLoc); 10523 10524 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10525 Method->setPure(); 10526 return false; 10527 } 10528 10529 if (!Method->isInvalidDecl()) 10530 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10531 << Method->getDeclName() << InitRange; 10532 return true; 10533} 10534 10535/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10536/// an initializer for the out-of-line declaration 'Dcl'. The scope 10537/// is a fresh scope pushed for just this purpose. 10538/// 10539/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10540/// static data member of class X, names should be looked up in the scope of 10541/// class X. 10542void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10543 // If there is no declaration, there was an error parsing it. 10544 if (D == 0 || D->isInvalidDecl()) return; 10545 10546 // We should only get called for declarations with scope specifiers, like: 10547 // int foo::bar; 10548 assert(D->isOutOfLine()); 10549 EnterDeclaratorContext(S, D->getDeclContext()); 10550} 10551 10552/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10553/// initializer for the out-of-line declaration 'D'. 10554void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10555 // If there is no declaration, there was an error parsing it. 10556 if (D == 0 || D->isInvalidDecl()) return; 10557 10558 assert(D->isOutOfLine()); 10559 ExitDeclaratorContext(S); 10560} 10561 10562/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10563/// C++ if/switch/while/for statement. 10564/// e.g: "if (int x = f()) {...}" 10565DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10566 // C++ 6.4p2: 10567 // The declarator shall not specify a function or an array. 10568 // The type-specifier-seq shall not contain typedef and shall not declare a 10569 // new class or enumeration. 10570 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10571 "Parser allowed 'typedef' as storage class of condition decl."); 10572 10573 Decl *Dcl = ActOnDeclarator(S, D); 10574 if (!Dcl) 10575 return true; 10576 10577 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10578 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10579 << D.getSourceRange(); 10580 return true; 10581 } 10582 10583 return Dcl; 10584} 10585 10586void Sema::LoadExternalVTableUses() { 10587 if (!ExternalSource) 10588 return; 10589 10590 SmallVector<ExternalVTableUse, 4> VTables; 10591 ExternalSource->ReadUsedVTables(VTables); 10592 SmallVector<VTableUse, 4> NewUses; 10593 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10594 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10595 = VTablesUsed.find(VTables[I].Record); 10596 // Even if a definition wasn't required before, it may be required now. 10597 if (Pos != VTablesUsed.end()) { 10598 if (!Pos->second && VTables[I].DefinitionRequired) 10599 Pos->second = true; 10600 continue; 10601 } 10602 10603 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10604 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10605 } 10606 10607 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10608} 10609 10610void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10611 bool DefinitionRequired) { 10612 // Ignore any vtable uses in unevaluated operands or for classes that do 10613 // not have a vtable. 10614 if (!Class->isDynamicClass() || Class->isDependentContext() || 10615 CurContext->isDependentContext() || 10616 ExprEvalContexts.back().Context == Unevaluated) 10617 return; 10618 10619 // Try to insert this class into the map. 10620 LoadExternalVTableUses(); 10621 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10622 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10623 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10624 if (!Pos.second) { 10625 // If we already had an entry, check to see if we are promoting this vtable 10626 // to required a definition. If so, we need to reappend to the VTableUses 10627 // list, since we may have already processed the first entry. 10628 if (DefinitionRequired && !Pos.first->second) { 10629 Pos.first->second = true; 10630 } else { 10631 // Otherwise, we can early exit. 10632 return; 10633 } 10634 } 10635 10636 // Local classes need to have their virtual members marked 10637 // immediately. For all other classes, we mark their virtual members 10638 // at the end of the translation unit. 10639 if (Class->isLocalClass()) 10640 MarkVirtualMembersReferenced(Loc, Class); 10641 else 10642 VTableUses.push_back(std::make_pair(Class, Loc)); 10643} 10644 10645bool Sema::DefineUsedVTables() { 10646 LoadExternalVTableUses(); 10647 if (VTableUses.empty()) 10648 return false; 10649 10650 // Note: The VTableUses vector could grow as a result of marking 10651 // the members of a class as "used", so we check the size each 10652 // time through the loop and prefer indices (with are stable) to 10653 // iterators (which are not). 10654 bool DefinedAnything = false; 10655 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10656 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10657 if (!Class) 10658 continue; 10659 10660 SourceLocation Loc = VTableUses[I].second; 10661 10662 // If this class has a key function, but that key function is 10663 // defined in another translation unit, we don't need to emit the 10664 // vtable even though we're using it. 10665 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10666 if (KeyFunction && !KeyFunction->hasBody()) { 10667 switch (KeyFunction->getTemplateSpecializationKind()) { 10668 case TSK_Undeclared: 10669 case TSK_ExplicitSpecialization: 10670 case TSK_ExplicitInstantiationDeclaration: 10671 // The key function is in another translation unit. 10672 continue; 10673 10674 case TSK_ExplicitInstantiationDefinition: 10675 case TSK_ImplicitInstantiation: 10676 // We will be instantiating the key function. 10677 break; 10678 } 10679 } else if (!KeyFunction) { 10680 // If we have a class with no key function that is the subject 10681 // of an explicit instantiation declaration, suppress the 10682 // vtable; it will live with the explicit instantiation 10683 // definition. 10684 bool IsExplicitInstantiationDeclaration 10685 = Class->getTemplateSpecializationKind() 10686 == TSK_ExplicitInstantiationDeclaration; 10687 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10688 REnd = Class->redecls_end(); 10689 R != REnd; ++R) { 10690 TemplateSpecializationKind TSK 10691 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10692 if (TSK == TSK_ExplicitInstantiationDeclaration) 10693 IsExplicitInstantiationDeclaration = true; 10694 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10695 IsExplicitInstantiationDeclaration = false; 10696 break; 10697 } 10698 } 10699 10700 if (IsExplicitInstantiationDeclaration) 10701 continue; 10702 } 10703 10704 // Mark all of the virtual members of this class as referenced, so 10705 // that we can build a vtable. Then, tell the AST consumer that a 10706 // vtable for this class is required. 10707 DefinedAnything = true; 10708 MarkVirtualMembersReferenced(Loc, Class); 10709 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10710 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10711 10712 // Optionally warn if we're emitting a weak vtable. 10713 if (Class->getLinkage() == ExternalLinkage && 10714 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10715 const FunctionDecl *KeyFunctionDef = 0; 10716 if (!KeyFunction || 10717 (KeyFunction->hasBody(KeyFunctionDef) && 10718 KeyFunctionDef->isInlined())) 10719 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 10720 } 10721 } 10722 VTableUses.clear(); 10723 10724 return DefinedAnything; 10725} 10726 10727void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10728 const CXXRecordDecl *RD) { 10729 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 10730 e = RD->method_end(); i != e; ++i) { 10731 CXXMethodDecl *MD = *i; 10732 10733 // C++ [basic.def.odr]p2: 10734 // [...] A virtual member function is used if it is not pure. [...] 10735 if (MD->isVirtual() && !MD->isPure()) 10736 MarkDeclarationReferenced(Loc, MD); 10737 } 10738 10739 // Only classes that have virtual bases need a VTT. 10740 if (RD->getNumVBases() == 0) 10741 return; 10742 10743 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10744 e = RD->bases_end(); i != e; ++i) { 10745 const CXXRecordDecl *Base = 10746 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10747 if (Base->getNumVBases() == 0) 10748 continue; 10749 MarkVirtualMembersReferenced(Loc, Base); 10750 } 10751} 10752 10753/// SetIvarInitializers - This routine builds initialization ASTs for the 10754/// Objective-C implementation whose ivars need be initialized. 10755void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10756 if (!getLangOptions().CPlusPlus) 10757 return; 10758 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10759 SmallVector<ObjCIvarDecl*, 8> ivars; 10760 CollectIvarsToConstructOrDestruct(OID, ivars); 10761 if (ivars.empty()) 10762 return; 10763 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10764 for (unsigned i = 0; i < ivars.size(); i++) { 10765 FieldDecl *Field = ivars[i]; 10766 if (Field->isInvalidDecl()) 10767 continue; 10768 10769 CXXCtorInitializer *Member; 10770 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10771 InitializationKind InitKind = 10772 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10773 10774 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10775 ExprResult MemberInit = 10776 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10777 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10778 // Note, MemberInit could actually come back empty if no initialization 10779 // is required (e.g., because it would call a trivial default constructor) 10780 if (!MemberInit.get() || MemberInit.isInvalid()) 10781 continue; 10782 10783 Member = 10784 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10785 SourceLocation(), 10786 MemberInit.takeAs<Expr>(), 10787 SourceLocation()); 10788 AllToInit.push_back(Member); 10789 10790 // Be sure that the destructor is accessible and is marked as referenced. 10791 if (const RecordType *RecordTy 10792 = Context.getBaseElementType(Field->getType()) 10793 ->getAs<RecordType>()) { 10794 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10795 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10796 MarkDeclarationReferenced(Field->getLocation(), Destructor); 10797 CheckDestructorAccess(Field->getLocation(), Destructor, 10798 PDiag(diag::err_access_dtor_ivar) 10799 << Context.getBaseElementType(Field->getType())); 10800 } 10801 } 10802 } 10803 ObjCImplementation->setIvarInitializers(Context, 10804 AllToInit.data(), AllToInit.size()); 10805 } 10806} 10807 10808static 10809void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10810 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10811 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10812 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10813 Sema &S) { 10814 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10815 CE = Current.end(); 10816 if (Ctor->isInvalidDecl()) 10817 return; 10818 10819 const FunctionDecl *FNTarget = 0; 10820 CXXConstructorDecl *Target; 10821 10822 // We ignore the result here since if we don't have a body, Target will be 10823 // null below. 10824 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10825 Target 10826= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10827 10828 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10829 // Avoid dereferencing a null pointer here. 10830 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10831 10832 if (!Current.insert(Canonical)) 10833 return; 10834 10835 // We know that beyond here, we aren't chaining into a cycle. 10836 if (!Target || !Target->isDelegatingConstructor() || 10837 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10838 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10839 Valid.insert(*CI); 10840 Current.clear(); 10841 // We've hit a cycle. 10842 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10843 Current.count(TCanonical)) { 10844 // If we haven't diagnosed this cycle yet, do so now. 10845 if (!Invalid.count(TCanonical)) { 10846 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10847 diag::warn_delegating_ctor_cycle) 10848 << Ctor; 10849 10850 // Don't add a note for a function delegating directo to itself. 10851 if (TCanonical != Canonical) 10852 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 10853 10854 CXXConstructorDecl *C = Target; 10855 while (C->getCanonicalDecl() != Canonical) { 10856 (void)C->getTargetConstructor()->hasBody(FNTarget); 10857 assert(FNTarget && "Ctor cycle through bodiless function"); 10858 10859 C 10860 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 10861 S.Diag(C->getLocation(), diag::note_which_delegates_to); 10862 } 10863 } 10864 10865 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10866 Invalid.insert(*CI); 10867 Current.clear(); 10868 } else { 10869 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 10870 } 10871} 10872 10873 10874void Sema::CheckDelegatingCtorCycles() { 10875 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 10876 10877 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10878 CE = Current.end(); 10879 10880 for (DelegatingCtorDeclsType::iterator 10881 I = DelegatingCtorDecls.begin(ExternalSource), 10882 E = DelegatingCtorDecls.end(); 10883 I != E; ++I) { 10884 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 10885 } 10886 10887 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 10888 (*CI)->setInvalidDecl(); 10889} 10890 10891/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 10892Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 10893 // Implicitly declared functions (e.g. copy constructors) are 10894 // __host__ __device__ 10895 if (D->isImplicit()) 10896 return CFT_HostDevice; 10897 10898 if (D->hasAttr<CUDAGlobalAttr>()) 10899 return CFT_Global; 10900 10901 if (D->hasAttr<CUDADeviceAttr>()) { 10902 if (D->hasAttr<CUDAHostAttr>()) 10903 return CFT_HostDevice; 10904 else 10905 return CFT_Device; 10906 } 10907 10908 return CFT_Host; 10909} 10910 10911bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 10912 CUDAFunctionTarget CalleeTarget) { 10913 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 10914 // Callable from the device only." 10915 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 10916 return true; 10917 10918 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 10919 // Callable from the host only." 10920 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 10921 // Callable from the host only." 10922 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 10923 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 10924 return true; 10925 10926 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 10927 return true; 10928 10929 return false; 10930} 10931