1193326Sed//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements semantic analysis for C++ declarations.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14212904Sdim#include "clang/Sema/SemaInternal.h"
15193326Sed#include "clang/AST/ASTConsumer.h"
16193326Sed#include "clang/AST/ASTContext.h"
17263508Sdim#include "clang/AST/ASTLambda.h"
18221345Sdim#include "clang/AST/ASTMutationListener.h"
19249423Sdim#include "clang/AST/CXXInheritance.h"
20207619Srdivacky#include "clang/AST/CharUnits.h"
21193326Sed#include "clang/AST/DeclVisitor.h"
22239462Sdim#include "clang/AST/EvaluatedExprVisitor.h"
23221345Sdim#include "clang/AST/ExprCXX.h"
24207619Srdivacky#include "clang/AST/RecordLayout.h"
25234982Sdim#include "clang/AST/RecursiveASTVisitor.h"
26207619Srdivacky#include "clang/AST/StmtVisitor.h"
27200583Srdivacky#include "clang/AST/TypeLoc.h"
28193326Sed#include "clang/AST/TypeOrdering.h"
29249423Sdim#include "clang/Basic/PartialDiagnostic.h"
30249423Sdim#include "clang/Basic/TargetInfo.h"
31263508Sdim#include "clang/Lex/LiteralSupport.h"
32249423Sdim#include "clang/Lex/Preprocessor.h"
33249423Sdim#include "clang/Sema/CXXFieldCollector.h"
34212904Sdim#include "clang/Sema/DeclSpec.h"
35249423Sdim#include "clang/Sema/Initialization.h"
36249423Sdim#include "clang/Sema/Lookup.h"
37212904Sdim#include "clang/Sema/ParsedTemplate.h"
38249423Sdim#include "clang/Sema/Scope.h"
39249423Sdim#include "clang/Sema/ScopeInfo.h"
40249423Sdim#include "llvm/ADT/STLExtras.h"
41234353Sdim#include "llvm/ADT/SmallString.h"
42193326Sed#include <map>
43198092Srdivacky#include <set>
44193326Sed
45193326Sedusing namespace clang;
46193326Sed
47193326Sed//===----------------------------------------------------------------------===//
48193326Sed// CheckDefaultArgumentVisitor
49193326Sed//===----------------------------------------------------------------------===//
50193326Sed
51193326Sednamespace {
52193326Sed  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53193326Sed  /// the default argument of a parameter to determine whether it
54193326Sed  /// contains any ill-formed subexpressions. For example, this will
55193326Sed  /// diagnose the use of local variables or parameters within the
56193326Sed  /// default argument expression.
57199990Srdivacky  class CheckDefaultArgumentVisitor
58193326Sed    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59193326Sed    Expr *DefaultArg;
60193326Sed    Sema *S;
61193326Sed
62193326Sed  public:
63198092Srdivacky    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64193326Sed      : DefaultArg(defarg), S(s) {}
65193326Sed
66193326Sed    bool VisitExpr(Expr *Node);
67193326Sed    bool VisitDeclRefExpr(DeclRefExpr *DRE);
68193326Sed    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69234353Sdim    bool VisitLambdaExpr(LambdaExpr *Lambda);
70251662Sdim    bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71193326Sed  };
72193326Sed
73193326Sed  /// VisitExpr - Visit all of the children of this expression.
74193326Sed  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75193326Sed    bool IsInvalid = false;
76218893Sdim    for (Stmt::child_range I = Node->children(); I; ++I)
77193326Sed      IsInvalid |= Visit(*I);
78193326Sed    return IsInvalid;
79193326Sed  }
80193326Sed
81193326Sed  /// VisitDeclRefExpr - Visit a reference to a declaration, to
82193326Sed  /// determine whether this declaration can be used in the default
83193326Sed  /// argument expression.
84193326Sed  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85193326Sed    NamedDecl *Decl = DRE->getDecl();
86193326Sed    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87193326Sed      // C++ [dcl.fct.default]p9
88193326Sed      //   Default arguments are evaluated each time the function is
89193326Sed      //   called. The order of evaluation of function arguments is
90193326Sed      //   unspecified. Consequently, parameters of a function shall not
91193326Sed      //   be used in default argument expressions, even if they are not
92193326Sed      //   evaluated. Parameters of a function declared before a default
93193326Sed      //   argument expression are in scope and can hide namespace and
94193326Sed      //   class member names.
95234353Sdim      return S->Diag(DRE->getLocStart(),
96193326Sed                     diag::err_param_default_argument_references_param)
97193326Sed         << Param->getDeclName() << DefaultArg->getSourceRange();
98193326Sed    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99193326Sed      // C++ [dcl.fct.default]p7
100193326Sed      //   Local variables shall not be used in default argument
101193326Sed      //   expressions.
102218893Sdim      if (VDecl->isLocalVarDecl())
103234353Sdim        return S->Diag(DRE->getLocStart(),
104193326Sed                       diag::err_param_default_argument_references_local)
105193326Sed          << VDecl->getDeclName() << DefaultArg->getSourceRange();
106193326Sed    }
107193326Sed
108193326Sed    return false;
109193326Sed  }
110193326Sed
111193326Sed  /// VisitCXXThisExpr - Visit a C++ "this" expression.
112193326Sed  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113193326Sed    // C++ [dcl.fct.default]p8:
114193326Sed    //   The keyword this shall not be used in a default argument of a
115193326Sed    //   member function.
116234353Sdim    return S->Diag(ThisE->getLocStart(),
117193326Sed                   diag::err_param_default_argument_references_this)
118193326Sed               << ThisE->getSourceRange();
119193326Sed  }
120234353Sdim
121251662Sdim  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122251662Sdim    bool Invalid = false;
123251662Sdim    for (PseudoObjectExpr::semantics_iterator
124251662Sdim           i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125251662Sdim      Expr *E = *i;
126251662Sdim
127251662Sdim      // Look through bindings.
128251662Sdim      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129251662Sdim        E = OVE->getSourceExpr();
130251662Sdim        assert(E && "pseudo-object binding without source expression?");
131251662Sdim      }
132251662Sdim
133251662Sdim      Invalid |= Visit(E);
134251662Sdim    }
135251662Sdim    return Invalid;
136251662Sdim  }
137251662Sdim
138234353Sdim  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139234353Sdim    // C++11 [expr.lambda.prim]p13:
140234353Sdim    //   A lambda-expression appearing in a default argument shall not
141234353Sdim    //   implicitly or explicitly capture any entity.
142234353Sdim    if (Lambda->capture_begin() == Lambda->capture_end())
143234353Sdim      return false;
144234353Sdim
145234353Sdim    return S->Diag(Lambda->getLocStart(),
146234353Sdim                   diag::err_lambda_capture_default_arg);
147234353Sdim  }
148193326Sed}
149193326Sed
150251662Sdimvoid
151251662SdimSema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152251662Sdim                                                 const CXXMethodDecl *Method) {
153239462Sdim  // If we have an MSAny spec already, don't bother.
154239462Sdim  if (!Method || ComputedEST == EST_MSAny)
155223017Sdim    return;
156223017Sdim
157223017Sdim  const FunctionProtoType *Proto
158223017Sdim    = Method->getType()->getAs<FunctionProtoType>();
159234982Sdim  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160234982Sdim  if (!Proto)
161234982Sdim    return;
162223017Sdim
163223017Sdim  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164223017Sdim
165223017Sdim  // If this function can throw any exceptions, make a note of that.
166239462Sdim  if (EST == EST_MSAny || EST == EST_None) {
167223017Sdim    ClearExceptions();
168223017Sdim    ComputedEST = EST;
169223017Sdim    return;
170223017Sdim  }
171223017Sdim
172223017Sdim  // FIXME: If the call to this decl is using any of its default arguments, we
173223017Sdim  // need to search them for potentially-throwing calls.
174223017Sdim
175223017Sdim  // If this function has a basic noexcept, it doesn't affect the outcome.
176223017Sdim  if (EST == EST_BasicNoexcept)
177223017Sdim    return;
178223017Sdim
179223017Sdim  // If we have a throw-all spec at this point, ignore the function.
180223017Sdim  if (ComputedEST == EST_None)
181223017Sdim    return;
182223017Sdim
183223017Sdim  // If we're still at noexcept(true) and there's a nothrow() callee,
184223017Sdim  // change to that specification.
185223017Sdim  if (EST == EST_DynamicNone) {
186223017Sdim    if (ComputedEST == EST_BasicNoexcept)
187223017Sdim      ComputedEST = EST_DynamicNone;
188223017Sdim    return;
189223017Sdim  }
190223017Sdim
191223017Sdim  // Check out noexcept specs.
192223017Sdim  if (EST == EST_ComputedNoexcept) {
193234982Sdim    FunctionProtoType::NoexceptResult NR =
194234982Sdim        Proto->getNoexceptSpec(Self->Context);
195223017Sdim    assert(NR != FunctionProtoType::NR_NoNoexcept &&
196223017Sdim           "Must have noexcept result for EST_ComputedNoexcept.");
197223017Sdim    assert(NR != FunctionProtoType::NR_Dependent &&
198223017Sdim           "Should not generate implicit declarations for dependent cases, "
199223017Sdim           "and don't know how to handle them anyway.");
200223017Sdim
201223017Sdim    // noexcept(false) -> no spec on the new function
202223017Sdim    if (NR == FunctionProtoType::NR_Throw) {
203223017Sdim      ClearExceptions();
204223017Sdim      ComputedEST = EST_None;
205223017Sdim    }
206223017Sdim    // noexcept(true) won't change anything either.
207223017Sdim    return;
208223017Sdim  }
209223017Sdim
210223017Sdim  assert(EST == EST_Dynamic && "EST case not considered earlier.");
211223017Sdim  assert(ComputedEST != EST_None &&
212223017Sdim         "Shouldn't collect exceptions when throw-all is guaranteed.");
213223017Sdim  ComputedEST = EST_Dynamic;
214223017Sdim  // Record the exceptions in this function's exception specification.
215223017Sdim  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216223017Sdim                                          EEnd = Proto->exception_end();
217223017Sdim       E != EEnd; ++E)
218234982Sdim    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
219223017Sdim      Exceptions.push_back(*E);
220223017Sdim}
221223017Sdim
222223017Sdimvoid Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223239462Sdim  if (!E || ComputedEST == EST_MSAny)
224223017Sdim    return;
225223017Sdim
226223017Sdim  // FIXME:
227223017Sdim  //
228223017Sdim  // C++0x [except.spec]p14:
229224145Sdim  //   [An] implicit exception-specification specifies the type-id T if and
230224145Sdim  // only if T is allowed by the exception-specification of a function directly
231224145Sdim  // invoked by f's implicit definition; f shall allow all exceptions if any
232223017Sdim  // function it directly invokes allows all exceptions, and f shall allow no
233223017Sdim  // exceptions if every function it directly invokes allows no exceptions.
234223017Sdim  //
235223017Sdim  // Note in particular that if an implicit exception-specification is generated
236223017Sdim  // for a function containing a throw-expression, that specification can still
237223017Sdim  // be noexcept(true).
238223017Sdim  //
239223017Sdim  // Note also that 'directly invoked' is not defined in the standard, and there
240223017Sdim  // is no indication that we should only consider potentially-evaluated calls.
241223017Sdim  //
242223017Sdim  // Ultimately we should implement the intent of the standard: the exception
243223017Sdim  // specification should be the set of exceptions which can be thrown by the
244223017Sdim  // implicit definition. For now, we assume that any non-nothrow expression can
245223017Sdim  // throw any exception.
246223017Sdim
247234982Sdim  if (Self->canThrow(E))
248223017Sdim    ComputedEST = EST_None;
249223017Sdim}
250223017Sdim
251198092Srdivackybool
252212904SdimSema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253198092Srdivacky                              SourceLocation EqualLoc) {
254198092Srdivacky  if (RequireCompleteType(Param->getLocation(), Param->getType(),
255198092Srdivacky                          diag::err_typecheck_decl_incomplete_type)) {
256198092Srdivacky    Param->setInvalidDecl();
257198092Srdivacky    return true;
258198092Srdivacky  }
259198092Srdivacky
260198092Srdivacky  // C++ [dcl.fct.default]p5
261198092Srdivacky  //   A default argument expression is implicitly converted (clause
262198092Srdivacky  //   4) to the parameter type. The default argument expression has
263198092Srdivacky  //   the same semantic constraints as the initializer expression in
264198092Srdivacky  //   a declaration of a variable of the parameter type, using the
265198092Srdivacky  //   copy-initialization semantics (8.5).
266218893Sdim  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267218893Sdim                                                                    Param);
268201361Srdivacky  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269201361Srdivacky                                                           EqualLoc);
270251662Sdim  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271243830Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272201361Srdivacky  if (Result.isInvalid())
273198092Srdivacky    return true;
274201361Srdivacky  Arg = Result.takeAs<Expr>();
275198092Srdivacky
276249423Sdim  CheckCompletedExpr(Arg, EqualLoc);
277218893Sdim  Arg = MaybeCreateExprWithCleanups(Arg);
278198092Srdivacky
279198092Srdivacky  // Okay: add the default argument to the parameter
280198092Srdivacky  Param->setDefaultArg(Arg);
281198092Srdivacky
282218893Sdim  // We have already instantiated this parameter; provide each of the
283218893Sdim  // instantiations with the uninstantiated default argument.
284218893Sdim  UnparsedDefaultArgInstantiationsMap::iterator InstPos
285218893Sdim    = UnparsedDefaultArgInstantiations.find(Param);
286218893Sdim  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287218893Sdim    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288218893Sdim      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289218893Sdim
290218893Sdim    // We're done tracking this parameter's instantiations.
291218893Sdim    UnparsedDefaultArgInstantiations.erase(InstPos);
292218893Sdim  }
293218893Sdim
294198092Srdivacky  return false;
295198092Srdivacky}
296198092Srdivacky
297193326Sed/// ActOnParamDefaultArgument - Check whether the default argument
298193326Sed/// provided for a function parameter is well-formed. If so, attach it
299193326Sed/// to the parameter declaration.
300193326Sedvoid
301212904SdimSema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302212904Sdim                                Expr *DefaultArg) {
303212904Sdim  if (!param || !DefaultArg)
304194711Sed    return;
305198092Srdivacky
306212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
307194179Sed  UnparsedDefaultArgLocs.erase(Param);
308194179Sed
309193326Sed  // Default arguments are only permitted in C++
310234353Sdim  if (!getLangOpts().CPlusPlus) {
311193326Sed    Diag(EqualLoc, diag::err_param_default_argument)
312193326Sed      << DefaultArg->getSourceRange();
313193326Sed    Param->setInvalidDecl();
314193326Sed    return;
315193326Sed  }
316193326Sed
317218893Sdim  // Check for unexpanded parameter packs.
318218893Sdim  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319218893Sdim    Param->setInvalidDecl();
320218893Sdim    return;
321218893Sdim  }
322218893Sdim
323193326Sed  // Check that the default argument is well-formed
324212904Sdim  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325212904Sdim  if (DefaultArgChecker.Visit(DefaultArg)) {
326193326Sed    Param->setInvalidDecl();
327193326Sed    return;
328193326Sed  }
329193326Sed
330212904Sdim  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
331193326Sed}
332193326Sed
333193326Sed/// ActOnParamUnparsedDefaultArgument - We've seen a default
334193326Sed/// argument for a function parameter, but we can't parse it yet
335193326Sed/// because we're inside a class definition. Note that this default
336193326Sed/// argument will be parsed later.
337212904Sdimvoid Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
338194179Sed                                             SourceLocation EqualLoc,
339194179Sed                                             SourceLocation ArgLoc) {
340194711Sed  if (!param)
341194711Sed    return;
342198092Srdivacky
343212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
344263508Sdim  Param->setUnparsedDefaultArg();
345194179Sed  UnparsedDefaultArgLocs[Param] = ArgLoc;
346193326Sed}
347193326Sed
348193326Sed/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349193326Sed/// the default argument for the parameter param failed.
350212904Sdimvoid Sema::ActOnParamDefaultArgumentError(Decl *param) {
351194711Sed  if (!param)
352194711Sed    return;
353198092Srdivacky
354212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
355194179Sed  Param->setInvalidDecl();
356194179Sed  UnparsedDefaultArgLocs.erase(Param);
357193326Sed}
358193326Sed
359193326Sed/// CheckExtraCXXDefaultArguments - Check for any extra default
360193326Sed/// arguments in the declarator, which is not a function declaration
361193326Sed/// or definition and therefore is not permitted to have default
362193326Sed/// arguments. This routine should be invoked for every declarator
363193326Sed/// that is not a function declaration or definition.
364193326Sedvoid Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365193326Sed  // C++ [dcl.fct.default]p3
366193326Sed  //   A default argument expression shall be specified only in the
367193326Sed  //   parameter-declaration-clause of a function declaration or in a
368193326Sed  //   template-parameter (14.1). It shall not be specified for a
369193326Sed  //   parameter pack. If it is specified in a
370193326Sed  //   parameter-declaration-clause, it shall not occur within a
371193326Sed  //   declarator or abstract-declarator of a parameter-declaration.
372249423Sdim  bool MightBeFunction = D.isFunctionDeclarationContext();
373193326Sed  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374193326Sed    DeclaratorChunk &chunk = D.getTypeObject(i);
375193326Sed    if (chunk.Kind == DeclaratorChunk::Function) {
376249423Sdim      if (MightBeFunction) {
377249423Sdim        // This is a function declaration. It can have default arguments, but
378249423Sdim        // keep looking in case its return type is a function type with default
379249423Sdim        // arguments.
380249423Sdim        MightBeFunction = false;
381249423Sdim        continue;
382249423Sdim      }
383193326Sed      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384193326Sed        ParmVarDecl *Param =
385212904Sdim          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
386193326Sed        if (Param->hasUnparsedDefaultArg()) {
387193326Sed          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
388193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389249423Sdim            << SourceRange((*Toks)[1].getLocation(),
390249423Sdim                           Toks->back().getLocation());
391193326Sed          delete Toks;
392193326Sed          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
393193326Sed        } else if (Param->getDefaultArg()) {
394193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395193326Sed            << Param->getDefaultArg()->getSourceRange();
396193326Sed          Param->setDefaultArg(0);
397193326Sed        }
398193326Sed      }
399249423Sdim    } else if (chunk.Kind != DeclaratorChunk::Paren) {
400249423Sdim      MightBeFunction = false;
401193326Sed    }
402193326Sed  }
403193326Sed}
404193326Sed
405263508Sdimstatic bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406263508Sdim  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407263508Sdim    const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408263508Sdim    if (!PVD->hasDefaultArg())
409263508Sdim      return false;
410263508Sdim    if (!PVD->hasInheritedDefaultArg())
411263508Sdim      return true;
412263508Sdim  }
413263508Sdim  return false;
414263508Sdim}
415263508Sdim
416243830Sdim/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417243830Sdim/// function, once we already know that they have the same
418243830Sdim/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419243830Sdim/// error, false otherwise.
420234353Sdimbool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421234353Sdim                                Scope *S) {
422193326Sed  bool Invalid = false;
423193326Sed
424193326Sed  // C++ [dcl.fct.default]p4:
425193326Sed  //   For non-template functions, default arguments can be added in
426193326Sed  //   later declarations of a function in the same
427193326Sed  //   scope. Declarations in different scopes have completely
428193326Sed  //   distinct sets of default arguments. That is, declarations in
429193326Sed  //   inner scopes do not acquire default arguments from
430193326Sed  //   declarations in outer scopes, and vice versa. In a given
431193326Sed  //   function declaration, all parameters subsequent to a
432193326Sed  //   parameter with a default argument shall have default
433193326Sed  //   arguments supplied in this or previous declarations. A
434193326Sed  //   default argument shall not be redefined by a later
435193326Sed  //   declaration (not even to the same value).
436198092Srdivacky  //
437198092Srdivacky  // C++ [dcl.fct.default]p6:
438263508Sdim  //   Except for member functions of class templates, the default arguments
439263508Sdim  //   in a member function definition that appears outside of the class
440263508Sdim  //   definition are added to the set of default arguments provided by the
441198092Srdivacky  //   member function declaration in the class definition.
442193326Sed  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443193326Sed    ParmVarDecl *OldParam = Old->getParamDecl(p);
444193326Sed    ParmVarDecl *NewParam = New->getParamDecl(p);
445193326Sed
446234353Sdim    bool OldParamHasDfl = OldParam->hasDefaultArg();
447234353Sdim    bool NewParamHasDfl = NewParam->hasDefaultArg();
448221345Sdim
449234353Sdim    NamedDecl *ND = Old;
450263508Sdim
451263508Sdim    // The declaration context corresponding to the scope is the semantic
452263508Sdim    // parent, unless this is a local function declaration, in which case
453263508Sdim    // it is that surrounding function.
454263508Sdim    DeclContext *ScopeDC = New->getLexicalDeclContext();
455263508Sdim    if (!ScopeDC->isFunctionOrMethod())
456263508Sdim      ScopeDC = New->getDeclContext();
457263508Sdim    if (S && !isDeclInScope(ND, ScopeDC, S) &&
458263508Sdim        !New->getDeclContext()->isRecord())
459234353Sdim      // Ignore default parameters of old decl if they are not in
460263508Sdim      // the same scope and this is not an out-of-line definition of
461263508Sdim      // a member function.
462234353Sdim      OldParamHasDfl = false;
463234353Sdim
464234353Sdim    if (OldParamHasDfl && NewParamHasDfl) {
465234353Sdim
466221345Sdim      unsigned DiagDefaultParamID =
467221345Sdim        diag::err_param_default_argument_redefinition;
468221345Sdim
469221345Sdim      // MSVC accepts that default parameters be redefined for member functions
470221345Sdim      // of template class. The new default parameter's value is ignored.
471221345Sdim      Invalid = true;
472234353Sdim      if (getLangOpts().MicrosoftExt) {
473221345Sdim        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474221345Sdim        if (MD && MD->getParent()->getDescribedClassTemplate()) {
475221345Sdim          // Merge the old default argument into the new parameter.
476221345Sdim          NewParam->setHasInheritedDefaultArg();
477221345Sdim          if (OldParam->hasUninstantiatedDefaultArg())
478221345Sdim            NewParam->setUninstantiatedDefaultArg(
479221345Sdim                                      OldParam->getUninstantiatedDefaultArg());
480221345Sdim          else
481221345Sdim            NewParam->setDefaultArg(OldParam->getInit());
482221345Sdim          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
483221345Sdim          Invalid = false;
484221345Sdim        }
485221345Sdim      }
486221345Sdim
487202379Srdivacky      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488202379Srdivacky      // hint here. Alternatively, we could walk the type-source information
489202379Srdivacky      // for NewParam to find the last source location in the type... but it
490202379Srdivacky      // isn't worth the effort right now. This is the kind of test case that
491202379Srdivacky      // is hard to get right:
492202379Srdivacky      //   int f(int);
493202379Srdivacky      //   void g(int (*fp)(int) = f);
494202379Srdivacky      //   void g(int (*fp)(int) = &f);
495221345Sdim      Diag(NewParam->getLocation(), DiagDefaultParamID)
496202379Srdivacky        << NewParam->getDefaultArgRange();
497198092Srdivacky
498198092Srdivacky      // Look for the function declaration where the default argument was
499198092Srdivacky      // actually written, which may be a declaration prior to Old.
500234353Sdim      for (FunctionDecl *Older = Old->getPreviousDecl();
501234353Sdim           Older; Older = Older->getPreviousDecl()) {
502198092Srdivacky        if (!Older->getParamDecl(p)->hasDefaultArg())
503198092Srdivacky          break;
504198092Srdivacky
505198092Srdivacky        OldParam = Older->getParamDecl(p);
506198092Srdivacky      }
507198092Srdivacky
508198092Srdivacky      Diag(OldParam->getLocation(), diag::note_previous_definition)
509198092Srdivacky        << OldParam->getDefaultArgRange();
510234353Sdim    } else if (OldParamHasDfl) {
511207619Srdivacky      // Merge the old default argument into the new parameter.
512207619Srdivacky      // It's important to use getInit() here;  getDefaultArg()
513218893Sdim      // strips off any top-level ExprWithCleanups.
514205219Srdivacky      NewParam->setHasInheritedDefaultArg();
515198092Srdivacky      if (OldParam->hasUninstantiatedDefaultArg())
516198092Srdivacky        NewParam->setUninstantiatedDefaultArg(
517198092Srdivacky                                      OldParam->getUninstantiatedDefaultArg());
518198092Srdivacky      else
519207619Srdivacky        NewParam->setDefaultArg(OldParam->getInit());
520234353Sdim    } else if (NewParamHasDfl) {
521198092Srdivacky      if (New->getDescribedFunctionTemplate()) {
522198092Srdivacky        // Paragraph 4, quoted above, only applies to non-template functions.
523198092Srdivacky        Diag(NewParam->getLocation(),
524198092Srdivacky             diag::err_param_default_argument_template_redecl)
525198092Srdivacky          << NewParam->getDefaultArgRange();
526198092Srdivacky        Diag(Old->getLocation(), diag::note_template_prev_declaration)
527198092Srdivacky          << false;
528198092Srdivacky      } else if (New->getTemplateSpecializationKind()
529198092Srdivacky                   != TSK_ImplicitInstantiation &&
530198092Srdivacky                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531198092Srdivacky        // C++ [temp.expr.spec]p21:
532198092Srdivacky        //   Default function arguments shall not be specified in a declaration
533198092Srdivacky        //   or a definition for one of the following explicit specializations:
534198092Srdivacky        //     - the explicit specialization of a function template;
535198092Srdivacky        //     - the explicit specialization of a member function template;
536198092Srdivacky        //     - the explicit specialization of a member function of a class
537198092Srdivacky        //       template where the class template specialization to which the
538198092Srdivacky        //       member function specialization belongs is implicitly
539198092Srdivacky        //       instantiated.
540198092Srdivacky        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541198092Srdivacky          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542198092Srdivacky          << New->getDeclName()
543198092Srdivacky          << NewParam->getDefaultArgRange();
544198092Srdivacky      } else if (New->getDeclContext()->isDependentContext()) {
545198092Srdivacky        // C++ [dcl.fct.default]p6 (DR217):
546198092Srdivacky        //   Default arguments for a member function of a class template shall
547198092Srdivacky        //   be specified on the initial declaration of the member function
548198092Srdivacky        //   within the class template.
549198092Srdivacky        //
550198092Srdivacky        // Reading the tea leaves a bit in DR217 and its reference to DR205
551198092Srdivacky        // leads me to the conclusion that one cannot add default function
552198092Srdivacky        // arguments for an out-of-line definition of a member function of a
553198092Srdivacky        // dependent type.
554198092Srdivacky        int WhichKind = 2;
555198092Srdivacky        if (CXXRecordDecl *Record
556198092Srdivacky              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557198092Srdivacky          if (Record->getDescribedClassTemplate())
558198092Srdivacky            WhichKind = 0;
559198092Srdivacky          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560198092Srdivacky            WhichKind = 1;
561198092Srdivacky          else
562198092Srdivacky            WhichKind = 2;
563198092Srdivacky        }
564198092Srdivacky
565198092Srdivacky        Diag(NewParam->getLocation(),
566198092Srdivacky             diag::err_param_default_argument_member_template_redecl)
567198092Srdivacky          << WhichKind
568198092Srdivacky          << NewParam->getDefaultArgRange();
569198092Srdivacky      }
570193326Sed    }
571193326Sed  }
572193326Sed
573249423Sdim  // DR1344: If a default argument is added outside a class definition and that
574249423Sdim  // default argument makes the function a special member function, the program
575249423Sdim  // is ill-formed. This can only happen for constructors.
576249423Sdim  if (isa<CXXConstructorDecl>(New) &&
577249423Sdim      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578249423Sdim    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579249423Sdim                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580249423Sdim    if (NewSM != OldSM) {
581249423Sdim      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582249423Sdim      assert(NewParam->hasDefaultArg());
583249423Sdim      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584249423Sdim        << NewParam->getDefaultArgRange() << NewSM;
585249423Sdim      Diag(Old->getLocation(), diag::note_previous_declaration);
586249423Sdim    }
587249423Sdim  }
588249423Sdim
589234353Sdim  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
590226633Sdim  // template has a constexpr specifier then all its declarations shall
591234353Sdim  // contain the constexpr specifier.
592226633Sdim  if (New->isConstexpr() != Old->isConstexpr()) {
593226633Sdim    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594226633Sdim      << New << New->isConstexpr();
595226633Sdim    Diag(Old->getLocation(), diag::note_previous_declaration);
596226633Sdim    Invalid = true;
597226633Sdim  }
598226633Sdim
599263508Sdim  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
600263508Sdim  // argument expression, that declaration shall be a definition and shall be
601263508Sdim  // the only declaration of the function or function template in the
602263508Sdim  // translation unit.
603263508Sdim  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604263508Sdim      functionDeclHasDefaultArgument(Old)) {
605263508Sdim    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606263508Sdim    Diag(Old->getLocation(), diag::note_previous_declaration);
607263508Sdim    Invalid = true;
608263508Sdim  }
609263508Sdim
610203955Srdivacky  if (CheckEquivalentExceptionSpec(Old, New))
611195341Sed    Invalid = true;
612195341Sed
613193326Sed  return Invalid;
614193326Sed}
615193326Sed
616221345Sdim/// \brief Merge the exception specifications of two variable declarations.
617221345Sdim///
618221345Sdim/// This is called when there's a redeclaration of a VarDecl. The function
619221345Sdim/// checks if the redeclaration might have an exception specification and
620221345Sdim/// validates compatibility and merges the specs if necessary.
621221345Sdimvoid Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622221345Sdim  // Shortcut if exceptions are disabled.
623234353Sdim  if (!getLangOpts().CXXExceptions)
624221345Sdim    return;
625221345Sdim
626221345Sdim  assert(Context.hasSameType(New->getType(), Old->getType()) &&
627221345Sdim         "Should only be called if types are otherwise the same.");
628221345Sdim
629221345Sdim  QualType NewType = New->getType();
630221345Sdim  QualType OldType = Old->getType();
631221345Sdim
632221345Sdim  // We're only interested in pointers and references to functions, as well
633221345Sdim  // as pointers to member functions.
634221345Sdim  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635221345Sdim    NewType = R->getPointeeType();
636221345Sdim    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637221345Sdim  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638221345Sdim    NewType = P->getPointeeType();
639221345Sdim    OldType = OldType->getAs<PointerType>()->getPointeeType();
640221345Sdim  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641221345Sdim    NewType = M->getPointeeType();
642221345Sdim    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643221345Sdim  }
644221345Sdim
645221345Sdim  if (!NewType->isFunctionProtoType())
646221345Sdim    return;
647221345Sdim
648221345Sdim  // There's lots of special cases for functions. For function pointers, system
649221345Sdim  // libraries are hopefully not as broken so that we don't need these
650221345Sdim  // workarounds.
651221345Sdim  if (CheckEquivalentExceptionSpec(
652221345Sdim        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653221345Sdim        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654221345Sdim    New->setInvalidDecl();
655221345Sdim  }
656221345Sdim}
657221345Sdim
658193326Sed/// CheckCXXDefaultArguments - Verify that the default arguments for a
659193326Sed/// function declaration are well-formed according to C++
660193326Sed/// [dcl.fct.default].
661193326Sedvoid Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662193326Sed  unsigned NumParams = FD->getNumParams();
663193326Sed  unsigned p;
664193326Sed
665193326Sed  // Find first parameter with a default argument
666193326Sed  for (p = 0; p < NumParams; ++p) {
667193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
668251662Sdim    if (Param->hasDefaultArg())
669193326Sed      break;
670193326Sed  }
671193326Sed
672193326Sed  // C++ [dcl.fct.default]p4:
673193326Sed  //   In a given function declaration, all parameters
674193326Sed  //   subsequent to a parameter with a default argument shall
675193326Sed  //   have default arguments supplied in this or previous
676193326Sed  //   declarations. A default argument shall not be redefined
677193326Sed  //   by a later declaration (not even to the same value).
678193326Sed  unsigned LastMissingDefaultArg = 0;
679198092Srdivacky  for (; p < NumParams; ++p) {
680193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
681198092Srdivacky    if (!Param->hasDefaultArg()) {
682193326Sed      if (Param->isInvalidDecl())
683193326Sed        /* We already complained about this parameter. */;
684193326Sed      else if (Param->getIdentifier())
685198092Srdivacky        Diag(Param->getLocation(),
686193326Sed             diag::err_param_default_argument_missing_name)
687193326Sed          << Param->getIdentifier();
688193326Sed      else
689198092Srdivacky        Diag(Param->getLocation(),
690193326Sed             diag::err_param_default_argument_missing);
691198092Srdivacky
692193326Sed      LastMissingDefaultArg = p;
693193326Sed    }
694193326Sed  }
695193326Sed
696193326Sed  if (LastMissingDefaultArg > 0) {
697193326Sed    // Some default arguments were missing. Clear out all of the
698193326Sed    // default arguments up to (and including) the last missing
699193326Sed    // default argument, so that we leave the function parameters
700193326Sed    // in a semantically valid state.
701193326Sed    for (p = 0; p <= LastMissingDefaultArg; ++p) {
702193326Sed      ParmVarDecl *Param = FD->getParamDecl(p);
703194179Sed      if (Param->hasDefaultArg()) {
704193326Sed        Param->setDefaultArg(0);
705193326Sed      }
706193326Sed    }
707193326Sed  }
708193326Sed}
709193326Sed
710226633Sdim// CheckConstexprParameterTypes - Check whether a function's parameter types
711226633Sdim// are all literal types. If so, return true. If not, produce a suitable
712234353Sdim// diagnostic and return false.
713234353Sdimstatic bool CheckConstexprParameterTypes(Sema &SemaRef,
714234353Sdim                                         const FunctionDecl *FD) {
715226633Sdim  unsigned ArgIndex = 0;
716226633Sdim  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717226633Sdim  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718226633Sdim       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719226633Sdim    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720226633Sdim    SourceLocation ParamLoc = PD->getLocation();
721226633Sdim    if (!(*i)->isDependentType() &&
722234353Sdim        SemaRef.RequireLiteralType(ParamLoc, *i,
723239462Sdim                                   diag::err_constexpr_non_literal_param,
724239462Sdim                                   ArgIndex+1, PD->getSourceRange(),
725239462Sdim                                   isa<CXXConstructorDecl>(FD)))
726226633Sdim      return false;
727226633Sdim  }
728226633Sdim  return true;
729226633Sdim}
730226633Sdim
731243830Sdim/// \brief Get diagnostic %select index for tag kind for
732243830Sdim/// record diagnostic message.
733243830Sdim/// WARNING: Indexes apply to particular diagnostics only!
734243830Sdim///
735243830Sdim/// \returns diagnostic %select index.
736243830Sdimstatic unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
737243830Sdim  switch (Tag) {
738243830Sdim  case TTK_Struct: return 0;
739243830Sdim  case TTK_Interface: return 1;
740243830Sdim  case TTK_Class:  return 2;
741243830Sdim  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
742243830Sdim  }
743243830Sdim}
744243830Sdim
745226633Sdim// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746234353Sdim// the requirements of a constexpr function definition or a constexpr
747234353Sdim// constructor definition. If so, return true. If not, produce appropriate
748234353Sdim// diagnostics and return false.
749226633Sdim//
750234353Sdim// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751234353Sdimbool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
752234353Sdim  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753234353Sdim  if (MD && MD->isInstance()) {
754234353Sdim    // C++11 [dcl.constexpr]p4:
755234353Sdim    //  The definition of a constexpr constructor shall satisfy the following
756234353Sdim    //  constraints:
757226633Sdim    //  - the class shall not have any virtual base classes;
758234353Sdim    const CXXRecordDecl *RD = MD->getParent();
759226633Sdim    if (RD->getNumVBases()) {
760234353Sdim      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761243830Sdim        << isa<CXXConstructorDecl>(NewFD)
762243830Sdim        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763234353Sdim      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764234353Sdim             E = RD->vbases_end(); I != E; ++I)
765234353Sdim        Diag(I->getLocStart(),
766234353Sdim             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
767226633Sdim      return false;
768226633Sdim    }
769234353Sdim  }
770234353Sdim
771234353Sdim  if (!isa<CXXConstructorDecl>(NewFD)) {
772234353Sdim    // C++11 [dcl.constexpr]p3:
773226633Sdim    //  The definition of a constexpr function shall satisfy the following
774226633Sdim    //  constraints:
775226633Sdim    // - it shall not be virtual;
776226633Sdim    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777226633Sdim    if (Method && Method->isVirtual()) {
778234353Sdim      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
779226633Sdim
780234353Sdim      // If it's not obvious why this function is virtual, find an overridden
781234353Sdim      // function which uses the 'virtual' keyword.
782234353Sdim      const CXXMethodDecl *WrittenVirtual = Method;
783234353Sdim      while (!WrittenVirtual->isVirtualAsWritten())
784234353Sdim        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785234353Sdim      if (WrittenVirtual != Method)
786234353Sdim        Diag(WrittenVirtual->getLocation(),
787234353Sdim             diag::note_overridden_virtual_function);
788226633Sdim      return false;
789226633Sdim    }
790226633Sdim
791226633Sdim    // - its return type shall be a literal type;
792226633Sdim    QualType RT = NewFD->getResultType();
793226633Sdim    if (!RT->isDependentType() &&
794234353Sdim        RequireLiteralType(NewFD->getLocation(), RT,
795239462Sdim                           diag::err_constexpr_non_literal_return))
796226633Sdim      return false;
797226633Sdim  }
798226633Sdim
799234353Sdim  // - each of its parameter types shall be a literal type;
800234353Sdim  if (!CheckConstexprParameterTypes(*this, NewFD))
801234353Sdim    return false;
802234353Sdim
803226633Sdim  return true;
804226633Sdim}
805226633Sdim
806226633Sdim/// Check the given declaration statement is legal within a constexpr function
807251662Sdim/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
808226633Sdim///
809251662Sdim/// \return true if the body is OK (maybe only as an extension), false if we
810251662Sdim///         have diagnosed a problem.
811226633Sdimstatic bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
812251662Sdim                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813251662Sdim  // C++11 [dcl.constexpr]p3 and p4:
814226633Sdim  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
815226633Sdim  //  contain only
816226633Sdim  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817226633Sdim         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818226633Sdim    switch ((*DclIt)->getKind()) {
819226633Sdim    case Decl::StaticAssert:
820226633Sdim    case Decl::Using:
821226633Sdim    case Decl::UsingShadow:
822226633Sdim    case Decl::UsingDirective:
823226633Sdim    case Decl::UnresolvedUsingTypename:
824251662Sdim    case Decl::UnresolvedUsingValue:
825226633Sdim      //   - static_assert-declarations
826226633Sdim      //   - using-declarations,
827226633Sdim      //   - using-directives,
828226633Sdim      continue;
829226633Sdim
830226633Sdim    case Decl::Typedef:
831226633Sdim    case Decl::TypeAlias: {
832226633Sdim      //   - typedef declarations and alias-declarations that do not define
833226633Sdim      //     classes or enumerations,
834226633Sdim      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835226633Sdim      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836226633Sdim        // Don't allow variably-modified types in constexpr functions.
837226633Sdim        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838226633Sdim        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839226633Sdim          << TL.getSourceRange() << TL.getType()
840226633Sdim          << isa<CXXConstructorDecl>(Dcl);
841226633Sdim        return false;
842226633Sdim      }
843226633Sdim      continue;
844226633Sdim    }
845226633Sdim
846226633Sdim    case Decl::Enum:
847226633Sdim    case Decl::CXXRecord:
848251662Sdim      // C++1y allows types to be defined, not just declared.
849251662Sdim      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850251662Sdim        SemaRef.Diag(DS->getLocStart(),
851251662Sdim                     SemaRef.getLangOpts().CPlusPlus1y
852251662Sdim                       ? diag::warn_cxx11_compat_constexpr_type_definition
853251662Sdim                       : diag::ext_constexpr_type_definition)
854226633Sdim          << isa<CXXConstructorDecl>(Dcl);
855226633Sdim      continue;
856226633Sdim
857251662Sdim    case Decl::EnumConstant:
858251662Sdim    case Decl::IndirectField:
859251662Sdim    case Decl::ParmVar:
860251662Sdim      // These can only appear with other declarations which are banned in
861251662Sdim      // C++11 and permitted in C++1y, so ignore them.
862251662Sdim      continue;
863251662Sdim
864251662Sdim    case Decl::Var: {
865251662Sdim      // C++1y [dcl.constexpr]p3 allows anything except:
866251662Sdim      //   a definition of a variable of non-literal type or of static or
867251662Sdim      //   thread storage duration or for which no initialization is performed.
868251662Sdim      VarDecl *VD = cast<VarDecl>(*DclIt);
869251662Sdim      if (VD->isThisDeclarationADefinition()) {
870251662Sdim        if (VD->isStaticLocal()) {
871251662Sdim          SemaRef.Diag(VD->getLocation(),
872251662Sdim                       diag::err_constexpr_local_var_static)
873251662Sdim            << isa<CXXConstructorDecl>(Dcl)
874251662Sdim            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875251662Sdim          return false;
876251662Sdim        }
877251662Sdim        if (!VD->getType()->isDependentType() &&
878251662Sdim            SemaRef.RequireLiteralType(
879251662Sdim              VD->getLocation(), VD->getType(),
880251662Sdim              diag::err_constexpr_local_var_non_literal_type,
881251662Sdim              isa<CXXConstructorDecl>(Dcl)))
882251662Sdim          return false;
883263508Sdim        if (!VD->hasInit() && !VD->isCXXForRangeDecl()) {
884251662Sdim          SemaRef.Diag(VD->getLocation(),
885251662Sdim                       diag::err_constexpr_local_var_no_init)
886251662Sdim            << isa<CXXConstructorDecl>(Dcl);
887251662Sdim          return false;
888251662Sdim        }
889251662Sdim      }
890251662Sdim      SemaRef.Diag(VD->getLocation(),
891251662Sdim                   SemaRef.getLangOpts().CPlusPlus1y
892251662Sdim                    ? diag::warn_cxx11_compat_constexpr_local_var
893251662Sdim                    : diag::ext_constexpr_local_var)
894226633Sdim        << isa<CXXConstructorDecl>(Dcl);
895251662Sdim      continue;
896251662Sdim    }
897226633Sdim
898251662Sdim    case Decl::NamespaceAlias:
899251662Sdim    case Decl::Function:
900251662Sdim      // These are disallowed in C++11 and permitted in C++1y. Allow them
901251662Sdim      // everywhere as an extension.
902251662Sdim      if (!Cxx1yLoc.isValid())
903251662Sdim        Cxx1yLoc = DS->getLocStart();
904251662Sdim      continue;
905251662Sdim
906226633Sdim    default:
907226633Sdim      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908226633Sdim        << isa<CXXConstructorDecl>(Dcl);
909226633Sdim      return false;
910226633Sdim    }
911226633Sdim  }
912226633Sdim
913226633Sdim  return true;
914226633Sdim}
915226633Sdim
916226633Sdim/// Check that the given field is initialized within a constexpr constructor.
917226633Sdim///
918226633Sdim/// \param Dcl The constexpr constructor being checked.
919226633Sdim/// \param Field The field being checked. This may be a member of an anonymous
920226633Sdim///        struct or union nested within the class being checked.
921226633Sdim/// \param Inits All declarations, including anonymous struct/union members and
922226633Sdim///        indirect members, for which any initialization was provided.
923226633Sdim/// \param Diagnosed Set to true if an error is produced.
924226633Sdimstatic void CheckConstexprCtorInitializer(Sema &SemaRef,
925226633Sdim                                          const FunctionDecl *Dcl,
926226633Sdim                                          FieldDecl *Field,
927226633Sdim                                          llvm::SmallSet<Decl*, 16> &Inits,
928226633Sdim                                          bool &Diagnosed) {
929263508Sdim  if (Field->isInvalidDecl())
930263508Sdim    return;
931263508Sdim
932226633Sdim  if (Field->isUnnamedBitfield())
933226633Sdim    return;
934234353Sdim
935234353Sdim  if (Field->isAnonymousStructOrUnion() &&
936234353Sdim      Field->getType()->getAsCXXRecordDecl()->isEmpty())
937234353Sdim    return;
938234353Sdim
939226633Sdim  if (!Inits.count(Field)) {
940226633Sdim    if (!Diagnosed) {
941226633Sdim      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942226633Sdim      Diagnosed = true;
943226633Sdim    }
944226633Sdim    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945226633Sdim  } else if (Field->isAnonymousStructOrUnion()) {
946226633Sdim    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947226633Sdim    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948226633Sdim         I != E; ++I)
949226633Sdim      // If an anonymous union contains an anonymous struct of which any member
950226633Sdim      // is initialized, all members must be initialized.
951226633Sdim      if (!RD->isUnion() || Inits.count(*I))
952226633Sdim        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
953226633Sdim  }
954226633Sdim}
955226633Sdim
956251662Sdim/// Check the provided statement is allowed in a constexpr function
957251662Sdim/// definition.
958251662Sdimstatic bool
959251662SdimCheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
960263508Sdim                           SmallVectorImpl<SourceLocation> &ReturnStmts,
961251662Sdim                           SourceLocation &Cxx1yLoc) {
962251662Sdim  // - its function-body shall be [...] a compound-statement that contains only
963251662Sdim  switch (S->getStmtClass()) {
964251662Sdim  case Stmt::NullStmtClass:
965251662Sdim    //   - null statements,
966251662Sdim    return true;
967251662Sdim
968251662Sdim  case Stmt::DeclStmtClass:
969251662Sdim    //   - static_assert-declarations
970251662Sdim    //   - using-declarations,
971251662Sdim    //   - using-directives,
972251662Sdim    //   - typedef declarations and alias-declarations that do not define
973251662Sdim    //     classes or enumerations,
974251662Sdim    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975251662Sdim      return false;
976251662Sdim    return true;
977251662Sdim
978251662Sdim  case Stmt::ReturnStmtClass:
979251662Sdim    //   - and exactly one return statement;
980251662Sdim    if (isa<CXXConstructorDecl>(Dcl)) {
981251662Sdim      // C++1y allows return statements in constexpr constructors.
982251662Sdim      if (!Cxx1yLoc.isValid())
983251662Sdim        Cxx1yLoc = S->getLocStart();
984251662Sdim      return true;
985251662Sdim    }
986251662Sdim
987251662Sdim    ReturnStmts.push_back(S->getLocStart());
988251662Sdim    return true;
989251662Sdim
990251662Sdim  case Stmt::CompoundStmtClass: {
991251662Sdim    // C++1y allows compound-statements.
992251662Sdim    if (!Cxx1yLoc.isValid())
993251662Sdim      Cxx1yLoc = S->getLocStart();
994251662Sdim
995251662Sdim    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996251662Sdim    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997251662Sdim           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998251662Sdim      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999251662Sdim                                      Cxx1yLoc))
1000251662Sdim        return false;
1001251662Sdim    }
1002251662Sdim    return true;
1003251662Sdim  }
1004251662Sdim
1005251662Sdim  case Stmt::AttributedStmtClass:
1006251662Sdim    if (!Cxx1yLoc.isValid())
1007251662Sdim      Cxx1yLoc = S->getLocStart();
1008251662Sdim    return true;
1009251662Sdim
1010251662Sdim  case Stmt::IfStmtClass: {
1011251662Sdim    // C++1y allows if-statements.
1012251662Sdim    if (!Cxx1yLoc.isValid())
1013251662Sdim      Cxx1yLoc = S->getLocStart();
1014251662Sdim
1015251662Sdim    IfStmt *If = cast<IfStmt>(S);
1016251662Sdim    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017251662Sdim                                    Cxx1yLoc))
1018251662Sdim      return false;
1019251662Sdim    if (If->getElse() &&
1020251662Sdim        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021251662Sdim                                    Cxx1yLoc))
1022251662Sdim      return false;
1023251662Sdim    return true;
1024251662Sdim  }
1025251662Sdim
1026251662Sdim  case Stmt::WhileStmtClass:
1027251662Sdim  case Stmt::DoStmtClass:
1028251662Sdim  case Stmt::ForStmtClass:
1029251662Sdim  case Stmt::CXXForRangeStmtClass:
1030251662Sdim  case Stmt::ContinueStmtClass:
1031251662Sdim    // C++1y allows all of these. We don't allow them as extensions in C++11,
1032251662Sdim    // because they don't make sense without variable mutation.
1033251662Sdim    if (!SemaRef.getLangOpts().CPlusPlus1y)
1034251662Sdim      break;
1035251662Sdim    if (!Cxx1yLoc.isValid())
1036251662Sdim      Cxx1yLoc = S->getLocStart();
1037251662Sdim    for (Stmt::child_range Children = S->children(); Children; ++Children)
1038251662Sdim      if (*Children &&
1039251662Sdim          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040251662Sdim                                      Cxx1yLoc))
1041251662Sdim        return false;
1042251662Sdim    return true;
1043251662Sdim
1044251662Sdim  case Stmt::SwitchStmtClass:
1045251662Sdim  case Stmt::CaseStmtClass:
1046251662Sdim  case Stmt::DefaultStmtClass:
1047251662Sdim  case Stmt::BreakStmtClass:
1048251662Sdim    // C++1y allows switch-statements, and since they don't need variable
1049251662Sdim    // mutation, we can reasonably allow them in C++11 as an extension.
1050251662Sdim    if (!Cxx1yLoc.isValid())
1051251662Sdim      Cxx1yLoc = S->getLocStart();
1052251662Sdim    for (Stmt::child_range Children = S->children(); Children; ++Children)
1053251662Sdim      if (*Children &&
1054251662Sdim          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055251662Sdim                                      Cxx1yLoc))
1056251662Sdim        return false;
1057251662Sdim    return true;
1058251662Sdim
1059251662Sdim  default:
1060251662Sdim    if (!isa<Expr>(S))
1061251662Sdim      break;
1062251662Sdim
1063251662Sdim    // C++1y allows expression-statements.
1064251662Sdim    if (!Cxx1yLoc.isValid())
1065251662Sdim      Cxx1yLoc = S->getLocStart();
1066251662Sdim    return true;
1067251662Sdim  }
1068251662Sdim
1069251662Sdim  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070251662Sdim    << isa<CXXConstructorDecl>(Dcl);
1071251662Sdim  return false;
1072251662Sdim}
1073251662Sdim
1074226633Sdim/// Check the body for the given constexpr function declaration only contains
1075226633Sdim/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076226633Sdim///
1077226633Sdim/// \return true if the body is OK, false if we have diagnosed a problem.
1078226633Sdimbool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1079226633Sdim  if (isa<CXXTryStmt>(Body)) {
1080234353Sdim    // C++11 [dcl.constexpr]p3:
1081226633Sdim    //  The definition of a constexpr function shall satisfy the following
1082226633Sdim    //  constraints: [...]
1083226633Sdim    // - its function-body shall be = delete, = default, or a
1084226633Sdim    //   compound-statement
1085226633Sdim    //
1086234353Sdim    // C++11 [dcl.constexpr]p4:
1087226633Sdim    //  In the definition of a constexpr constructor, [...]
1088226633Sdim    // - its function-body shall not be a function-try-block;
1089226633Sdim    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090226633Sdim      << isa<CXXConstructorDecl>(Dcl);
1091226633Sdim    return false;
1092226633Sdim  }
1093226633Sdim
1094251662Sdim  SmallVector<SourceLocation, 4> ReturnStmts;
1095251662Sdim
1096226633Sdim  // - its function-body shall be [...] a compound-statement that contains only
1097251662Sdim  //   [... list of cases ...]
1098226633Sdim  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099251662Sdim  SourceLocation Cxx1yLoc;
1100226633Sdim  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101226633Sdim         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1102251662Sdim    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103251662Sdim      return false;
1104251662Sdim  }
1105226633Sdim
1106251662Sdim  if (Cxx1yLoc.isValid())
1107251662Sdim    Diag(Cxx1yLoc,
1108251662Sdim         getLangOpts().CPlusPlus1y
1109251662Sdim           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110251662Sdim           : diag::ext_constexpr_body_invalid_stmt)
1111226633Sdim      << isa<CXXConstructorDecl>(Dcl);
1112226633Sdim
1113226633Sdim  if (const CXXConstructorDecl *Constructor
1114226633Sdim        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115226633Sdim    const CXXRecordDecl *RD = Constructor->getParent();
1116234353Sdim    // DR1359:
1117234353Sdim    // - every non-variant non-static data member and base class sub-object
1118234353Sdim    //   shall be initialized;
1119234353Sdim    // - if the class is a non-empty union, or for each non-empty anonymous
1120234353Sdim    //   union member of a non-union class, exactly one non-static data member
1121234353Sdim    //   shall be initialized;
1122226633Sdim    if (RD->isUnion()) {
1123234353Sdim      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1124226633Sdim        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125226633Sdim        return false;
1126226633Sdim      }
1127226633Sdim    } else if (!Constructor->isDependentContext() &&
1128226633Sdim               !Constructor->isDelegatingConstructor()) {
1129226633Sdim      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130226633Sdim
1131226633Sdim      // Skip detailed checking if we have enough initializers, and we would
1132226633Sdim      // allow at most one initializer per member.
1133226633Sdim      bool AnyAnonStructUnionMembers = false;
1134226633Sdim      unsigned Fields = 0;
1135226633Sdim      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136226633Sdim           E = RD->field_end(); I != E; ++I, ++Fields) {
1137239462Sdim        if (I->isAnonymousStructOrUnion()) {
1138226633Sdim          AnyAnonStructUnionMembers = true;
1139226633Sdim          break;
1140226633Sdim        }
1141226633Sdim      }
1142226633Sdim      if (AnyAnonStructUnionMembers ||
1143226633Sdim          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144226633Sdim        // Check initialization of non-static data members. Base classes are
1145226633Sdim        // always initialized so do not need to be checked. Dependent bases
1146226633Sdim        // might not have initializers in the member initializer list.
1147226633Sdim        llvm::SmallSet<Decl*, 16> Inits;
1148226633Sdim        for (CXXConstructorDecl::init_const_iterator
1149226633Sdim               I = Constructor->init_begin(), E = Constructor->init_end();
1150226633Sdim             I != E; ++I) {
1151226633Sdim          if (FieldDecl *FD = (*I)->getMember())
1152226633Sdim            Inits.insert(FD);
1153226633Sdim          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154226633Sdim            Inits.insert(ID->chain_begin(), ID->chain_end());
1155226633Sdim        }
1156226633Sdim
1157226633Sdim        bool Diagnosed = false;
1158226633Sdim        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159226633Sdim             E = RD->field_end(); I != E; ++I)
1160226633Sdim          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1161226633Sdim        if (Diagnosed)
1162226633Sdim          return false;
1163226633Sdim      }
1164226633Sdim    }
1165226633Sdim  } else {
1166226633Sdim    if (ReturnStmts.empty()) {
1167251662Sdim      // C++1y doesn't require constexpr functions to contain a 'return'
1168251662Sdim      // statement. We still do, unless the return type is void, because
1169251662Sdim      // otherwise if there's no return statement, the function cannot
1170251662Sdim      // be used in a core constant expression.
1171251662Sdim      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1172251662Sdim      Diag(Dcl->getLocation(),
1173251662Sdim           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174251662Sdim              : diag::err_constexpr_body_no_return);
1175251662Sdim      return OK;
1176226633Sdim    }
1177226633Sdim    if (ReturnStmts.size() > 1) {
1178251662Sdim      Diag(ReturnStmts.back(),
1179251662Sdim           getLangOpts().CPlusPlus1y
1180251662Sdim             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181251662Sdim             : diag::ext_constexpr_body_multiple_return);
1182226633Sdim      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183226633Sdim        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1184226633Sdim    }
1185226633Sdim  }
1186226633Sdim
1187234353Sdim  // C++11 [dcl.constexpr]p5:
1188234353Sdim  //   if no function argument values exist such that the function invocation
1189234353Sdim  //   substitution would produce a constant expression, the program is
1190234353Sdim  //   ill-formed; no diagnostic required.
1191234353Sdim  // C++11 [dcl.constexpr]p3:
1192234353Sdim  //   - every constructor call and implicit conversion used in initializing the
1193234353Sdim  //     return value shall be one of those allowed in a constant expression.
1194234353Sdim  // C++11 [dcl.constexpr]p4:
1195234353Sdim  //   - every constructor involved in initializing non-static data members and
1196234353Sdim  //     base class sub-objects shall be a constexpr constructor.
1197249423Sdim  SmallVector<PartialDiagnosticAt, 8> Diags;
1198234353Sdim  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1199249423Sdim    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1200234353Sdim      << isa<CXXConstructorDecl>(Dcl);
1201234353Sdim    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202234353Sdim      Diag(Diags[I].first, Diags[I].second);
1203249423Sdim    // Don't return false here: we allow this for compatibility in
1204249423Sdim    // system headers.
1205234353Sdim  }
1206234353Sdim
1207226633Sdim  return true;
1208226633Sdim}
1209226633Sdim
1210193326Sed/// isCurrentClassName - Determine whether the identifier II is the
1211193326Sed/// name of the class type currently being defined. In the case of
1212193326Sed/// nested classes, this will only return true if II is the name of
1213193326Sed/// the innermost class.
1214193326Sedbool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215193326Sed                              const CXXScopeSpec *SS) {
1216234353Sdim  assert(getLangOpts().CPlusPlus && "No class names in C!");
1217202379Srdivacky
1218193326Sed  CXXRecordDecl *CurDecl;
1219193326Sed  if (SS && SS->isSet() && !SS->isInvalid()) {
1220198092Srdivacky    DeclContext *DC = computeDeclContext(*SS, true);
1221193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222193326Sed  } else
1223193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224193326Sed
1225203955Srdivacky  if (CurDecl && CurDecl->getIdentifier())
1226193326Sed    return &II == CurDecl->getIdentifier();
1227263508Sdim  return false;
1228263508Sdim}
1229263508Sdim
1230263508Sdim/// \brief Determine whether the identifier II is a typo for the name of
1231263508Sdim/// the class type currently being defined. If so, update it to the identifier
1232263508Sdim/// that should have been used.
1233263508Sdimbool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234263508Sdim  assert(getLangOpts().CPlusPlus && "No class names in C!");
1235263508Sdim
1236263508Sdim  if (!getLangOpts().SpellChecking)
1237193326Sed    return false;
1238263508Sdim
1239263508Sdim  CXXRecordDecl *CurDecl;
1240263508Sdim  if (SS && SS->isSet() && !SS->isInvalid()) {
1241263508Sdim    DeclContext *DC = computeDeclContext(*SS, true);
1242263508Sdim    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243263508Sdim  } else
1244263508Sdim    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245263508Sdim
1246263508Sdim  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247263508Sdim      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248263508Sdim          < II->getLength()) {
1249263508Sdim    II = CurDecl->getIdentifier();
1250263508Sdim    return true;
1251263508Sdim  }
1252263508Sdim
1253263508Sdim  return false;
1254193326Sed}
1255193326Sed
1256243830Sdim/// \brief Determine whether the given class is a base class of the given
1257243830Sdim/// class, including looking at dependent bases.
1258243830Sdimstatic bool findCircularInheritance(const CXXRecordDecl *Class,
1259243830Sdim                                    const CXXRecordDecl *Current) {
1260243830Sdim  SmallVector<const CXXRecordDecl*, 8> Queue;
1261243830Sdim
1262243830Sdim  Class = Class->getCanonicalDecl();
1263243830Sdim  while (true) {
1264243830Sdim    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265243830Sdim                                                  E = Current->bases_end();
1266243830Sdim         I != E; ++I) {
1267243830Sdim      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268243830Sdim      if (!Base)
1269243830Sdim        continue;
1270243830Sdim
1271243830Sdim      Base = Base->getDefinition();
1272243830Sdim      if (!Base)
1273243830Sdim        continue;
1274243830Sdim
1275243830Sdim      if (Base->getCanonicalDecl() == Class)
1276243830Sdim        return true;
1277243830Sdim
1278243830Sdim      Queue.push_back(Base);
1279243830Sdim    }
1280243830Sdim
1281243830Sdim    if (Queue.empty())
1282243830Sdim      return false;
1283243830Sdim
1284263508Sdim    Current = Queue.pop_back_val();
1285243830Sdim  }
1286243830Sdim
1287243830Sdim  return false;
1288243830Sdim}
1289243830Sdim
1290198092Srdivacky/// \brief Check the validity of a C++ base class specifier.
1291193326Sed///
1292193326Sed/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293193326Sed/// and returns NULL otherwise.
1294193326SedCXXBaseSpecifier *
1295193326SedSema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296193326Sed                         SourceRange SpecifierRange,
1297193326Sed                         bool Virtual, AccessSpecifier Access,
1298218893Sdim                         TypeSourceInfo *TInfo,
1299218893Sdim                         SourceLocation EllipsisLoc) {
1300212904Sdim  QualType BaseType = TInfo->getType();
1301212904Sdim
1302193326Sed  // C++ [class.union]p1:
1303193326Sed  //   A union shall not have base classes.
1304193326Sed  if (Class->isUnion()) {
1305193326Sed    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306193326Sed      << SpecifierRange;
1307193326Sed    return 0;
1308193326Sed  }
1309193326Sed
1310218893Sdim  if (EllipsisLoc.isValid() &&
1311218893Sdim      !TInfo->getType()->containsUnexpandedParameterPack()) {
1312218893Sdim    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313218893Sdim      << TInfo->getTypeLoc().getSourceRange();
1314218893Sdim    EllipsisLoc = SourceLocation();
1315218893Sdim  }
1316243830Sdim
1317243830Sdim  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318243830Sdim
1319243830Sdim  if (BaseType->isDependentType()) {
1320243830Sdim    // Make sure that we don't have circular inheritance among our dependent
1321243830Sdim    // bases. For non-dependent bases, the check for completeness below handles
1322243830Sdim    // this.
1323243830Sdim    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324243830Sdim      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325243830Sdim          ((BaseDecl = BaseDecl->getDefinition()) &&
1326243830Sdim           findCircularInheritance(Class, BaseDecl))) {
1327243830Sdim        Diag(BaseLoc, diag::err_circular_inheritance)
1328243830Sdim          << BaseType << Context.getTypeDeclType(Class);
1329243830Sdim
1330243830Sdim        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331243830Sdim          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332243830Sdim            << BaseType;
1333243830Sdim
1334243830Sdim        return 0;
1335243830Sdim      }
1336243830Sdim    }
1337243830Sdim
1338198092Srdivacky    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1339212904Sdim                                          Class->getTagKind() == TTK_Class,
1340218893Sdim                                          Access, TInfo, EllipsisLoc);
1341243830Sdim  }
1342193326Sed
1343193326Sed  // Base specifiers must be record types.
1344193326Sed  if (!BaseType->isRecordType()) {
1345193326Sed    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346193326Sed    return 0;
1347193326Sed  }
1348193326Sed
1349193326Sed  // C++ [class.union]p1:
1350193326Sed  //   A union shall not be used as a base class.
1351193326Sed  if (BaseType->isUnionType()) {
1352193326Sed    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353193326Sed    return 0;
1354193326Sed  }
1355193326Sed
1356193326Sed  // C++ [class.derived]p2:
1357193326Sed  //   The class-name in a base-specifier shall not be an incompletely
1358193326Sed  //   defined class.
1359198092Srdivacky  if (RequireCompleteType(BaseLoc, BaseType,
1360239462Sdim                          diag::err_incomplete_base_class, SpecifierRange)) {
1361212904Sdim    Class->setInvalidDecl();
1362193326Sed    return 0;
1363212904Sdim  }
1364193326Sed
1365198092Srdivacky  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1366198092Srdivacky  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1367193326Sed  assert(BaseDecl && "Record type has no declaration");
1368203955Srdivacky  BaseDecl = BaseDecl->getDefinition();
1369193326Sed  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1370263508Sdim  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1371198092Srdivacky  assert(CXXBaseDecl && "Base type is not a C++ type");
1372200583Srdivacky
1373263508Sdim  // A class which contains a flexible array member is not suitable for use as a
1374263508Sdim  // base class:
1375263508Sdim  //   - If the layout determines that a base comes before another base,
1376263508Sdim  //     the flexible array member would index into the subsequent base.
1377263508Sdim  //   - If the layout determines that base comes before the derived class,
1378263508Sdim  //     the flexible array member would index into the derived class.
1379263508Sdim  if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380263508Sdim    Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381263508Sdim      << CXXBaseDecl->getDeclName();
1382263508Sdim    return 0;
1383263508Sdim  }
1384263508Sdim
1385221345Sdim  // C++ [class]p3:
1386263508Sdim  //   If a class is marked final and it appears as a base-type-specifier in
1387221345Sdim  //   base-clause, the program is ill-formed.
1388263508Sdim  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1389263508Sdim    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1390263508Sdim      << CXXBaseDecl->getDeclName()
1391263508Sdim      << FA->isSpelledAsSealed();
1392200583Srdivacky    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393218893Sdim      << CXXBaseDecl->getDeclName();
1394199990Srdivacky    return 0;
1395199990Srdivacky  }
1396193326Sed
1397212904Sdim  if (BaseDecl->isInvalidDecl())
1398212904Sdim    Class->setInvalidDecl();
1399263508Sdim
1400200583Srdivacky  // Create the base specifier.
1401200583Srdivacky  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1402212904Sdim                                        Class->getTagKind() == TTK_Class,
1403218893Sdim                                        Access, TInfo, EllipsisLoc);
1404200583Srdivacky}
1405200583Srdivacky
1406193326Sed/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407193326Sed/// one entry in the base class list of a class specifier, for
1408198092Srdivacky/// example:
1409198092Srdivacky///    class foo : public bar, virtual private baz {
1410193326Sed/// 'public bar' and 'virtual private baz' are each base-specifiers.
1411212904SdimBaseResult
1412212904SdimSema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1413249423Sdim                         ParsedAttributes &Attributes,
1414193326Sed                         bool Virtual, AccessSpecifier Access,
1415218893Sdim                         ParsedType basetype, SourceLocation BaseLoc,
1416218893Sdim                         SourceLocation EllipsisLoc) {
1417194711Sed  if (!classdecl)
1418194711Sed    return true;
1419194711Sed
1420193326Sed  AdjustDeclIfTemplate(classdecl);
1421212904Sdim  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1422204643Srdivacky  if (!Class)
1423204643Srdivacky    return true;
1424204643Srdivacky
1425249423Sdim  // We do not support any C++11 attributes on base-specifiers yet.
1426249423Sdim  // Diagnose any attributes we see.
1427249423Sdim  if (!Attributes.empty()) {
1428249423Sdim    for (AttributeList *Attr = Attributes.getList(); Attr;
1429249423Sdim         Attr = Attr->getNext()) {
1430249423Sdim      if (Attr->isInvalid() ||
1431249423Sdim          Attr->getKind() == AttributeList::IgnoredAttribute)
1432249423Sdim        continue;
1433249423Sdim      Diag(Attr->getLoc(),
1434249423Sdim           Attr->getKind() == AttributeList::UnknownAttribute
1435249423Sdim             ? diag::warn_unknown_attribute_ignored
1436249423Sdim             : diag::err_base_specifier_attribute)
1437249423Sdim        << Attr->getName();
1438249423Sdim    }
1439249423Sdim  }
1440249423Sdim
1441212904Sdim  TypeSourceInfo *TInfo = 0;
1442212904Sdim  GetTypeFromParser(basetype, &TInfo);
1443218893Sdim
1444218893Sdim  if (EllipsisLoc.isInvalid() &&
1445218893Sdim      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1446218893Sdim                                      UPPC_BaseType))
1447218893Sdim    return true;
1448218893Sdim
1449193326Sed  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1450218893Sdim                                                      Virtual, Access, TInfo,
1451218893Sdim                                                      EllipsisLoc))
1452193326Sed    return BaseSpec;
1453239462Sdim  else
1454239462Sdim    Class->setInvalidDecl();
1455198092Srdivacky
1456193326Sed  return true;
1457193326Sed}
1458193326Sed
1459193326Sed/// \brief Performs the actual work of attaching the given base class
1460193326Sed/// specifiers to a C++ class.
1461193326Sedbool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462193326Sed                                unsigned NumBases) {
1463193326Sed if (NumBases == 0)
1464193326Sed    return false;
1465193326Sed
1466193326Sed  // Used to keep track of which base types we have already seen, so
1467193326Sed  // that we can properly diagnose redundant direct base types. Note
1468193326Sed  // that the key is always the unqualified canonical type of the base
1469193326Sed  // class.
1470193326Sed  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471193326Sed
1472193326Sed  // Copy non-redundant base specifiers into permanent storage.
1473193326Sed  unsigned NumGoodBases = 0;
1474193326Sed  bool Invalid = false;
1475193326Sed  for (unsigned idx = 0; idx < NumBases; ++idx) {
1476198092Srdivacky    QualType NewBaseType
1477193326Sed      = Context.getCanonicalType(Bases[idx]->getType());
1478199482Srdivacky    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1479234353Sdim
1480234353Sdim    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481234353Sdim    if (KnownBase) {
1482193326Sed      // C++ [class.mi]p3:
1483193326Sed      //   A class shall not be specified as a direct base class of a
1484193326Sed      //   derived class more than once.
1485234353Sdim      Diag(Bases[idx]->getLocStart(),
1486193326Sed           diag::err_duplicate_base_class)
1487234353Sdim        << KnownBase->getType()
1488193326Sed        << Bases[idx]->getSourceRange();
1489193326Sed
1490193326Sed      // Delete the duplicate base class specifier; we're going to
1491193326Sed      // overwrite its pointer later.
1492198092Srdivacky      Context.Deallocate(Bases[idx]);
1493193326Sed
1494193326Sed      Invalid = true;
1495193326Sed    } else {
1496193326Sed      // Okay, add this new base class.
1497234353Sdim      KnownBase = Bases[idx];
1498193326Sed      Bases[NumGoodBases++] = Bases[idx];
1499243830Sdim      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500243830Sdim        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501243830Sdim        if (Class->isInterface() &&
1502243830Sdim              (!RD->isInterface() ||
1503243830Sdim               KnownBase->getAccessSpecifier() != AS_public)) {
1504243830Sdim          // The Microsoft extension __interface does not permit bases that
1505243830Sdim          // are not themselves public interfaces.
1506243830Sdim          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507243830Sdim            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508243830Sdim            << RD->getSourceRange();
1509243830Sdim          Invalid = true;
1510243830Sdim        }
1511243830Sdim        if (RD->hasAttr<WeakAttr>())
1512243830Sdim          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1513243830Sdim      }
1514193326Sed    }
1515193326Sed  }
1516193326Sed
1517193326Sed  // Attach the remaining base class specifiers to the derived class.
1518203955Srdivacky  Class->setBases(Bases, NumGoodBases);
1519193326Sed
1520193326Sed  // Delete the remaining (good) base class specifiers, since their
1521193326Sed  // data has been copied into the CXXRecordDecl.
1522193326Sed  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1523198092Srdivacky    Context.Deallocate(Bases[idx]);
1524193326Sed
1525193326Sed  return Invalid;
1526193326Sed}
1527193326Sed
1528193326Sed/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529193326Sed/// class, after checking whether there are any duplicate base
1530193326Sed/// classes.
1531226633Sdimvoid Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1532193326Sed                               unsigned NumBases) {
1533193326Sed  if (!ClassDecl || !Bases || !NumBases)
1534193326Sed    return;
1535193326Sed
1536193326Sed  AdjustDeclIfTemplate(ClassDecl);
1537263508Sdim  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1538193326Sed}
1539193326Sed
1540198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is
1541198092Srdivacky/// derived from the type \p Base.
1542198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1543234353Sdim  if (!getLangOpts().CPlusPlus)
1544198092Srdivacky    return false;
1545204962Srdivacky
1546249423Sdim  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1547204962Srdivacky  if (!DerivedRD)
1548198092Srdivacky    return false;
1549198092Srdivacky
1550249423Sdim  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1551204962Srdivacky  if (!BaseRD)
1552198092Srdivacky    return false;
1553249423Sdim
1554249423Sdim  // If either the base or the derived type is invalid, don't try to
1555249423Sdim  // check whether one is derived from the other.
1556249423Sdim  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557249423Sdim    return false;
1558249423Sdim
1559203955Srdivacky  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1560203955Srdivacky  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1561198092Srdivacky}
1562198092Srdivacky
1563198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is
1564198092Srdivacky/// derived from the type \p Base.
1565198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1566234353Sdim  if (!getLangOpts().CPlusPlus)
1567198092Srdivacky    return false;
1568198092Srdivacky
1569249423Sdim  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1570204962Srdivacky  if (!DerivedRD)
1571198092Srdivacky    return false;
1572198092Srdivacky
1573249423Sdim  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1574204962Srdivacky  if (!BaseRD)
1575198092Srdivacky    return false;
1576198092Srdivacky
1577198092Srdivacky  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578198092Srdivacky}
1579198092Srdivacky
1580207619Srdivackyvoid Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1581212904Sdim                              CXXCastPath &BasePathArray) {
1582207619Srdivacky  assert(BasePathArray.empty() && "Base path array must be empty!");
1583207619Srdivacky  assert(Paths.isRecordingPaths() && "Must record paths!");
1584207619Srdivacky
1585207619Srdivacky  const CXXBasePath &Path = Paths.front();
1586207619Srdivacky
1587207619Srdivacky  // We first go backward and check if we have a virtual base.
1588207619Srdivacky  // FIXME: It would be better if CXXBasePath had the base specifier for
1589207619Srdivacky  // the nearest virtual base.
1590207619Srdivacky  unsigned Start = 0;
1591207619Srdivacky  for (unsigned I = Path.size(); I != 0; --I) {
1592207619Srdivacky    if (Path[I - 1].Base->isVirtual()) {
1593207619Srdivacky      Start = I - 1;
1594207619Srdivacky      break;
1595207619Srdivacky    }
1596207619Srdivacky  }
1597207619Srdivacky
1598207619Srdivacky  // Now add all bases.
1599207619Srdivacky  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1600212904Sdim    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1601207619Srdivacky}
1602207619Srdivacky
1603208600Srdivacky/// \brief Determine whether the given base path includes a virtual
1604208600Srdivacky/// base class.
1605212904Sdimbool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606212904Sdim  for (CXXCastPath::const_iterator B = BasePath.begin(),
1607212904Sdim                                BEnd = BasePath.end();
1608208600Srdivacky       B != BEnd; ++B)
1609208600Srdivacky    if ((*B)->isVirtual())
1610208600Srdivacky      return true;
1611208600Srdivacky
1612208600Srdivacky  return false;
1613208600Srdivacky}
1614208600Srdivacky
1615198092Srdivacky/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616198092Srdivacky/// conversion (where Derived and Base are class types) is
1617198092Srdivacky/// well-formed, meaning that the conversion is unambiguous (and
1618198092Srdivacky/// that all of the base classes are accessible). Returns true
1619198092Srdivacky/// and emits a diagnostic if the code is ill-formed, returns false
1620198092Srdivacky/// otherwise. Loc is the location where this routine should point to
1621198092Srdivacky/// if there is an error, and Range is the source range to highlight
1622198092Srdivacky/// if there is an error.
1623198092Srdivackybool
1624198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1625205219Srdivacky                                   unsigned InaccessibleBaseID,
1626198092Srdivacky                                   unsigned AmbigiousBaseConvID,
1627198092Srdivacky                                   SourceLocation Loc, SourceRange Range,
1628207619Srdivacky                                   DeclarationName Name,
1629212904Sdim                                   CXXCastPath *BasePath) {
1630198092Srdivacky  // First, determine whether the path from Derived to Base is
1631198092Srdivacky  // ambiguous. This is slightly more expensive than checking whether
1632198092Srdivacky  // the Derived to Base conversion exists, because here we need to
1633198092Srdivacky  // explore multiple paths to determine if there is an ambiguity.
1634198092Srdivacky  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635198092Srdivacky                     /*DetectVirtual=*/false);
1636198092Srdivacky  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637198092Srdivacky  assert(DerivationOkay &&
1638198092Srdivacky         "Can only be used with a derived-to-base conversion");
1639198092Srdivacky  (void)DerivationOkay;
1640198092Srdivacky
1641198092Srdivacky  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1642207619Srdivacky    if (InaccessibleBaseID) {
1643207619Srdivacky      // Check that the base class can be accessed.
1644207619Srdivacky      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645207619Srdivacky                                   InaccessibleBaseID)) {
1646207619Srdivacky        case AR_inaccessible:
1647207619Srdivacky          return true;
1648207619Srdivacky        case AR_accessible:
1649207619Srdivacky        case AR_dependent:
1650207619Srdivacky        case AR_delayed:
1651207619Srdivacky          break;
1652207619Srdivacky      }
1653203955Srdivacky    }
1654207619Srdivacky
1655207619Srdivacky    // Build a base path if necessary.
1656207619Srdivacky    if (BasePath)
1657207619Srdivacky      BuildBasePathArray(Paths, *BasePath);
1658207619Srdivacky    return false;
1659198092Srdivacky  }
1660198092Srdivacky
1661263508Sdim  if (AmbigiousBaseConvID) {
1662263508Sdim    // We know that the derived-to-base conversion is ambiguous, and
1663263508Sdim    // we're going to produce a diagnostic. Perform the derived-to-base
1664263508Sdim    // search just one more time to compute all of the possible paths so
1665263508Sdim    // that we can print them out. This is more expensive than any of
1666263508Sdim    // the previous derived-to-base checks we've done, but at this point
1667263508Sdim    // performance isn't as much of an issue.
1668263508Sdim    Paths.clear();
1669263508Sdim    Paths.setRecordingPaths(true);
1670263508Sdim    bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671263508Sdim    assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672263508Sdim    (void)StillOkay;
1673263508Sdim
1674263508Sdim    // Build up a textual representation of the ambiguous paths, e.g.,
1675263508Sdim    // D -> B -> A, that will be used to illustrate the ambiguous
1676263508Sdim    // conversions in the diagnostic. We only print one of the paths
1677263508Sdim    // to each base class subobject.
1678263508Sdim    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679263508Sdim
1680263508Sdim    Diag(Loc, AmbigiousBaseConvID)
1681263508Sdim    << Derived << Base << PathDisplayStr << Range << Name;
1682263508Sdim  }
1683198092Srdivacky  return true;
1684198092Srdivacky}
1685198092Srdivacky
1686198092Srdivackybool
1687198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1688199482Srdivacky                                   SourceLocation Loc, SourceRange Range,
1689212904Sdim                                   CXXCastPath *BasePath,
1690199482Srdivacky                                   bool IgnoreAccess) {
1691198092Srdivacky  return CheckDerivedToBaseConversion(Derived, Base,
1692205219Srdivacky                                      IgnoreAccess ? 0
1693205219Srdivacky                                       : diag::err_upcast_to_inaccessible_base,
1694198092Srdivacky                                      diag::err_ambiguous_derived_to_base_conv,
1695207619Srdivacky                                      Loc, Range, DeclarationName(),
1696207619Srdivacky                                      BasePath);
1697198092Srdivacky}
1698198092Srdivacky
1699198092Srdivacky
1700198092Srdivacky/// @brief Builds a string representing ambiguous paths from a
1701198092Srdivacky/// specific derived class to different subobjects of the same base
1702198092Srdivacky/// class.
1703198092Srdivacky///
1704198092Srdivacky/// This function builds a string that can be used in error messages
1705198092Srdivacky/// to show the different paths that one can take through the
1706198092Srdivacky/// inheritance hierarchy to go from the derived class to different
1707198092Srdivacky/// subobjects of a base class. The result looks something like this:
1708198092Srdivacky/// @code
1709198092Srdivacky/// struct D -> struct B -> struct A
1710198092Srdivacky/// struct D -> struct C -> struct A
1711198092Srdivacky/// @endcode
1712198092Srdivackystd::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713198092Srdivacky  std::string PathDisplayStr;
1714198092Srdivacky  std::set<unsigned> DisplayedPaths;
1715198092Srdivacky  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716198092Srdivacky       Path != Paths.end(); ++Path) {
1717198092Srdivacky    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718198092Srdivacky      // We haven't displayed a path to this particular base
1719198092Srdivacky      // class subobject yet.
1720198092Srdivacky      PathDisplayStr += "\n    ";
1721198092Srdivacky      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722198092Srdivacky      for (CXXBasePath::const_iterator Element = Path->begin();
1723198092Srdivacky           Element != Path->end(); ++Element)
1724198092Srdivacky        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725198092Srdivacky    }
1726198092Srdivacky  }
1727198092Srdivacky
1728198092Srdivacky  return PathDisplayStr;
1729198092Srdivacky}
1730198092Srdivacky
1731193326Sed//===----------------------------------------------------------------------===//
1732193326Sed// C++ class member Handling
1733193326Sed//===----------------------------------------------------------------------===//
1734193326Sed
1735210299Sed/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1736226633Sdimbool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737226633Sdim                                SourceLocation ASLoc,
1738226633Sdim                                SourceLocation ColonLoc,
1739226633Sdim                                AttributeList *Attrs) {
1740210299Sed  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1741212904Sdim  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1742210299Sed                                                  ASLoc, ColonLoc);
1743210299Sed  CurContext->addHiddenDecl(ASDecl);
1744226633Sdim  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1745210299Sed}
1746210299Sed
1747239462Sdim/// CheckOverrideControl - Check C++11 override control semantics.
1748263508Sdimvoid Sema::CheckOverrideControl(NamedDecl *D) {
1749243830Sdim  if (D->isInvalidDecl())
1750243830Sdim    return;
1751243830Sdim
1752263508Sdim  // We only care about "override" and "final" declarations.
1753263508Sdim  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754263508Sdim    return;
1755239462Sdim
1756263508Sdim  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1757239462Sdim
1758263508Sdim  // We can't check dependent instance methods.
1759263508Sdim  if (MD && MD->isInstance() &&
1760263508Sdim      (MD->getParent()->hasAnyDependentBases() ||
1761263508Sdim       MD->getType()->isDependentType()))
1762263508Sdim    return;
1763263508Sdim
1764263508Sdim  if (MD && !MD->isVirtual()) {
1765263508Sdim    // If we have a non-virtual method, check if if hides a virtual method.
1766263508Sdim    // (In that case, it's most likely the method has the wrong type.)
1767263508Sdim    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768263508Sdim    FindHiddenVirtualMethods(MD, OverloadedMethods);
1769263508Sdim
1770263508Sdim    if (!OverloadedMethods.empty()) {
1771239462Sdim      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772239462Sdim        Diag(OA->getLocation(),
1773263508Sdim             diag::override_keyword_hides_virtual_member_function)
1774263508Sdim          << "override" << (OverloadedMethods.size() > 1);
1775263508Sdim      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1776239462Sdim        Diag(FA->getLocation(),
1777263508Sdim             diag::override_keyword_hides_virtual_member_function)
1778263508Sdim          << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779263508Sdim          << (OverloadedMethods.size() > 1);
1780239462Sdim      }
1781263508Sdim      NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782263508Sdim      MD->setInvalidDecl();
1783263508Sdim      return;
1784239462Sdim    }
1785263508Sdim    // Fall through into the general case diagnostic.
1786263508Sdim    // FIXME: We might want to attempt typo correction here.
1787239462Sdim  }
1788218893Sdim
1789263508Sdim  if (!MD || !MD->isVirtual()) {
1790263508Sdim    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791263508Sdim      Diag(OA->getLocation(),
1792263508Sdim           diag::override_keyword_only_allowed_on_virtual_member_functions)
1793263508Sdim        << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794263508Sdim      D->dropAttr<OverrideAttr>();
1795263508Sdim    }
1796263508Sdim    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797263508Sdim      Diag(FA->getLocation(),
1798263508Sdim           diag::override_keyword_only_allowed_on_virtual_member_functions)
1799263508Sdim        << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800263508Sdim        << FixItHint::CreateRemoval(FA->getLocation());
1801263508Sdim      D->dropAttr<FinalAttr>();
1802263508Sdim    }
1803218893Sdim    return;
1804263508Sdim  }
1805218893Sdim
1806239462Sdim  // C++11 [class.virtual]p5:
1807239462Sdim  //   If a virtual function is marked with the virt-specifier override and
1808239462Sdim  //   does not override a member function of a base class, the program is
1809239462Sdim  //   ill-formed.
1810239462Sdim  bool HasOverriddenMethods =
1811218893Sdim    MD->begin_overridden_methods() != MD->end_overridden_methods();
1812239462Sdim  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813239462Sdim    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814218893Sdim      << MD->getDeclName();
1815218893Sdim}
1816218893Sdim
1817239462Sdim/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1818218893Sdim/// function overrides a virtual member function marked 'final', according to
1819239462Sdim/// C++11 [class.virtual]p4.
1820218893Sdimbool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821218893Sdim                                                  const CXXMethodDecl *Old) {
1822263508Sdim  FinalAttr *FA = Old->getAttr<FinalAttr>();
1823263508Sdim  if (!FA)
1824218893Sdim    return false;
1825218893Sdim
1826218893Sdim  Diag(New->getLocation(), diag::err_final_function_overridden)
1827263508Sdim    << New->getDeclName()
1828263508Sdim    << FA->isSpelledAsSealed();
1829218893Sdim  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830218893Sdim  return true;
1831218893Sdim}
1832218893Sdim
1833239462Sdimstatic bool InitializationHasSideEffects(const FieldDecl &FD) {
1834239462Sdim  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835239462Sdim  // FIXME: Destruction of ObjC lifetime types has side-effects.
1836239462Sdim  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837239462Sdim    return !RD->isCompleteDefinition() ||
1838239462Sdim           !RD->hasTrivialDefaultConstructor() ||
1839239462Sdim           !RD->hasTrivialDestructor();
1840239462Sdim  return false;
1841239462Sdim}
1842239462Sdim
1843251662Sdimstatic AttributeList *getMSPropertyAttr(AttributeList *list) {
1844251662Sdim  for (AttributeList* it = list; it != 0; it = it->getNext())
1845251662Sdim    if (it->isDeclspecPropertyAttribute())
1846251662Sdim      return it;
1847251662Sdim  return 0;
1848251662Sdim}
1849251662Sdim
1850193326Sed/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851193326Sed/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1852223017Sdim/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1853239462Sdim/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854239462Sdim/// present (but parsing it has been deferred).
1855249423SdimNamedDecl *
1856193326SedSema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1857198092Srdivacky                               MultiTemplateParamsArg TemplateParameterLists,
1858226633Sdim                               Expr *BW, const VirtSpecifiers &VS,
1859239462Sdim                               InClassInitStyle InitStyle) {
1860193326Sed  const DeclSpec &DS = D.getDeclSpec();
1861212904Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862212904Sdim  DeclarationName Name = NameInfo.getName();
1863212904Sdim  SourceLocation Loc = NameInfo.getLoc();
1864218893Sdim
1865218893Sdim  // For anonymous bitfields, the location should point to the type.
1866218893Sdim  if (Loc.isInvalid())
1867234353Sdim    Loc = D.getLocStart();
1868218893Sdim
1869193326Sed  Expr *BitWidth = static_cast<Expr*>(BW);
1870193326Sed
1871210299Sed  assert(isa<CXXRecordDecl>(CurContext));
1872198092Srdivacky  assert(!DS.isFriendSpecified());
1873198092Srdivacky
1874224145Sdim  bool isFunc = D.isDeclarationOfFunction();
1875210299Sed
1876243830Sdim  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877243830Sdim    // The Microsoft extension __interface only permits public member functions
1878243830Sdim    // and prohibits constructors, destructors, operators, non-public member
1879243830Sdim    // functions, static methods and data members.
1880243830Sdim    unsigned InvalidDecl;
1881243830Sdim    bool ShowDeclName = true;
1882243830Sdim    if (!isFunc)
1883243830Sdim      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884243830Sdim    else if (AS != AS_public)
1885243830Sdim      InvalidDecl = 2;
1886243830Sdim    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887243830Sdim      InvalidDecl = 3;
1888243830Sdim    else switch (Name.getNameKind()) {
1889243830Sdim      case DeclarationName::CXXConstructorName:
1890243830Sdim        InvalidDecl = 4;
1891243830Sdim        ShowDeclName = false;
1892243830Sdim        break;
1893243830Sdim
1894243830Sdim      case DeclarationName::CXXDestructorName:
1895243830Sdim        InvalidDecl = 5;
1896243830Sdim        ShowDeclName = false;
1897243830Sdim        break;
1898243830Sdim
1899243830Sdim      case DeclarationName::CXXOperatorName:
1900243830Sdim      case DeclarationName::CXXConversionFunctionName:
1901243830Sdim        InvalidDecl = 6;
1902243830Sdim        break;
1903243830Sdim
1904243830Sdim      default:
1905243830Sdim        InvalidDecl = 0;
1906243830Sdim        break;
1907243830Sdim    }
1908243830Sdim
1909243830Sdim    if (InvalidDecl) {
1910243830Sdim      if (ShowDeclName)
1911243830Sdim        Diag(Loc, diag::err_invalid_member_in_interface)
1912243830Sdim          << (InvalidDecl-1) << Name;
1913243830Sdim      else
1914243830Sdim        Diag(Loc, diag::err_invalid_member_in_interface)
1915243830Sdim          << (InvalidDecl-1) << "";
1916243830Sdim      return 0;
1917243830Sdim    }
1918243830Sdim  }
1919243830Sdim
1920193326Sed  // C++ 9.2p6: A member shall not be declared to have automatic storage
1921193326Sed  // duration (auto, register) or with the extern storage-class-specifier.
1922193326Sed  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923193326Sed  // data members and cannot be applied to names declared const or static,
1924193326Sed  // and cannot be applied to reference members.
1925193326Sed  switch (DS.getStorageClassSpec()) {
1926251662Sdim  case DeclSpec::SCS_unspecified:
1927251662Sdim  case DeclSpec::SCS_typedef:
1928251662Sdim  case DeclSpec::SCS_static:
1929251662Sdim    break;
1930251662Sdim  case DeclSpec::SCS_mutable:
1931251662Sdim    if (isFunc) {
1932251662Sdim      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1933198092Srdivacky
1934251662Sdim      // FIXME: It would be nicer if the keyword was ignored only for this
1935251662Sdim      // declarator. Otherwise we could get follow-up errors.
1936193326Sed      D.getMutableDeclSpec().ClearStorageClassSpecs();
1937251662Sdim    }
1938251662Sdim    break;
1939251662Sdim  default:
1940251662Sdim    Diag(DS.getStorageClassSpecLoc(),
1941251662Sdim         diag::err_storageclass_invalid_for_member);
1942251662Sdim    D.getMutableDeclSpec().ClearStorageClassSpecs();
1943251662Sdim    break;
1944193326Sed  }
1945193326Sed
1946193326Sed  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947193326Sed                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1948193326Sed                      !isFunc);
1949193326Sed
1950249423Sdim  if (DS.isConstexprSpecified() && isInstField) {
1951249423Sdim    SemaDiagnosticBuilder B =
1952249423Sdim        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953249423Sdim    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954249423Sdim    if (InitStyle == ICIS_NoInit) {
1955249423Sdim      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956249423Sdim      D.getMutableDeclSpec().ClearConstexprSpec();
1957249423Sdim      const char *PrevSpec;
1958249423Sdim      unsigned DiagID;
1959249423Sdim      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960249423Sdim                                         PrevSpec, DiagID, getLangOpts());
1961249423Sdim      (void)Failed;
1962249423Sdim      assert(!Failed && "Making a constexpr member const shouldn't fail");
1963249423Sdim    } else {
1964249423Sdim      B << 1;
1965249423Sdim      const char *PrevSpec;
1966249423Sdim      unsigned DiagID;
1967249423Sdim      if (D.getMutableDeclSpec().SetStorageClassSpec(
1968249423Sdim          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1969249423Sdim        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1970249423Sdim               "This is the only DeclSpec that should fail to be applied");
1971249423Sdim        B << 1;
1972249423Sdim      } else {
1973249423Sdim        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1974249423Sdim        isInstField = false;
1975249423Sdim      }
1976249423Sdim    }
1977249423Sdim  }
1978249423Sdim
1979249423Sdim  NamedDecl *Member;
1980193326Sed  if (isInstField) {
1981218893Sdim    CXXScopeSpec &SS = D.getCXXScopeSpec();
1982226633Sdim
1983226633Sdim    // Data members must have identifiers for names.
1984239462Sdim    if (!Name.isIdentifier()) {
1985226633Sdim      Diag(Loc, diag::err_bad_variable_name)
1986226633Sdim        << Name;
1987226633Sdim      return 0;
1988226633Sdim    }
1989239462Sdim
1990226633Sdim    IdentifierInfo *II = Name.getAsIdentifierInfo();
1991226633Sdim
1992226633Sdim    // Member field could not be with "template" keyword.
1993226633Sdim    // So TemplateParameterLists should be empty in this case.
1994226633Sdim    if (TemplateParameterLists.size()) {
1995243830Sdim      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1996226633Sdim      if (TemplateParams->size()) {
1997226633Sdim        // There is no such thing as a member field template.
1998226633Sdim        Diag(D.getIdentifierLoc(), diag::err_template_member)
1999226633Sdim            << II
2000226633Sdim            << SourceRange(TemplateParams->getTemplateLoc(),
2001226633Sdim                TemplateParams->getRAngleLoc());
2002226633Sdim      } else {
2003226633Sdim        // There is an extraneous 'template<>' for this member.
2004226633Sdim        Diag(TemplateParams->getTemplateLoc(),
2005226633Sdim            diag::err_template_member_noparams)
2006226633Sdim            << II
2007226633Sdim            << SourceRange(TemplateParams->getTemplateLoc(),
2008226633Sdim                TemplateParams->getRAngleLoc());
2009226633Sdim      }
2010226633Sdim      return 0;
2011226633Sdim    }
2012226633Sdim
2013218893Sdim    if (SS.isSet() && !SS.isInvalid()) {
2014218893Sdim      // The user provided a superfluous scope specifier inside a class
2015218893Sdim      // definition:
2016218893Sdim      //
2017218893Sdim      // class X {
2018218893Sdim      //   int X::member;
2019218893Sdim      // };
2020234353Sdim      if (DeclContext *DC = computeDeclContext(SS, false))
2021234353Sdim        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2022218893Sdim      else
2023218893Sdim        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2024218893Sdim          << Name << SS.getRange();
2025234353Sdim
2026218893Sdim      SS.clear();
2027218893Sdim    }
2028226633Sdim
2029251662Sdim    AttributeList *MSPropertyAttr =
2030251662Sdim      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2031251662Sdim    if (MSPropertyAttr) {
2032251662Sdim      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2033251662Sdim                                BitWidth, InitStyle, AS, MSPropertyAttr);
2034263508Sdim      if (!Member)
2035263508Sdim        return 0;
2036251662Sdim      isInstField = false;
2037251662Sdim    } else {
2038251662Sdim      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2039251662Sdim                                BitWidth, InitStyle, AS);
2040263508Sdim      assert(Member && "HandleField never returns null");
2041251662Sdim    }
2042193326Sed  } else {
2043249423Sdim    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2044223017Sdim
2045243830Sdim    Member = HandleDeclarator(S, D, TemplateParameterLists);
2046263508Sdim    if (!Member)
2047212904Sdim      return 0;
2048193326Sed
2049193326Sed    // Non-instance-fields can't have a bitfield.
2050193326Sed    if (BitWidth) {
2051193326Sed      if (Member->isInvalidDecl()) {
2052193326Sed        // don't emit another diagnostic.
2053193326Sed      } else if (isa<VarDecl>(Member)) {
2054193326Sed        // C++ 9.6p3: A bit-field shall not be a static member.
2055193326Sed        // "static member 'A' cannot be a bit-field"
2056193326Sed        Diag(Loc, diag::err_static_not_bitfield)
2057193326Sed          << Name << BitWidth->getSourceRange();
2058193326Sed      } else if (isa<TypedefDecl>(Member)) {
2059193326Sed        // "typedef member 'x' cannot be a bit-field"
2060193326Sed        Diag(Loc, diag::err_typedef_not_bitfield)
2061193326Sed          << Name << BitWidth->getSourceRange();
2062193326Sed      } else {
2063193326Sed        // A function typedef ("typedef int f(); f a;").
2064193326Sed        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2065193326Sed        Diag(Loc, diag::err_not_integral_type_bitfield)
2066198092Srdivacky          << Name << cast<ValueDecl>(Member)->getType()
2067193326Sed          << BitWidth->getSourceRange();
2068193326Sed      }
2069198092Srdivacky
2070193326Sed      BitWidth = 0;
2071193326Sed      Member->setInvalidDecl();
2072193326Sed    }
2073193326Sed
2074193326Sed    Member->setAccess(AS);
2075198092Srdivacky
2076263508Sdim    // If we have declared a member function template or static data member
2077263508Sdim    // template, set the access of the templated declaration as well.
2078198092Srdivacky    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2079198092Srdivacky      FunTmpl->getTemplatedDecl()->setAccess(AS);
2080263508Sdim    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2081263508Sdim      VarTmpl->getTemplatedDecl()->setAccess(AS);
2082193326Sed  }
2083193326Sed
2084239462Sdim  if (VS.isOverrideSpecified())
2085239462Sdim    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2086239462Sdim  if (VS.isFinalSpecified())
2087263508Sdim    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2088263508Sdim                                            VS.isFinalSpelledSealed()));
2089218893Sdim
2090221345Sdim  if (VS.getLastLocation().isValid()) {
2091221345Sdim    // Update the end location of a method that has a virt-specifiers.
2092221345Sdim    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2093221345Sdim      MD->setRangeEnd(VS.getLastLocation());
2094221345Sdim  }
2095239462Sdim
2096218893Sdim  CheckOverrideControl(Member);
2097218893Sdim
2098193326Sed  assert((Name || isInstField) && "No identifier for non-field ?");
2099193326Sed
2100239462Sdim  if (isInstField) {
2101239462Sdim    FieldDecl *FD = cast<FieldDecl>(Member);
2102239462Sdim    FieldCollector->Add(FD);
2103239462Sdim
2104239462Sdim    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2105239462Sdim                                 FD->getLocation())
2106239462Sdim          != DiagnosticsEngine::Ignored) {
2107239462Sdim      // Remember all explicit private FieldDecls that have a name, no side
2108239462Sdim      // effects and are not part of a dependent type declaration.
2109239462Sdim      if (!FD->isImplicit() && FD->getDeclName() &&
2110239462Sdim          FD->getAccess() == AS_private &&
2111239462Sdim          !FD->hasAttr<UnusedAttr>() &&
2112239462Sdim          !FD->getParent()->isDependentContext() &&
2113239462Sdim          !InitializationHasSideEffects(*FD))
2114239462Sdim        UnusedPrivateFields.insert(FD);
2115239462Sdim    }
2116239462Sdim  }
2117239462Sdim
2118212904Sdim  return Member;
2119193326Sed}
2120193326Sed
2121243830Sdimnamespace {
2122243830Sdim  class UninitializedFieldVisitor
2123243830Sdim      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2124243830Sdim    Sema &S;
2125263508Sdim    // List of Decls to generate a warning on.  Also remove Decls that become
2126263508Sdim    // initialized.
2127263508Sdim    llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2128263508Sdim    // If non-null, add a note to the warning pointing back to the constructor.
2129263508Sdim    const CXXConstructorDecl *Constructor;
2130243830Sdim  public:
2131243830Sdim    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2132263508Sdim    UninitializedFieldVisitor(Sema &S,
2133263508Sdim                              llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2134263508Sdim                              const CXXConstructorDecl *Constructor)
2135263508Sdim      : Inherited(S.Context), S(S), Decls(Decls),
2136263508Sdim        Constructor(Constructor) { }
2137243830Sdim
2138263508Sdim    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2139263508Sdim      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2140263508Sdim        return;
2141243830Sdim
2142263508Sdim      // FieldME is the inner-most MemberExpr that is not an anonymous struct
2143263508Sdim      // or union.
2144263508Sdim      MemberExpr *FieldME = ME;
2145243830Sdim
2146263508Sdim      Expr *Base = ME;
2147263508Sdim      while (isa<MemberExpr>(Base)) {
2148263508Sdim        ME = cast<MemberExpr>(Base);
2149243830Sdim
2150263508Sdim        if (isa<VarDecl>(ME->getMemberDecl()))
2151249423Sdim          return;
2152249423Sdim
2153263508Sdim        if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2154263508Sdim          if (!FD->isAnonymousStructOrUnion())
2155263508Sdim            FieldME = ME;
2156249423Sdim
2157263508Sdim        Base = ME->getBase();
2158263508Sdim      }
2159249423Sdim
2160263508Sdim      if (!isa<CXXThisExpr>(Base))
2161263508Sdim        return;
2162249423Sdim
2163263508Sdim      ValueDecl* FoundVD = FieldME->getMemberDecl();
2164249423Sdim
2165263508Sdim      if (!Decls.count(FoundVD))
2166263508Sdim        return;
2167243830Sdim
2168263508Sdim      const bool IsReference = FoundVD->getType()->isReferenceType();
2169263508Sdim
2170263508Sdim      // Prevent double warnings on use of unbounded references.
2171263508Sdim      if (IsReference != CheckReferenceOnly)
2172249423Sdim        return;
2173263508Sdim
2174263508Sdim      unsigned diag = IsReference
2175263508Sdim          ? diag::warn_reference_field_is_uninit
2176263508Sdim          : diag::warn_field_is_uninit;
2177263508Sdim      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2178263508Sdim      if (Constructor)
2179263508Sdim        S.Diag(Constructor->getLocation(),
2180263508Sdim               diag::note_uninit_in_this_constructor)
2181263508Sdim          << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2182263508Sdim
2183263508Sdim    }
2184263508Sdim
2185263508Sdim    void HandleValue(Expr *E) {
2186263508Sdim      E = E->IgnoreParens();
2187263508Sdim
2188263508Sdim      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2189263508Sdim        HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2190263508Sdim        return;
2191243830Sdim      }
2192243830Sdim
2193243830Sdim      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2194243830Sdim        HandleValue(CO->getTrueExpr());
2195243830Sdim        HandleValue(CO->getFalseExpr());
2196243830Sdim        return;
2197243830Sdim      }
2198243830Sdim
2199243830Sdim      if (BinaryConditionalOperator *BCO =
2200243830Sdim              dyn_cast<BinaryConditionalOperator>(E)) {
2201243830Sdim        HandleValue(BCO->getCommon());
2202243830Sdim        HandleValue(BCO->getFalseExpr());
2203243830Sdim        return;
2204243830Sdim      }
2205243830Sdim
2206243830Sdim      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2207243830Sdim        switch (BO->getOpcode()) {
2208243830Sdim        default:
2209243830Sdim          return;
2210243830Sdim        case(BO_PtrMemD):
2211243830Sdim        case(BO_PtrMemI):
2212243830Sdim          HandleValue(BO->getLHS());
2213243830Sdim          return;
2214243830Sdim        case(BO_Comma):
2215243830Sdim          HandleValue(BO->getRHS());
2216243830Sdim          return;
2217243830Sdim        }
2218243830Sdim      }
2219243830Sdim    }
2220243830Sdim
2221263508Sdim    void VisitMemberExpr(MemberExpr *ME) {
2222263508Sdim      // All uses of unbounded reference fields will warn.
2223263508Sdim      HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2224263508Sdim
2225263508Sdim      Inherited::VisitMemberExpr(ME);
2226263508Sdim    }
2227263508Sdim
2228243830Sdim    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2229243830Sdim      if (E->getCastKind() == CK_LValueToRValue)
2230243830Sdim        HandleValue(E->getSubExpr());
2231243830Sdim
2232243830Sdim      Inherited::VisitImplicitCastExpr(E);
2233243830Sdim    }
2234243830Sdim
2235263508Sdim    void VisitCXXConstructExpr(CXXConstructExpr *E) {
2236263508Sdim      if (E->getConstructor()->isCopyConstructor())
2237263508Sdim        if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2238263508Sdim          if (ICE->getCastKind() == CK_NoOp)
2239263508Sdim            if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2240263508Sdim              HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2241263508Sdim
2242263508Sdim      Inherited::VisitCXXConstructExpr(E);
2243263508Sdim    }
2244263508Sdim
2245243830Sdim    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2246243830Sdim      Expr *Callee = E->getCallee();
2247243830Sdim      if (isa<MemberExpr>(Callee))
2248243830Sdim        HandleValue(Callee);
2249243830Sdim
2250243830Sdim      Inherited::VisitCXXMemberCallExpr(E);
2251243830Sdim    }
2252263508Sdim
2253263508Sdim    void VisitBinaryOperator(BinaryOperator *E) {
2254263508Sdim      // If a field assignment is detected, remove the field from the
2255263508Sdim      // uninitiailized field set.
2256263508Sdim      if (E->getOpcode() == BO_Assign)
2257263508Sdim        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2258263508Sdim          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2259263508Sdim            if (!FD->getType()->isReferenceType())
2260263508Sdim              Decls.erase(FD);
2261263508Sdim
2262263508Sdim      Inherited::VisitBinaryOperator(E);
2263263508Sdim    }
2264243830Sdim  };
2265263508Sdim  static void CheckInitExprContainsUninitializedFields(
2266263508Sdim      Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2267263508Sdim      const CXXConstructorDecl *Constructor) {
2268263508Sdim    if (Decls.size() == 0)
2269263508Sdim      return;
2270263508Sdim
2271263508Sdim    if (!E)
2272263508Sdim      return;
2273263508Sdim
2274263508Sdim    if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2275263508Sdim      E = Default->getExpr();
2276263508Sdim      if (!E)
2277263508Sdim        return;
2278263508Sdim      // In class initializers will point to the constructor.
2279263508Sdim      UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2280263508Sdim    } else {
2281263508Sdim      UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2282263508Sdim    }
2283243830Sdim  }
2284263508Sdim
2285263508Sdim  // Diagnose value-uses of fields to initialize themselves, e.g.
2286263508Sdim  //   foo(foo)
2287263508Sdim  // where foo is not also a parameter to the constructor.
2288263508Sdim  // Also diagnose across field uninitialized use such as
2289263508Sdim  //   x(y), y(x)
2290263508Sdim  // TODO: implement -Wuninitialized and fold this into that framework.
2291263508Sdim  static void DiagnoseUninitializedFields(
2292263508Sdim      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2293263508Sdim
2294263508Sdim    if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2295263508Sdim                                                    Constructor->getLocation())
2296263508Sdim        == DiagnosticsEngine::Ignored) {
2297263508Sdim      return;
2298263508Sdim    }
2299263508Sdim
2300263508Sdim    if (Constructor->isInvalidDecl())
2301263508Sdim      return;
2302263508Sdim
2303263508Sdim    const CXXRecordDecl *RD = Constructor->getParent();
2304263508Sdim
2305263508Sdim    // Holds fields that are uninitialized.
2306263508Sdim    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2307263508Sdim
2308263508Sdim    // At the beginning, all fields are uninitialized.
2309263508Sdim    for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2310263508Sdim         I != E; ++I) {
2311263508Sdim      if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2312263508Sdim        UninitializedFields.insert(FD);
2313263508Sdim      } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2314263508Sdim        UninitializedFields.insert(IFD->getAnonField());
2315263508Sdim      }
2316263508Sdim    }
2317263508Sdim
2318263508Sdim    for (CXXConstructorDecl::init_const_iterator FieldInit =
2319263508Sdim             Constructor->init_begin(),
2320263508Sdim             FieldInitEnd = Constructor->init_end();
2321263508Sdim         FieldInit != FieldInitEnd; ++FieldInit) {
2322263508Sdim
2323263508Sdim      Expr *InitExpr = (*FieldInit)->getInit();
2324263508Sdim
2325263508Sdim      CheckInitExprContainsUninitializedFields(
2326263508Sdim          SemaRef, InitExpr, UninitializedFields, Constructor);
2327263508Sdim
2328263508Sdim      if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2329263508Sdim        UninitializedFields.erase(Field);
2330263508Sdim    }
2331263508Sdim  }
2332243830Sdim} // namespace
2333243830Sdim
2334223017Sdim/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2335226633Sdim/// in-class initializer for a non-static C++ class member, and after
2336226633Sdim/// instantiating an in-class initializer in a class template. Such actions
2337226633Sdim/// are deferred until the class is complete.
2338223017Sdimvoid
2339239462SdimSema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2340223017Sdim                                       Expr *InitExpr) {
2341223017Sdim  FieldDecl *FD = cast<FieldDecl>(D);
2342239462Sdim  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2343239462Sdim         "must set init style when field is created");
2344223017Sdim
2345223017Sdim  if (!InitExpr) {
2346223017Sdim    FD->setInvalidDecl();
2347223017Sdim    FD->removeInClassInitializer();
2348223017Sdim    return;
2349223017Sdim  }
2350223017Sdim
2351234353Sdim  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2352234353Sdim    FD->setInvalidDecl();
2353234353Sdim    FD->removeInClassInitializer();
2354234353Sdim    return;
2355234353Sdim  }
2356234353Sdim
2357223017Sdim  ExprResult Init = InitExpr;
2358249423Sdim  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2359234353Sdim    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2360239462Sdim    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2361234353Sdim        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2362239462Sdim        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2363251662Sdim    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2364251662Sdim    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2365223017Sdim    if (Init.isInvalid()) {
2366223017Sdim      FD->setInvalidDecl();
2367223017Sdim      return;
2368223017Sdim    }
2369223017Sdim  }
2370223017Sdim
2371249423Sdim  // C++11 [class.base.init]p7:
2372223017Sdim  //   The initialization of each base and member constitutes a
2373223017Sdim  //   full-expression.
2374249423Sdim  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2375223017Sdim  if (Init.isInvalid()) {
2376223017Sdim    FD->setInvalidDecl();
2377223017Sdim    return;
2378223017Sdim  }
2379223017Sdim
2380223017Sdim  InitExpr = Init.release();
2381223017Sdim
2382223017Sdim  FD->setInClassInitializer(InitExpr);
2383223017Sdim}
2384223017Sdim
2385201361Srdivacky/// \brief Find the direct and/or virtual base specifiers that
2386201361Srdivacky/// correspond to the given base type, for use in base initialization
2387201361Srdivacky/// within a constructor.
2388201361Srdivackystatic bool FindBaseInitializer(Sema &SemaRef,
2389201361Srdivacky                                CXXRecordDecl *ClassDecl,
2390201361Srdivacky                                QualType BaseType,
2391201361Srdivacky                                const CXXBaseSpecifier *&DirectBaseSpec,
2392201361Srdivacky                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2393201361Srdivacky  // First, check for a direct base class.
2394201361Srdivacky  DirectBaseSpec = 0;
2395201361Srdivacky  for (CXXRecordDecl::base_class_const_iterator Base
2396201361Srdivacky         = ClassDecl->bases_begin();
2397201361Srdivacky       Base != ClassDecl->bases_end(); ++Base) {
2398201361Srdivacky    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2399201361Srdivacky      // We found a direct base of this type. That's what we're
2400201361Srdivacky      // initializing.
2401201361Srdivacky      DirectBaseSpec = &*Base;
2402201361Srdivacky      break;
2403201361Srdivacky    }
2404201361Srdivacky  }
2405201361Srdivacky
2406201361Srdivacky  // Check for a virtual base class.
2407201361Srdivacky  // FIXME: We might be able to short-circuit this if we know in advance that
2408201361Srdivacky  // there are no virtual bases.
2409201361Srdivacky  VirtualBaseSpec = 0;
2410201361Srdivacky  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2411201361Srdivacky    // We haven't found a base yet; search the class hierarchy for a
2412201361Srdivacky    // virtual base class.
2413201361Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2414201361Srdivacky                       /*DetectVirtual=*/false);
2415201361Srdivacky    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2416201361Srdivacky                              BaseType, Paths)) {
2417201361Srdivacky      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2418201361Srdivacky           Path != Paths.end(); ++Path) {
2419201361Srdivacky        if (Path->back().Base->isVirtual()) {
2420201361Srdivacky          VirtualBaseSpec = Path->back().Base;
2421201361Srdivacky          break;
2422201361Srdivacky        }
2423201361Srdivacky      }
2424201361Srdivacky    }
2425201361Srdivacky  }
2426201361Srdivacky
2427201361Srdivacky  return DirectBaseSpec || VirtualBaseSpec;
2428201361Srdivacky}
2429201361Srdivacky
2430226633Sdim/// \brief Handle a C++ member initializer using braced-init-list syntax.
2431212904SdimMemInitResult
2432212904SdimSema::ActOnMemInitializer(Decl *ConstructorD,
2433193326Sed                          Scope *S,
2434207619Srdivacky                          CXXScopeSpec &SS,
2435193326Sed                          IdentifierInfo *MemberOrBase,
2436212904Sdim                          ParsedType TemplateTypeTy,
2437234353Sdim                          const DeclSpec &DS,
2438193326Sed                          SourceLocation IdLoc,
2439226633Sdim                          Expr *InitList,
2440226633Sdim                          SourceLocation EllipsisLoc) {
2441226633Sdim  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2442234353Sdim                             DS, IdLoc, InitList,
2443234353Sdim                             EllipsisLoc);
2444226633Sdim}
2445226633Sdim
2446226633Sdim/// \brief Handle a C++ member initializer using parentheses syntax.
2447226633SdimMemInitResult
2448226633SdimSema::ActOnMemInitializer(Decl *ConstructorD,
2449226633Sdim                          Scope *S,
2450226633Sdim                          CXXScopeSpec &SS,
2451226633Sdim                          IdentifierInfo *MemberOrBase,
2452226633Sdim                          ParsedType TemplateTypeTy,
2453234353Sdim                          const DeclSpec &DS,
2454226633Sdim                          SourceLocation IdLoc,
2455193326Sed                          SourceLocation LParenLoc,
2456263508Sdim                          ArrayRef<Expr *> Args,
2457218893Sdim                          SourceLocation RParenLoc,
2458218893Sdim                          SourceLocation EllipsisLoc) {
2459243830Sdim  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2460263508Sdim                                           Args, RParenLoc);
2461226633Sdim  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2462234353Sdim                             DS, IdLoc, List, EllipsisLoc);
2463226633Sdim}
2464226633Sdim
2465234353Sdimnamespace {
2466234353Sdim
2467234353Sdim// Callback to only accept typo corrections that can be a valid C++ member
2468234353Sdim// intializer: either a non-static field member or a base class.
2469234353Sdimclass MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2470263508Sdimpublic:
2471234353Sdim  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2472234353Sdim      : ClassDecl(ClassDecl) {}
2473234353Sdim
2474263508Sdim  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
2475234353Sdim    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2476234353Sdim      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2477234353Sdim        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2478263508Sdim      return isa<TypeDecl>(ND);
2479234353Sdim    }
2480234353Sdim    return false;
2481234353Sdim  }
2482234353Sdim
2483263508Sdimprivate:
2484234353Sdim  CXXRecordDecl *ClassDecl;
2485234353Sdim};
2486234353Sdim
2487234353Sdim}
2488234353Sdim
2489226633Sdim/// \brief Handle a C++ member initializer.
2490226633SdimMemInitResult
2491226633SdimSema::BuildMemInitializer(Decl *ConstructorD,
2492226633Sdim                          Scope *S,
2493226633Sdim                          CXXScopeSpec &SS,
2494226633Sdim                          IdentifierInfo *MemberOrBase,
2495226633Sdim                          ParsedType TemplateTypeTy,
2496234353Sdim                          const DeclSpec &DS,
2497226633Sdim                          SourceLocation IdLoc,
2498234353Sdim                          Expr *Init,
2499226633Sdim                          SourceLocation EllipsisLoc) {
2500194711Sed  if (!ConstructorD)
2501194711Sed    return true;
2502198092Srdivacky
2503198092Srdivacky  AdjustDeclIfTemplate(ConstructorD);
2504198092Srdivacky
2505198092Srdivacky  CXXConstructorDecl *Constructor
2506212904Sdim    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2507193326Sed  if (!Constructor) {
2508193326Sed    // The user wrote a constructor initializer on a function that is
2509193326Sed    // not a C++ constructor. Ignore the error for now, because we may
2510193326Sed    // have more member initializers coming; we'll diagnose it just
2511193326Sed    // once in ActOnMemInitializers.
2512193326Sed    return true;
2513193326Sed  }
2514193326Sed
2515193326Sed  CXXRecordDecl *ClassDecl = Constructor->getParent();
2516193326Sed
2517193326Sed  // C++ [class.base.init]p2:
2518193326Sed  //   Names in a mem-initializer-id are looked up in the scope of the
2519218893Sdim  //   constructor's class and, if not found in that scope, are looked
2520218893Sdim  //   up in the scope containing the constructor's definition.
2521218893Sdim  //   [Note: if the constructor's class contains a member with the
2522218893Sdim  //   same name as a direct or virtual base class of the class, a
2523218893Sdim  //   mem-initializer-id naming the member or base class and composed
2524218893Sdim  //   of a single identifier refers to the class member. A
2525193326Sed  //   mem-initializer-id for the hidden base class may be specified
2526193326Sed  //   using a qualified name. ]
2527195341Sed  if (!SS.getScopeRep() && !TemplateTypeTy) {
2528195341Sed    // Look for a member, first.
2529198092Srdivacky    DeclContext::lookup_result Result
2530195341Sed      = ClassDecl->lookup(MemberOrBase);
2531249423Sdim    if (!Result.empty()) {
2532234353Sdim      ValueDecl *Member;
2533249423Sdim      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2534249423Sdim          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2535218893Sdim        if (EllipsisLoc.isValid())
2536218893Sdim          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2537234353Sdim            << MemberOrBase
2538234353Sdim            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2539226633Sdim
2540234353Sdim        return BuildMemberInitializer(Member, Init, IdLoc);
2541218893Sdim      }
2542218893Sdim    }
2543193326Sed  }
2544193326Sed  // It didn't name a member, so see if it names a class.
2545200583Srdivacky  QualType BaseType;
2546201361Srdivacky  TypeSourceInfo *TInfo = 0;
2547200583Srdivacky
2548201361Srdivacky  if (TemplateTypeTy) {
2549200583Srdivacky    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2550234353Sdim  } else if (DS.getTypeSpecType() == TST_decltype) {
2551234353Sdim    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2552201361Srdivacky  } else {
2553201361Srdivacky    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2554201361Srdivacky    LookupParsedName(R, S, &SS);
2555193326Sed
2556201361Srdivacky    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2557201361Srdivacky    if (!TyD) {
2558201361Srdivacky      if (R.isAmbiguous()) return true;
2559201361Srdivacky
2560207619Srdivacky      // We don't want access-control diagnostics here.
2561207619Srdivacky      R.suppressDiagnostics();
2562207619Srdivacky
2563202879Srdivacky      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2564202879Srdivacky        bool NotUnknownSpecialization = false;
2565202879Srdivacky        DeclContext *DC = computeDeclContext(SS, false);
2566202879Srdivacky        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2567202879Srdivacky          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2568202879Srdivacky
2569202879Srdivacky        if (!NotUnknownSpecialization) {
2570202879Srdivacky          // When the scope specifier can refer to a member of an unknown
2571202879Srdivacky          // specialization, we take it as a type name.
2572221345Sdim          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2573221345Sdim                                       SS.getWithLocInContext(Context),
2574221345Sdim                                       *MemberOrBase, IdLoc);
2575204962Srdivacky          if (BaseType.isNull())
2576204962Srdivacky            return true;
2577204962Srdivacky
2578202879Srdivacky          R.clear();
2579210299Sed          R.setLookupName(MemberOrBase);
2580202879Srdivacky        }
2581202879Srdivacky      }
2582202879Srdivacky
2583201361Srdivacky      // If no results were found, try to correct typos.
2584224145Sdim      TypoCorrection Corr;
2585234353Sdim      MemInitializerValidatorCCC Validator(ClassDecl);
2586202879Srdivacky      if (R.empty() && BaseType.isNull() &&
2587224145Sdim          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2588234353Sdim                              Validator, ClassDecl))) {
2589224145Sdim        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2590234353Sdim          // We have found a non-static data member with a similar
2591234353Sdim          // name to what was typed; complain and initialize that
2592234353Sdim          // member.
2593263508Sdim          diagnoseTypo(Corr,
2594263508Sdim                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
2595263508Sdim                         << MemberOrBase << true);
2596234353Sdim          return BuildMemberInitializer(Member, Init, IdLoc);
2597224145Sdim        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2598201361Srdivacky          const CXXBaseSpecifier *DirectBaseSpec;
2599201361Srdivacky          const CXXBaseSpecifier *VirtualBaseSpec;
2600201361Srdivacky          if (FindBaseInitializer(*this, ClassDecl,
2601201361Srdivacky                                  Context.getTypeDeclType(Type),
2602201361Srdivacky                                  DirectBaseSpec, VirtualBaseSpec)) {
2603201361Srdivacky            // We have found a direct or virtual base class with a
2604201361Srdivacky            // similar name to what was typed; complain and initialize
2605201361Srdivacky            // that base class.
2606263508Sdim            diagnoseTypo(Corr,
2607263508Sdim                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608263508Sdim                           << MemberOrBase << false,
2609263508Sdim                         PDiag() /*Suppress note, we provide our own.*/);
2610202379Srdivacky
2611263508Sdim            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2612263508Sdim                                                              : VirtualBaseSpec;
2613234353Sdim            Diag(BaseSpec->getLocStart(),
2614202379Srdivacky                 diag::note_base_class_specified_here)
2615202379Srdivacky              << BaseSpec->getType()
2616202379Srdivacky              << BaseSpec->getSourceRange();
2617202379Srdivacky
2618201361Srdivacky            TyD = Type;
2619201361Srdivacky          }
2620201361Srdivacky        }
2621201361Srdivacky      }
2622201361Srdivacky
2623202879Srdivacky      if (!TyD && BaseType.isNull()) {
2624201361Srdivacky        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2625234353Sdim          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2626201361Srdivacky        return true;
2627201361Srdivacky      }
2628201361Srdivacky    }
2629201361Srdivacky
2630202879Srdivacky    if (BaseType.isNull()) {
2631202879Srdivacky      BaseType = Context.getTypeDeclType(TyD);
2632202879Srdivacky      if (SS.isSet()) {
2633202879Srdivacky        NestedNameSpecifier *Qualifier =
2634202879Srdivacky          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2635201361Srdivacky
2636202879Srdivacky        // FIXME: preserve source range information
2637208600Srdivacky        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2638202879Srdivacky      }
2639201361Srdivacky    }
2640201361Srdivacky  }
2641201361Srdivacky
2642200583Srdivacky  if (!TInfo)
2643200583Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2644198092Srdivacky
2645234353Sdim  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2646198092Srdivacky}
2647198092Srdivacky
2648226633Sdim/// Checks a member initializer expression for cases where reference (or
2649226633Sdim/// pointer) members are bound to by-value parameters (or their addresses).
2650226633Sdimstatic void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2651226633Sdim                                               Expr *Init,
2652226633Sdim                                               SourceLocation IdLoc) {
2653226633Sdim  QualType MemberTy = Member->getType();
2654226633Sdim
2655226633Sdim  // We only handle pointers and references currently.
2656226633Sdim  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2657226633Sdim  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2658226633Sdim    return;
2659226633Sdim
2660226633Sdim  const bool IsPointer = MemberTy->isPointerType();
2661226633Sdim  if (IsPointer) {
2662226633Sdim    if (const UnaryOperator *Op
2663226633Sdim          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2664226633Sdim      // The only case we're worried about with pointers requires taking the
2665226633Sdim      // address.
2666226633Sdim      if (Op->getOpcode() != UO_AddrOf)
2667226633Sdim        return;
2668226633Sdim
2669226633Sdim      Init = Op->getSubExpr();
2670226633Sdim    } else {
2671226633Sdim      // We only handle address-of expression initializers for pointers.
2672226633Sdim      return;
2673226633Sdim    }
2674226633Sdim  }
2675226633Sdim
2676263508Sdim  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2677226633Sdim    // We only warn when referring to a non-reference parameter declaration.
2678226633Sdim    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2679226633Sdim    if (!Parameter || Parameter->getType()->isReferenceType())
2680226633Sdim      return;
2681226633Sdim
2682226633Sdim    S.Diag(Init->getExprLoc(),
2683226633Sdim           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2684226633Sdim                     : diag::warn_bind_ref_member_to_parameter)
2685226633Sdim      << Member << Parameter << Init->getSourceRange();
2686226633Sdim  } else {
2687226633Sdim    // Other initializers are fine.
2688226633Sdim    return;
2689226633Sdim  }
2690226633Sdim
2691226633Sdim  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2692226633Sdim    << (unsigned)IsPointer;
2693226633Sdim}
2694226633Sdim
2695212904SdimMemInitResult
2696234353SdimSema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2697226633Sdim                             SourceLocation IdLoc) {
2698218893Sdim  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2699218893Sdim  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2700218893Sdim  assert((DirectMember || IndirectMember) &&
2701218893Sdim         "Member must be a FieldDecl or IndirectFieldDecl");
2702218893Sdim
2703234353Sdim  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2704234353Sdim    return true;
2705234353Sdim
2706218893Sdim  if (Member->isInvalidDecl())
2707218893Sdim    return true;
2708218893Sdim
2709251662Sdim  MultiExprArg Args;
2710234353Sdim  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2711251662Sdim    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2712249423Sdim  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2713251662Sdim    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2714249423Sdim  } else {
2715249423Sdim    // Template instantiation doesn't reconstruct ParenListExprs for us.
2716251662Sdim    Args = Init;
2717234353Sdim  }
2718239462Sdim
2719234353Sdim  SourceRange InitRange = Init->getSourceRange();
2720198092Srdivacky
2721234353Sdim  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2722203955Srdivacky    // Can't check initialization for a member of dependent type or when
2723203955Srdivacky    // any of the arguments are type-dependent expressions.
2724224145Sdim    DiscardCleanupsInEvaluationContext();
2725218893Sdim  } else {
2726234353Sdim    bool InitList = false;
2727234353Sdim    if (isa<InitListExpr>(Init)) {
2728234353Sdim      InitList = true;
2729251662Sdim      Args = Init;
2730234353Sdim    }
2731234353Sdim
2732218893Sdim    // Initialize the member.
2733218893Sdim    InitializedEntity MemberEntity =
2734218893Sdim      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2735218893Sdim                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2736218893Sdim    InitializationKind Kind =
2737234353Sdim      InitList ? InitializationKind::CreateDirectList(IdLoc)
2738234353Sdim               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2739234353Sdim                                                  InitRange.getEnd());
2740218893Sdim
2741251662Sdim    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2742251662Sdim    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2743218893Sdim    if (MemberInit.isInvalid())
2744218893Sdim      return true;
2745218893Sdim
2746263508Sdim    CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2747263508Sdim
2748249423Sdim    // C++11 [class.base.init]p7:
2749218893Sdim    //   The initialization of each base and member constitutes a
2750218893Sdim    //   full-expression.
2751249423Sdim    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2752218893Sdim    if (MemberInit.isInvalid())
2753218893Sdim      return true;
2754218893Sdim
2755249423Sdim    Init = MemberInit.get();
2756193326Sed  }
2757203955Srdivacky
2758218893Sdim  if (DirectMember) {
2759234353Sdim    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2760234353Sdim                                            InitRange.getBegin(), Init,
2761234353Sdim                                            InitRange.getEnd());
2762218893Sdim  } else {
2763234353Sdim    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2764234353Sdim                                            InitRange.getBegin(), Init,
2765234353Sdim                                            InitRange.getEnd());
2766203955Srdivacky  }
2767218893Sdim}
2768203955Srdivacky
2769218893SdimMemInitResult
2770234353SdimSema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2771221345Sdim                                 CXXRecordDecl *ClassDecl) {
2772234353Sdim  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2773249423Sdim  if (!LangOpts.CPlusPlus11)
2774234353Sdim    return Diag(NameLoc, diag::err_delegating_ctor)
2775218893Sdim      << TInfo->getTypeLoc().getLocalSourceRange();
2776234353Sdim  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2777218893Sdim
2778234353Sdim  bool InitList = true;
2779251662Sdim  MultiExprArg Args = Init;
2780234353Sdim  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2781234353Sdim    InitList = false;
2782251662Sdim    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2783234353Sdim  }
2784234353Sdim
2785234353Sdim  SourceRange InitRange = Init->getSourceRange();
2786221345Sdim  // Initialize the object.
2787221345Sdim  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2788221345Sdim                                     QualType(ClassDecl->getTypeForDecl(), 0));
2789221345Sdim  InitializationKind Kind =
2790234353Sdim    InitList ? InitializationKind::CreateDirectList(NameLoc)
2791234353Sdim             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2792234353Sdim                                                InitRange.getEnd());
2793251662Sdim  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2794234353Sdim  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2795251662Sdim                                              Args, 0);
2796221345Sdim  if (DelegationInit.isInvalid())
2797221345Sdim    return true;
2798221345Sdim
2799234353Sdim  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2800234353Sdim         "Delegating constructor with no target?");
2801221345Sdim
2802249423Sdim  // C++11 [class.base.init]p7:
2803221345Sdim  //   The initialization of each base and member constitutes a
2804221345Sdim  //   full-expression.
2805249423Sdim  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2806249423Sdim                                       InitRange.getBegin());
2807221345Sdim  if (DelegationInit.isInvalid())
2808221345Sdim    return true;
2809221345Sdim
2810239462Sdim  // If we are in a dependent context, template instantiation will
2811239462Sdim  // perform this type-checking again. Just save the arguments that we
2812239462Sdim  // received in a ParenListExpr.
2813239462Sdim  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2814239462Sdim  // of the information that we have about the base
2815239462Sdim  // initializer. However, deconstructing the ASTs is a dicey process,
2816239462Sdim  // and this approach is far more likely to get the corner cases right.
2817239462Sdim  if (CurContext->isDependentContext())
2818239462Sdim    DelegationInit = Owned(Init);
2819239462Sdim
2820234353Sdim  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2821221345Sdim                                          DelegationInit.takeAs<Expr>(),
2822234353Sdim                                          InitRange.getEnd());
2823198092Srdivacky}
2824198092Srdivacky
2825212904SdimMemInitResult
2826200583SrdivackySema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2827234353Sdim                           Expr *Init, CXXRecordDecl *ClassDecl,
2828218893Sdim                           SourceLocation EllipsisLoc) {
2829210299Sed  SourceLocation BaseLoc
2830210299Sed    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2831226633Sdim
2832210299Sed  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2833210299Sed    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2834210299Sed             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2835210299Sed
2836210299Sed  // C++ [class.base.init]p2:
2837210299Sed  //   [...] Unless the mem-initializer-id names a nonstatic data
2838218893Sdim  //   member of the constructor's class or a direct or virtual base
2839210299Sed  //   of that class, the mem-initializer is ill-formed. A
2840210299Sed  //   mem-initializer-list can initialize a base class using any
2841210299Sed  //   name that denotes that base class type.
2842234353Sdim  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2843210299Sed
2844234353Sdim  SourceRange InitRange = Init->getSourceRange();
2845218893Sdim  if (EllipsisLoc.isValid()) {
2846218893Sdim    // This is a pack expansion.
2847218893Sdim    if (!BaseType->containsUnexpandedParameterPack())  {
2848218893Sdim      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2849234353Sdim        << SourceRange(BaseLoc, InitRange.getEnd());
2850226633Sdim
2851218893Sdim      EllipsisLoc = SourceLocation();
2852218893Sdim    }
2853218893Sdim  } else {
2854218893Sdim    // Check for any unexpanded parameter packs.
2855218893Sdim    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2856218893Sdim      return true;
2857226633Sdim
2858234353Sdim    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2859226633Sdim      return true;
2860218893Sdim  }
2861226633Sdim
2862210299Sed  // Check for direct and virtual base classes.
2863210299Sed  const CXXBaseSpecifier *DirectBaseSpec = 0;
2864210299Sed  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2865210299Sed  if (!Dependent) {
2866218893Sdim    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2867218893Sdim                                       BaseType))
2868234353Sdim      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2869218893Sdim
2870210299Sed    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2871210299Sed                        VirtualBaseSpec);
2872210299Sed
2873210299Sed    // C++ [base.class.init]p2:
2874210299Sed    // Unless the mem-initializer-id names a nonstatic data member of the
2875210299Sed    // constructor's class or a direct or virtual base of that class, the
2876210299Sed    // mem-initializer is ill-formed.
2877210299Sed    if (!DirectBaseSpec && !VirtualBaseSpec) {
2878210299Sed      // If the class has any dependent bases, then it's possible that
2879210299Sed      // one of those types will resolve to the same type as
2880210299Sed      // BaseType. Therefore, just treat this as a dependent base
2881210299Sed      // class initialization.  FIXME: Should we try to check the
2882210299Sed      // initialization anyway? It seems odd.
2883210299Sed      if (ClassDecl->hasAnyDependentBases())
2884210299Sed        Dependent = true;
2885210299Sed      else
2886210299Sed        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2887210299Sed          << BaseType << Context.getTypeDeclType(ClassDecl)
2888210299Sed          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2889210299Sed    }
2890210299Sed  }
2891210299Sed
2892210299Sed  if (Dependent) {
2893224145Sdim    DiscardCleanupsInEvaluationContext();
2894198092Srdivacky
2895226633Sdim    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2896226633Sdim                                            /*IsVirtual=*/false,
2897234353Sdim                                            InitRange.getBegin(), Init,
2898234353Sdim                                            InitRange.getEnd(), EllipsisLoc);
2899193326Sed  }
2900193326Sed
2901203955Srdivacky  // C++ [base.class.init]p2:
2902203955Srdivacky  //   If a mem-initializer-id is ambiguous because it designates both
2903203955Srdivacky  //   a direct non-virtual base class and an inherited virtual base
2904203955Srdivacky  //   class, the mem-initializer is ill-formed.
2905203955Srdivacky  if (DirectBaseSpec && VirtualBaseSpec)
2906203955Srdivacky    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2907208600Srdivacky      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2908203955Srdivacky
2909263508Sdim  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2910203955Srdivacky  if (!BaseSpec)
2911263508Sdim    BaseSpec = VirtualBaseSpec;
2912203955Srdivacky
2913203955Srdivacky  // Initialize the base.
2914234353Sdim  bool InitList = true;
2915251662Sdim  MultiExprArg Args = Init;
2916234353Sdim  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2917234353Sdim    InitList = false;
2918251662Sdim    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2919234353Sdim  }
2920234353Sdim
2921203955Srdivacky  InitializedEntity BaseEntity =
2922207619Srdivacky    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2923234353Sdim  InitializationKind Kind =
2924234353Sdim    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2925234353Sdim             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2926234353Sdim                                                InitRange.getEnd());
2927251662Sdim  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2928251662Sdim  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2929203955Srdivacky  if (BaseInit.isInvalid())
2930203955Srdivacky    return true;
2931218893Sdim
2932249423Sdim  // C++11 [class.base.init]p7:
2933249423Sdim  //   The initialization of each base and member constitutes a
2934203955Srdivacky  //   full-expression.
2935249423Sdim  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2936203955Srdivacky  if (BaseInit.isInvalid())
2937203955Srdivacky    return true;
2938203955Srdivacky
2939203955Srdivacky  // If we are in a dependent context, template instantiation will
2940203955Srdivacky  // perform this type-checking again. Just save the arguments that we
2941203955Srdivacky  // received in a ParenListExpr.
2942203955Srdivacky  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2943203955Srdivacky  // of the information that we have about the base
2944203955Srdivacky  // initializer. However, deconstructing the ASTs is a dicey process,
2945203955Srdivacky  // and this approach is far more likely to get the corner cases right.
2946226633Sdim  if (CurContext->isDependentContext())
2947234353Sdim    BaseInit = Owned(Init);
2948198092Srdivacky
2949218893Sdim  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2950226633Sdim                                          BaseSpec->isVirtual(),
2951234353Sdim                                          InitRange.getBegin(),
2952226633Sdim                                          BaseInit.takeAs<Expr>(),
2953234353Sdim                                          InitRange.getEnd(), EllipsisLoc);
2954193326Sed}
2955193326Sed
2956226633Sdim// Create a static_cast\<T&&>(expr).
2957249423Sdimstatic Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2958249423Sdim  if (T.isNull()) T = E->getType();
2959249423Sdim  QualType TargetType = SemaRef.BuildReferenceType(
2960249423Sdim      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2961226633Sdim  SourceLocation ExprLoc = E->getLocStart();
2962226633Sdim  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2963226633Sdim      TargetType, ExprLoc);
2964226633Sdim
2965226633Sdim  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2966226633Sdim                                   SourceRange(ExprLoc, ExprLoc),
2967226633Sdim                                   E->getSourceRange()).take();
2968226633Sdim}
2969226633Sdim
2970207619Srdivacky/// ImplicitInitializerKind - How an implicit base or member initializer should
2971207619Srdivacky/// initialize its base or member.
2972207619Srdivackyenum ImplicitInitializerKind {
2973207619Srdivacky  IIK_Default,
2974207619Srdivacky  IIK_Copy,
2975249423Sdim  IIK_Move,
2976249423Sdim  IIK_Inherit
2977207619Srdivacky};
2978207619Srdivacky
2979207619Srdivackystatic bool
2980207619SrdivackyBuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2981207619Srdivacky                             ImplicitInitializerKind ImplicitInitKind,
2982207619Srdivacky                             CXXBaseSpecifier *BaseSpec,
2983207619Srdivacky                             bool IsInheritedVirtualBase,
2984218893Sdim                             CXXCtorInitializer *&CXXBaseInit) {
2985207619Srdivacky  InitializedEntity InitEntity
2986207619Srdivacky    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2987207619Srdivacky                                        IsInheritedVirtualBase);
2988207619Srdivacky
2989212904Sdim  ExprResult BaseInit;
2990207619Srdivacky
2991207619Srdivacky  switch (ImplicitInitKind) {
2992249423Sdim  case IIK_Inherit: {
2993249423Sdim    const CXXRecordDecl *Inherited =
2994249423Sdim        Constructor->getInheritedConstructor()->getParent();
2995249423Sdim    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2996249423Sdim    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2997249423Sdim      // C++11 [class.inhctor]p8:
2998249423Sdim      //   Each expression in the expression-list is of the form
2999249423Sdim      //   static_cast<T&&>(p), where p is the name of the corresponding
3000249423Sdim      //   constructor parameter and T is the declared type of p.
3001249423Sdim      SmallVector<Expr*, 16> Args;
3002249423Sdim      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3003249423Sdim        ParmVarDecl *PD = Constructor->getParamDecl(I);
3004249423Sdim        ExprResult ArgExpr =
3005249423Sdim            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3006249423Sdim                                     VK_LValue, SourceLocation());
3007249423Sdim        if (ArgExpr.isInvalid())
3008249423Sdim          return true;
3009249423Sdim        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3010249423Sdim      }
3011249423Sdim
3012249423Sdim      InitializationKind InitKind = InitializationKind::CreateDirect(
3013249423Sdim          Constructor->getLocation(), SourceLocation(), SourceLocation());
3014251662Sdim      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3015249423Sdim      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3016249423Sdim      break;
3017249423Sdim    }
3018249423Sdim  }
3019249423Sdim  // Fall through.
3020207619Srdivacky  case IIK_Default: {
3021207619Srdivacky    InitializationKind InitKind
3022207619Srdivacky      = InitializationKind::CreateDefault(Constructor->getLocation());
3023251662Sdim    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3024251662Sdim    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3025207619Srdivacky    break;
3026207619Srdivacky  }
3027207619Srdivacky
3028226633Sdim  case IIK_Move:
3029207619Srdivacky  case IIK_Copy: {
3030226633Sdim    bool Moving = ImplicitInitKind == IIK_Move;
3031207619Srdivacky    ParmVarDecl *Param = Constructor->getParamDecl(0);
3032207619Srdivacky    QualType ParamType = Param->getType().getNonReferenceType();
3033234353Sdim
3034207619Srdivacky    Expr *CopyCtorArg =
3035234353Sdim      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3036234353Sdim                          SourceLocation(), Param, false,
3037218893Sdim                          Constructor->getLocation(), ParamType,
3038218893Sdim                          VK_LValue, 0);
3039226633Sdim
3040234353Sdim    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3041234353Sdim
3042207619Srdivacky    // Cast to the base class to avoid ambiguities.
3043207619Srdivacky    QualType ArgTy =
3044207619Srdivacky      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3045207619Srdivacky                                       ParamType.getQualifiers());
3046207619Srdivacky
3047226633Sdim    if (Moving) {
3048226633Sdim      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3049226633Sdim    }
3050226633Sdim
3051212904Sdim    CXXCastPath BasePath;
3052212904Sdim    BasePath.push_back(BaseSpec);
3053221345Sdim    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3054221345Sdim                                            CK_UncheckedDerivedToBase,
3055226633Sdim                                            Moving ? VK_XValue : VK_LValue,
3056226633Sdim                                            &BasePath).take();
3057212904Sdim
3058207619Srdivacky    InitializationKind InitKind
3059207619Srdivacky      = InitializationKind::CreateDirect(Constructor->getLocation(),
3060207619Srdivacky                                         SourceLocation(), SourceLocation());
3061251662Sdim    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3062251662Sdim    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3063207619Srdivacky    break;
3064207619Srdivacky  }
3065207619Srdivacky  }
3066212904Sdim
3067218893Sdim  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3068212904Sdim  if (BaseInit.isInvalid())
3069212904Sdim    return true;
3070207619Srdivacky
3071207619Srdivacky  CXXBaseInit =
3072218893Sdim    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3073207619Srdivacky               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3074207619Srdivacky                                                        SourceLocation()),
3075207619Srdivacky                                             BaseSpec->isVirtual(),
3076207619Srdivacky                                             SourceLocation(),
3077207619Srdivacky                                             BaseInit.takeAs<Expr>(),
3078218893Sdim                                             SourceLocation(),
3079207619Srdivacky                                             SourceLocation());
3080207619Srdivacky
3081207619Srdivacky  return false;
3082207619Srdivacky}
3083207619Srdivacky
3084226633Sdimstatic bool RefersToRValueRef(Expr *MemRef) {
3085226633Sdim  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3086226633Sdim  return Referenced->getType()->isRValueReferenceType();
3087226633Sdim}
3088226633Sdim
3089207619Srdivackystatic bool
3090207619SrdivackyBuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3091207619Srdivacky                               ImplicitInitializerKind ImplicitInitKind,
3092226633Sdim                               FieldDecl *Field, IndirectFieldDecl *Indirect,
3093218893Sdim                               CXXCtorInitializer *&CXXMemberInit) {
3094208600Srdivacky  if (Field->isInvalidDecl())
3095208600Srdivacky    return true;
3096208600Srdivacky
3097210299Sed  SourceLocation Loc = Constructor->getLocation();
3098210299Sed
3099226633Sdim  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3100226633Sdim    bool Moving = ImplicitInitKind == IIK_Move;
3101207619Srdivacky    ParmVarDecl *Param = Constructor->getParamDecl(0);
3102207619Srdivacky    QualType ParamType = Param->getType().getNonReferenceType();
3103224145Sdim
3104224145Sdim    // Suppress copying zero-width bitfields.
3105226633Sdim    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3106226633Sdim      return false;
3107234353Sdim
3108207619Srdivacky    Expr *MemberExprBase =
3109234353Sdim      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3110234353Sdim                          SourceLocation(), Param, false,
3111218893Sdim                          Loc, ParamType, VK_LValue, 0);
3112208600Srdivacky
3113234353Sdim    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3114234353Sdim
3115226633Sdim    if (Moving) {
3116226633Sdim      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3117226633Sdim    }
3118226633Sdim
3119208600Srdivacky    // Build a reference to this field within the parameter.
3120208600Srdivacky    CXXScopeSpec SS;
3121208600Srdivacky    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3122208600Srdivacky                              Sema::LookupMemberName);
3123226633Sdim    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3124226633Sdim                                  : cast<ValueDecl>(Field), AS_public);
3125208600Srdivacky    MemberLookup.resolveKind();
3126226633Sdim    ExprResult CtorArg
3127212904Sdim      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3128208600Srdivacky                                         ParamType, Loc,
3129208600Srdivacky                                         /*IsArrow=*/false,
3130208600Srdivacky                                         SS,
3131234353Sdim                                         /*TemplateKWLoc=*/SourceLocation(),
3132208600Srdivacky                                         /*FirstQualifierInScope=*/0,
3133208600Srdivacky                                         MemberLookup,
3134208600Srdivacky                                         /*TemplateArgs=*/0);
3135226633Sdim    if (CtorArg.isInvalid())
3136208600Srdivacky      return true;
3137226633Sdim
3138226633Sdim    // C++11 [class.copy]p15:
3139226633Sdim    //   - if a member m has rvalue reference type T&&, it is direct-initialized
3140226633Sdim    //     with static_cast<T&&>(x.m);
3141226633Sdim    if (RefersToRValueRef(CtorArg.get())) {
3142226633Sdim      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3143226633Sdim    }
3144226633Sdim
3145208600Srdivacky    // When the field we are copying is an array, create index variables for
3146208600Srdivacky    // each dimension of the array. We use these index variables to subscript
3147208600Srdivacky    // the source array, and other clients (e.g., CodeGen) will perform the
3148208600Srdivacky    // necessary iteration with these index variables.
3149226633Sdim    SmallVector<VarDecl *, 4> IndexVariables;
3150208600Srdivacky    QualType BaseType = Field->getType();
3151208600Srdivacky    QualType SizeType = SemaRef.Context.getSizeType();
3152226633Sdim    bool InitializingArray = false;
3153208600Srdivacky    while (const ConstantArrayType *Array
3154208600Srdivacky                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3155226633Sdim      InitializingArray = true;
3156208600Srdivacky      // Create the iteration variable for this array index.
3157208600Srdivacky      IdentifierInfo *IterationVarName = 0;
3158208600Srdivacky      {
3159234353Sdim        SmallString<8> Str;
3160208600Srdivacky        llvm::raw_svector_ostream OS(Str);
3161208600Srdivacky        OS << "__i" << IndexVariables.size();
3162208600Srdivacky        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3163208600Srdivacky      }
3164208600Srdivacky      VarDecl *IterationVar
3165221345Sdim        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3166208600Srdivacky                          IterationVarName, SizeType,
3167208600Srdivacky                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3168249423Sdim                          SC_None);
3169208600Srdivacky      IndexVariables.push_back(IterationVar);
3170208600Srdivacky
3171208600Srdivacky      // Create a reference to the iteration variable.
3172212904Sdim      ExprResult IterationVarRef
3173234353Sdim        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3174208600Srdivacky      assert(!IterationVarRef.isInvalid() &&
3175208600Srdivacky             "Reference to invented variable cannot fail!");
3176234353Sdim      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3177234353Sdim      assert(!IterationVarRef.isInvalid() &&
3178234353Sdim             "Conversion of invented variable cannot fail!");
3179226633Sdim
3180208600Srdivacky      // Subscript the array with this iteration variable.
3181226633Sdim      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3182212904Sdim                                                        IterationVarRef.take(),
3183226633Sdim                                                        Loc);
3184226633Sdim      if (CtorArg.isInvalid())
3185208600Srdivacky        return true;
3186226633Sdim
3187208600Srdivacky      BaseType = Array->getElementType();
3188208600Srdivacky    }
3189226633Sdim
3190226633Sdim    // The array subscript expression is an lvalue, which is wrong for moving.
3191226633Sdim    if (Moving && InitializingArray)
3192226633Sdim      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3193226633Sdim
3194208600Srdivacky    // Construct the entity that we will be initializing. For an array, this
3195208600Srdivacky    // will be first element in the array, which may require several levels
3196208600Srdivacky    // of array-subscript entities.
3197226633Sdim    SmallVector<InitializedEntity, 4> Entities;
3198208600Srdivacky    Entities.reserve(1 + IndexVariables.size());
3199226633Sdim    if (Indirect)
3200226633Sdim      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3201226633Sdim    else
3202226633Sdim      Entities.push_back(InitializedEntity::InitializeMember(Field));
3203208600Srdivacky    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3204208600Srdivacky      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3205208600Srdivacky                                                              0,
3206208600Srdivacky                                                              Entities.back()));
3207207619Srdivacky
3208208600Srdivacky    // Direct-initialize to use the copy constructor.
3209207619Srdivacky    InitializationKind InitKind =
3210208600Srdivacky      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3211207619Srdivacky
3212226633Sdim    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3213251662Sdim    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3214207619Srdivacky
3215212904Sdim    ExprResult MemberInit
3216208600Srdivacky      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3217226633Sdim                        MultiExprArg(&CtorArgE, 1));
3218218893Sdim    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3219207619Srdivacky    if (MemberInit.isInvalid())
3220207619Srdivacky      return true;
3221208600Srdivacky
3222226633Sdim    if (Indirect) {
3223226633Sdim      assert(IndexVariables.size() == 0 &&
3224226633Sdim             "Indirect field improperly initialized");
3225226633Sdim      CXXMemberInit
3226226633Sdim        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3227226633Sdim                                                   Loc, Loc,
3228226633Sdim                                                   MemberInit.takeAs<Expr>(),
3229226633Sdim                                                   Loc);
3230226633Sdim    } else
3231226633Sdim      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3232226633Sdim                                                 Loc, MemberInit.takeAs<Expr>(),
3233226633Sdim                                                 Loc,
3234226633Sdim                                                 IndexVariables.data(),
3235226633Sdim                                                 IndexVariables.size());
3236207619Srdivacky    return false;
3237207619Srdivacky  }
3238207619Srdivacky
3239249423Sdim  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3240249423Sdim         "Unhandled implicit init kind!");
3241207619Srdivacky
3242207619Srdivacky  QualType FieldBaseElementType =
3243207619Srdivacky    SemaRef.Context.getBaseElementType(Field->getType());
3244207619Srdivacky
3245207619Srdivacky  if (FieldBaseElementType->isRecordType()) {
3246226633Sdim    InitializedEntity InitEntity
3247226633Sdim      = Indirect? InitializedEntity::InitializeMember(Indirect)
3248226633Sdim                : InitializedEntity::InitializeMember(Field);
3249207619Srdivacky    InitializationKind InitKind =
3250210299Sed      InitializationKind::CreateDefault(Loc);
3251212904Sdim
3252251662Sdim    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3253251662Sdim    ExprResult MemberInit =
3254251662Sdim      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3255251662Sdim
3256218893Sdim    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3257212904Sdim    if (MemberInit.isInvalid())
3258212904Sdim      return true;
3259207619Srdivacky
3260226633Sdim    if (Indirect)
3261226633Sdim      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3262226633Sdim                                                               Indirect, Loc,
3263226633Sdim                                                               Loc,
3264226633Sdim                                                               MemberInit.get(),
3265226633Sdim                                                               Loc);
3266226633Sdim    else
3267226633Sdim      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3268226633Sdim                                                               Field, Loc, Loc,
3269226633Sdim                                                               MemberInit.get(),
3270226633Sdim                                                               Loc);
3271207619Srdivacky    return false;
3272207619Srdivacky  }
3273207619Srdivacky
3274223017Sdim  if (!Field->getParent()->isUnion()) {
3275223017Sdim    if (FieldBaseElementType->isReferenceType()) {
3276223017Sdim      SemaRef.Diag(Constructor->getLocation(),
3277223017Sdim                   diag::err_uninitialized_member_in_ctor)
3278223017Sdim      << (int)Constructor->isImplicit()
3279223017Sdim      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3280223017Sdim      << 0 << Field->getDeclName();
3281223017Sdim      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3282223017Sdim      return true;
3283223017Sdim    }
3284207619Srdivacky
3285223017Sdim    if (FieldBaseElementType.isConstQualified()) {
3286223017Sdim      SemaRef.Diag(Constructor->getLocation(),
3287223017Sdim                   diag::err_uninitialized_member_in_ctor)
3288223017Sdim      << (int)Constructor->isImplicit()
3289223017Sdim      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290223017Sdim      << 1 << Field->getDeclName();
3291223017Sdim      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292223017Sdim      return true;
3293223017Sdim    }
3294207619Srdivacky  }
3295207619Srdivacky
3296234353Sdim  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3297224145Sdim      FieldBaseElementType->isObjCRetainableType() &&
3298224145Sdim      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3299224145Sdim      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3300239462Sdim    // ARC:
3301224145Sdim    //   Default-initialize Objective-C pointers to NULL.
3302224145Sdim    CXXMemberInit
3303224145Sdim      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3304224145Sdim                                                 Loc, Loc,
3305224145Sdim                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3306224145Sdim                                                 Loc);
3307224145Sdim    return false;
3308224145Sdim  }
3309224145Sdim
3310207619Srdivacky  // Nothing to initialize.
3311207619Srdivacky  CXXMemberInit = 0;
3312207619Srdivacky  return false;
3313207619Srdivacky}
3314208600Srdivacky
3315208600Srdivackynamespace {
3316208600Srdivackystruct BaseAndFieldInfo {
3317208600Srdivacky  Sema &S;
3318208600Srdivacky  CXXConstructorDecl *Ctor;
3319208600Srdivacky  bool AnyErrorsInInits;
3320208600Srdivacky  ImplicitInitializerKind IIK;
3321218893Sdim  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3322226633Sdim  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3323208600Srdivacky
3324208600Srdivacky  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3325208600Srdivacky    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3326226633Sdim    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3327226633Sdim    if (Generated && Ctor->isCopyConstructor())
3328208600Srdivacky      IIK = IIK_Copy;
3329226633Sdim    else if (Generated && Ctor->isMoveConstructor())
3330226633Sdim      IIK = IIK_Move;
3331249423Sdim    else if (Ctor->getInheritedConstructor())
3332249423Sdim      IIK = IIK_Inherit;
3333208600Srdivacky    else
3334208600Srdivacky      IIK = IIK_Default;
3335208600Srdivacky  }
3336234353Sdim
3337234353Sdim  bool isImplicitCopyOrMove() const {
3338234353Sdim    switch (IIK) {
3339234353Sdim    case IIK_Copy:
3340234353Sdim    case IIK_Move:
3341234353Sdim      return true;
3342234353Sdim
3343234353Sdim    case IIK_Default:
3344249423Sdim    case IIK_Inherit:
3345234353Sdim      return false;
3346234353Sdim    }
3347234353Sdim
3348234353Sdim    llvm_unreachable("Invalid ImplicitInitializerKind!");
3349234353Sdim  }
3350239462Sdim
3351239462Sdim  bool addFieldInitializer(CXXCtorInitializer *Init) {
3352239462Sdim    AllToInit.push_back(Init);
3353239462Sdim
3354239462Sdim    // Check whether this initializer makes the field "used".
3355251662Sdim    if (Init->getInit()->HasSideEffects(S.Context))
3356239462Sdim      S.UnusedPrivateFields.remove(Init->getAnyMember());
3357239462Sdim
3358239462Sdim    return false;
3359239462Sdim  }
3360208600Srdivacky};
3361208600Srdivacky}
3362208600Srdivacky
3363226633Sdim/// \brief Determine whether the given indirect field declaration is somewhere
3364226633Sdim/// within an anonymous union.
3365226633Sdimstatic bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3366226633Sdim  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3367226633Sdim                                      CEnd = F->chain_end();
3368226633Sdim       C != CEnd; ++C)
3369226633Sdim    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3370226633Sdim      if (Record->isUnion())
3371226633Sdim        return true;
3372226633Sdim
3373226633Sdim  return false;
3374226633Sdim}
3375226633Sdim
3376234353Sdim/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3377234353Sdim/// array type.
3378234353Sdimstatic bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3379234353Sdim  if (T->isIncompleteArrayType())
3380234353Sdim    return true;
3381234353Sdim
3382234353Sdim  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3383234353Sdim    if (!ArrayT->getSize())
3384234353Sdim      return true;
3385234353Sdim
3386234353Sdim    T = ArrayT->getElementType();
3387234353Sdim  }
3388234353Sdim
3389234353Sdim  return false;
3390234353Sdim}
3391234353Sdim
3392223017Sdimstatic bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3393226633Sdim                                    FieldDecl *Field,
3394226633Sdim                                    IndirectFieldDecl *Indirect = 0) {
3395263508Sdim  if (Field->isInvalidDecl())
3396263508Sdim    return false;
3397208600Srdivacky
3398210299Sed  // Overwhelmingly common case: we have a direct initializer for this field.
3399239462Sdim  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3400239462Sdim    return Info.addFieldInitializer(Init);
3401208600Srdivacky
3402239462Sdim  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3403223017Sdim  // has a brace-or-equal-initializer, the entity is initialized as specified
3404223017Sdim  // in [dcl.init].
3405234353Sdim  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3406251662Sdim    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3407251662Sdim                                           Info.Ctor->getLocation(), Field);
3408226633Sdim    CXXCtorInitializer *Init;
3409226633Sdim    if (Indirect)
3410226633Sdim      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3411226633Sdim                                                      SourceLocation(),
3412251662Sdim                                                      SourceLocation(), DIE,
3413226633Sdim                                                      SourceLocation());
3414226633Sdim    else
3415226633Sdim      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3416226633Sdim                                                      SourceLocation(),
3417251662Sdim                                                      SourceLocation(), DIE,
3418226633Sdim                                                      SourceLocation());
3419239462Sdim    return Info.addFieldInitializer(Init);
3420223017Sdim  }
3421223017Sdim
3422226633Sdim  // Don't build an implicit initializer for union members if none was
3423226633Sdim  // explicitly specified.
3424226633Sdim  if (Field->getParent()->isUnion() ||
3425226633Sdim      (Indirect && isWithinAnonymousUnion(Indirect)))
3426226633Sdim    return false;
3427208600Srdivacky
3428234353Sdim  // Don't initialize incomplete or zero-length arrays.
3429234353Sdim  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3430234353Sdim    return false;
3431234353Sdim
3432208600Srdivacky  // Don't try to build an implicit initializer if there were semantic
3433208600Srdivacky  // errors in any of the initializers (and therefore we might be
3434208600Srdivacky  // missing some that the user actually wrote).
3435263508Sdim  if (Info.AnyErrorsInInits)
3436208600Srdivacky    return false;
3437208600Srdivacky
3438218893Sdim  CXXCtorInitializer *Init = 0;
3439226633Sdim  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3440226633Sdim                                     Indirect, Init))
3441208600Srdivacky    return true;
3442208600Srdivacky
3443239462Sdim  if (!Init)
3444239462Sdim    return false;
3445218893Sdim
3446239462Sdim  return Info.addFieldInitializer(Init);
3447208600Srdivacky}
3448221345Sdim
3449221345Sdimbool
3450221345SdimSema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3451221345Sdim                               CXXCtorInitializer *Initializer) {
3452223017Sdim  assert(Initializer->isDelegatingInitializer());
3453221345Sdim  Constructor->setNumCtorInitializers(1);
3454221345Sdim  CXXCtorInitializer **initializer =
3455221345Sdim    new (Context) CXXCtorInitializer*[1];
3456221345Sdim  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3457221345Sdim  Constructor->setCtorInitializers(initializer);
3458221345Sdim
3459223017Sdim  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3460234353Sdim    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3461223017Sdim    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3462221345Sdim  }
3463221345Sdim
3464223017Sdim  DelegatingCtorDecls.push_back(Constructor);
3465223017Sdim
3466221345Sdim  return false;
3467221345Sdim}
3468226633Sdim
3469249423Sdimbool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3470249423Sdim                               ArrayRef<CXXCtorInitializer *> Initializers) {
3471226633Sdim  if (Constructor->isDependentContext()) {
3472206084Srdivacky    // Just store the initializers as written, they will be checked during
3473206084Srdivacky    // instantiation.
3474249423Sdim    if (!Initializers.empty()) {
3475249423Sdim      Constructor->setNumCtorInitializers(Initializers.size());
3476218893Sdim      CXXCtorInitializer **baseOrMemberInitializers =
3477249423Sdim        new (Context) CXXCtorInitializer*[Initializers.size()];
3478249423Sdim      memcpy(baseOrMemberInitializers, Initializers.data(),
3479249423Sdim             Initializers.size() * sizeof(CXXCtorInitializer*));
3480218893Sdim      Constructor->setCtorInitializers(baseOrMemberInitializers);
3481206084Srdivacky    }
3482243830Sdim
3483243830Sdim    // Let template instantiation know whether we had errors.
3484243830Sdim    if (AnyErrors)
3485243830Sdim      Constructor->setInvalidDecl();
3486243830Sdim
3487206084Srdivacky    return false;
3488206084Srdivacky  }
3489206084Srdivacky
3490208600Srdivacky  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3491207619Srdivacky
3492198092Srdivacky  // We need to build the initializer AST according to order of construction
3493198092Srdivacky  // and not what user specified in the Initializers list.
3494206084Srdivacky  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3495206084Srdivacky  if (!ClassDecl)
3496206084Srdivacky    return true;
3497206084Srdivacky
3498199482Srdivacky  bool HadError = false;
3499198092Srdivacky
3500249423Sdim  for (unsigned i = 0; i < Initializers.size(); i++) {
3501218893Sdim    CXXCtorInitializer *Member = Initializers[i];
3502263508Sdim
3503206084Srdivacky    if (Member->isBaseInitializer())
3504208600Srdivacky      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3505206084Srdivacky    else
3506218893Sdim      Info.AllBaseFields[Member->getAnyMember()] = Member;
3507198092Srdivacky  }
3508198092Srdivacky
3509207619Srdivacky  // Keep track of the direct virtual bases.
3510207619Srdivacky  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3511207619Srdivacky  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3512207619Srdivacky       E = ClassDecl->bases_end(); I != E; ++I) {
3513207619Srdivacky    if (I->isVirtual())
3514207619Srdivacky      DirectVBases.insert(I);
3515207619Srdivacky  }
3516198092Srdivacky
3517206084Srdivacky  // Push virtual bases before others.
3518206084Srdivacky  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3519206084Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3520206084Srdivacky
3521218893Sdim    if (CXXCtorInitializer *Value
3522208600Srdivacky        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3523263508Sdim      // [class.base.init]p7, per DR257:
3524263508Sdim      //   A mem-initializer where the mem-initializer-id names a virtual base
3525263508Sdim      //   class is ignored during execution of a constructor of any class that
3526263508Sdim      //   is not the most derived class.
3527263508Sdim      if (ClassDecl->isAbstract()) {
3528263508Sdim        // FIXME: Provide a fixit to remove the base specifier. This requires
3529263508Sdim        // tracking the location of the associated comma for a base specifier.
3530263508Sdim        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3531263508Sdim          << VBase->getType() << ClassDecl;
3532263508Sdim        DiagnoseAbstractType(ClassDecl);
3533263508Sdim      }
3534263508Sdim
3535208600Srdivacky      Info.AllToInit.push_back(Value);
3536263508Sdim    } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3537263508Sdim      // [class.base.init]p8, per DR257:
3538263508Sdim      //   If a given [...] base class is not named by a mem-initializer-id
3539263508Sdim      //   [...] and the entity is not a virtual base class of an abstract
3540263508Sdim      //   class, then [...] the entity is default-initialized.
3541207619Srdivacky      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3542218893Sdim      CXXCtorInitializer *CXXBaseInit;
3543208600Srdivacky      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3544263508Sdim                                       VBase, IsInheritedVirtualBase,
3545207619Srdivacky                                       CXXBaseInit)) {
3546206084Srdivacky        HadError = true;
3547198092Srdivacky        continue;
3548206084Srdivacky      }
3549207619Srdivacky
3550208600Srdivacky      Info.AllToInit.push_back(CXXBaseInit);
3551198092Srdivacky    }
3552206084Srdivacky  }
3553198092Srdivacky
3554208600Srdivacky  // Non-virtual bases.
3555206084Srdivacky  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3556206084Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
3557206084Srdivacky    // Virtuals are in the virtual base list and already constructed.
3558206084Srdivacky    if (Base->isVirtual())
3559206084Srdivacky      continue;
3560206084Srdivacky
3561218893Sdim    if (CXXCtorInitializer *Value
3562208600Srdivacky          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3563208600Srdivacky      Info.AllToInit.push_back(Value);
3564206084Srdivacky    } else if (!AnyErrors) {
3565218893Sdim      CXXCtorInitializer *CXXBaseInit;
3566208600Srdivacky      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3567207619Srdivacky                                       Base, /*IsInheritedVirtualBase=*/false,
3568207619Srdivacky                                       CXXBaseInit)) {
3569206084Srdivacky        HadError = true;
3570198092Srdivacky        continue;
3571198092Srdivacky      }
3572206084Srdivacky
3573208600Srdivacky      Info.AllToInit.push_back(CXXBaseInit);
3574198092Srdivacky    }
3575198092Srdivacky  }
3576198092Srdivacky
3577208600Srdivacky  // Fields.
3578226633Sdim  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3579226633Sdim                               MemEnd = ClassDecl->decls_end();
3580226633Sdim       Mem != MemEnd; ++Mem) {
3581226633Sdim    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3582226633Sdim      // C++ [class.bit]p2:
3583226633Sdim      //   A declaration for a bit-field that omits the identifier declares an
3584226633Sdim      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3585226633Sdim      //   initialized.
3586226633Sdim      if (F->isUnnamedBitfield())
3587226633Sdim        continue;
3588234353Sdim
3589226633Sdim      // If we're not generating the implicit copy/move constructor, then we'll
3590226633Sdim      // handle anonymous struct/union fields based on their individual
3591226633Sdim      // indirect fields.
3592249423Sdim      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3593226633Sdim        continue;
3594226633Sdim
3595226633Sdim      if (CollectFieldInitializer(*this, Info, F))
3596226633Sdim        HadError = true;
3597198092Srdivacky      continue;
3598198092Srdivacky    }
3599226633Sdim
3600226633Sdim    // Beyond this point, we only consider default initialization.
3601249423Sdim    if (Info.isImplicitCopyOrMove())
3602226633Sdim      continue;
3603226633Sdim
3604226633Sdim    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3605226633Sdim      if (F->getType()->isIncompleteArrayType()) {
3606226633Sdim        assert(ClassDecl->hasFlexibleArrayMember() &&
3607226633Sdim               "Incomplete array type is not valid");
3608226633Sdim        continue;
3609226633Sdim      }
3610226633Sdim
3611226633Sdim      // Initialize each field of an anonymous struct individually.
3612226633Sdim      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3613226633Sdim        HadError = true;
3614226633Sdim
3615226633Sdim      continue;
3616226633Sdim    }
3617198092Srdivacky  }
3618198092Srdivacky
3619249423Sdim  unsigned NumInitializers = Info.AllToInit.size();
3620198092Srdivacky  if (NumInitializers > 0) {
3621218893Sdim    Constructor->setNumCtorInitializers(NumInitializers);
3622218893Sdim    CXXCtorInitializer **baseOrMemberInitializers =
3623218893Sdim      new (Context) CXXCtorInitializer*[NumInitializers];
3624208600Srdivacky    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3625218893Sdim           NumInitializers * sizeof(CXXCtorInitializer*));
3626218893Sdim    Constructor->setCtorInitializers(baseOrMemberInitializers);
3627205219Srdivacky
3628205408Srdivacky    // Constructors implicitly reference the base and member
3629205408Srdivacky    // destructors.
3630205408Srdivacky    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3631205408Srdivacky                                           Constructor->getParent());
3632198092Srdivacky  }
3633198092Srdivacky
3634199482Srdivacky  return HadError;
3635198092Srdivacky}
3636198092Srdivacky
3637249423Sdimstatic void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3638198092Srdivacky  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3639249423Sdim    const RecordDecl *RD = RT->getDecl();
3640249423Sdim    if (RD->isAnonymousStructOrUnion()) {
3641249423Sdim      for (RecordDecl::field_iterator Field = RD->field_begin(),
3642249423Sdim          E = RD->field_end(); Field != E; ++Field)
3643249423Sdim        PopulateKeysForFields(*Field, IdealInits);
3644249423Sdim      return;
3645249423Sdim    }
3646198092Srdivacky  }
3647249423Sdim  IdealInits.push_back(Field);
3648198092Srdivacky}
3649198092Srdivacky
3650263508Sdimstatic const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3651263508Sdim  return Context.getCanonicalType(BaseType).getTypePtr();
3652198092Srdivacky}
3653198092Srdivacky
3654263508Sdimstatic const void *GetKeyForMember(ASTContext &Context,
3655263508Sdim                                   CXXCtorInitializer *Member) {
3656218893Sdim  if (!Member->isAnyMemberInitializer())
3657206084Srdivacky    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3658206084Srdivacky
3659249423Sdim  return Member->getAnyMember();
3660198092Srdivacky}
3661198092Srdivacky
3662249423Sdimstatic void DiagnoseBaseOrMemInitializerOrder(
3663249423Sdim    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3664249423Sdim    ArrayRef<CXXCtorInitializer *> Inits) {
3665207619Srdivacky  if (Constructor->getDeclContext()->isDependentContext())
3666198092Srdivacky    return;
3667198092Srdivacky
3668218893Sdim  // Don't check initializers order unless the warning is enabled at the
3669218893Sdim  // location of at least one initializer.
3670218893Sdim  bool ShouldCheckOrder = false;
3671249423Sdim  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3672218893Sdim    CXXCtorInitializer *Init = Inits[InitIndex];
3673218893Sdim    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3674218893Sdim                                         Init->getSourceLocation())
3675226633Sdim          != DiagnosticsEngine::Ignored) {
3676218893Sdim      ShouldCheckOrder = true;
3677218893Sdim      break;
3678218893Sdim    }
3679218893Sdim  }
3680218893Sdim  if (!ShouldCheckOrder)
3681198092Srdivacky    return;
3682206084Srdivacky
3683207619Srdivacky  // Build the list of bases and members in the order that they'll
3684207619Srdivacky  // actually be initialized.  The explicit initializers should be in
3685207619Srdivacky  // this same order but may be missing things.
3686226633Sdim  SmallVector<const void*, 32> IdealInitKeys;
3687198092Srdivacky
3688206084Srdivacky  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3689206084Srdivacky
3690207619Srdivacky  // 1. Virtual bases.
3691206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator VBase =
3692198092Srdivacky       ClassDecl->vbases_begin(),
3693198092Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3694207619Srdivacky    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3695198092Srdivacky
3696207619Srdivacky  // 2. Non-virtual bases.
3697206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3698198092Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
3699198092Srdivacky    if (Base->isVirtual())
3700198092Srdivacky      continue;
3701207619Srdivacky    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3702198092Srdivacky  }
3703198092Srdivacky
3704207619Srdivacky  // 3. Direct fields.
3705198092Srdivacky  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3706226633Sdim       E = ClassDecl->field_end(); Field != E; ++Field) {
3707226633Sdim    if (Field->isUnnamedBitfield())
3708226633Sdim      continue;
3709226633Sdim
3710249423Sdim    PopulateKeysForFields(*Field, IdealInitKeys);
3711226633Sdim  }
3712226633Sdim
3713207619Srdivacky  unsigned NumIdealInits = IdealInitKeys.size();
3714207619Srdivacky  unsigned IdealIndex = 0;
3715198092Srdivacky
3716218893Sdim  CXXCtorInitializer *PrevInit = 0;
3717249423Sdim  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3718218893Sdim    CXXCtorInitializer *Init = Inits[InitIndex];
3719263508Sdim    const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3720207619Srdivacky
3721207619Srdivacky    // Scan forward to try to find this initializer in the idealized
3722207619Srdivacky    // initializers list.
3723207619Srdivacky    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3724207619Srdivacky      if (InitKey == IdealInitKeys[IdealIndex])
3725198092Srdivacky        break;
3726207619Srdivacky
3727207619Srdivacky    // If we didn't find this initializer, it must be because we
3728207619Srdivacky    // scanned past it on a previous iteration.  That can only
3729207619Srdivacky    // happen if we're out of order;  emit a warning.
3730208600Srdivacky    if (IdealIndex == NumIdealInits && PrevInit) {
3731207619Srdivacky      Sema::SemaDiagnosticBuilder D =
3732207619Srdivacky        SemaRef.Diag(PrevInit->getSourceLocation(),
3733207619Srdivacky                     diag::warn_initializer_out_of_order);
3734207619Srdivacky
3735218893Sdim      if (PrevInit->isAnyMemberInitializer())
3736218893Sdim        D << 0 << PrevInit->getAnyMember()->getDeclName();
3737207619Srdivacky      else
3738234353Sdim        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3739207619Srdivacky
3740218893Sdim      if (Init->isAnyMemberInitializer())
3741218893Sdim        D << 0 << Init->getAnyMember()->getDeclName();
3742207619Srdivacky      else
3743234353Sdim        D << 1 << Init->getTypeSourceInfo()->getType();
3744207619Srdivacky
3745207619Srdivacky      // Move back to the initializer's location in the ideal list.
3746207619Srdivacky      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3747207619Srdivacky        if (InitKey == IdealInitKeys[IdealIndex])
3748198092Srdivacky          break;
3749207619Srdivacky
3750207619Srdivacky      assert(IdealIndex != NumIdealInits &&
3751207619Srdivacky             "initializer not found in initializer list");
3752198092Srdivacky    }
3753207619Srdivacky
3754207619Srdivacky    PrevInit = Init;
3755198092Srdivacky  }
3756198092Srdivacky}
3757198092Srdivacky
3758207619Srdivackynamespace {
3759207619Srdivackybool CheckRedundantInit(Sema &S,
3760218893Sdim                        CXXCtorInitializer *Init,
3761218893Sdim                        CXXCtorInitializer *&PrevInit) {
3762207619Srdivacky  if (!PrevInit) {
3763207619Srdivacky    PrevInit = Init;
3764207619Srdivacky    return false;
3765207619Srdivacky  }
3766207619Srdivacky
3767249423Sdim  if (FieldDecl *Field = Init->getAnyMember())
3768207619Srdivacky    S.Diag(Init->getSourceLocation(),
3769207619Srdivacky           diag::err_multiple_mem_initialization)
3770207619Srdivacky      << Field->getDeclName()
3771207619Srdivacky      << Init->getSourceRange();
3772207619Srdivacky  else {
3773218893Sdim    const Type *BaseClass = Init->getBaseClass();
3774207619Srdivacky    assert(BaseClass && "neither field nor base");
3775207619Srdivacky    S.Diag(Init->getSourceLocation(),
3776207619Srdivacky           diag::err_multiple_base_initialization)
3777207619Srdivacky      << QualType(BaseClass, 0)
3778207619Srdivacky      << Init->getSourceRange();
3779207619Srdivacky  }
3780207619Srdivacky  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3781207619Srdivacky    << 0 << PrevInit->getSourceRange();
3782207619Srdivacky
3783207619Srdivacky  return true;
3784207619Srdivacky}
3785207619Srdivacky
3786218893Sdimtypedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3787207619Srdivackytypedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3788207619Srdivacky
3789207619Srdivackybool CheckRedundantUnionInit(Sema &S,
3790218893Sdim                             CXXCtorInitializer *Init,
3791207619Srdivacky                             RedundantUnionMap &Unions) {
3792218893Sdim  FieldDecl *Field = Init->getAnyMember();
3793207619Srdivacky  RecordDecl *Parent = Field->getParent();
3794234353Sdim  NamedDecl *Child = Field;
3795207619Srdivacky
3796234353Sdim  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3797207619Srdivacky    if (Parent->isUnion()) {
3798207619Srdivacky      UnionEntry &En = Unions[Parent];
3799207619Srdivacky      if (En.first && En.first != Child) {
3800207619Srdivacky        S.Diag(Init->getSourceLocation(),
3801207619Srdivacky               diag::err_multiple_mem_union_initialization)
3802207619Srdivacky          << Field->getDeclName()
3803207619Srdivacky          << Init->getSourceRange();
3804207619Srdivacky        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3805207619Srdivacky          << 0 << En.second->getSourceRange();
3806207619Srdivacky        return true;
3807234353Sdim      }
3808234353Sdim      if (!En.first) {
3809207619Srdivacky        En.first = Child;
3810207619Srdivacky        En.second = Init;
3811207619Srdivacky      }
3812234353Sdim      if (!Parent->isAnonymousStructOrUnion())
3813234353Sdim        return false;
3814207619Srdivacky    }
3815207619Srdivacky
3816207619Srdivacky    Child = Parent;
3817207619Srdivacky    Parent = cast<RecordDecl>(Parent->getDeclContext());
3818234353Sdim  }
3819207619Srdivacky
3820207619Srdivacky  return false;
3821207619Srdivacky}
3822207619Srdivacky}
3823207619Srdivacky
3824206084Srdivacky/// ActOnMemInitializers - Handle the member initializers for a constructor.
3825212904Sdimvoid Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3826206084Srdivacky                                SourceLocation ColonLoc,
3827249423Sdim                                ArrayRef<CXXCtorInitializer*> MemInits,
3828206084Srdivacky                                bool AnyErrors) {
3829206084Srdivacky  if (!ConstructorDecl)
3830206084Srdivacky    return;
3831206084Srdivacky
3832206084Srdivacky  AdjustDeclIfTemplate(ConstructorDecl);
3833206084Srdivacky
3834206084Srdivacky  CXXConstructorDecl *Constructor
3835212904Sdim    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3836206084Srdivacky
3837206084Srdivacky  if (!Constructor) {
3838206084Srdivacky    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3839206084Srdivacky    return;
3840206084Srdivacky  }
3841206084Srdivacky
3842207619Srdivacky  // Mapping for the duplicate initializers check.
3843207619Srdivacky  // For member initializers, this is keyed with a FieldDecl*.
3844207619Srdivacky  // For base initializers, this is keyed with a Type*.
3845263508Sdim  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3846207619Srdivacky
3847207619Srdivacky  // Mapping for the inconsistent anonymous-union initializers check.
3848207619Srdivacky  RedundantUnionMap MemberUnions;
3849207619Srdivacky
3850206084Srdivacky  bool HadError = false;
3851249423Sdim  for (unsigned i = 0; i < MemInits.size(); i++) {
3852218893Sdim    CXXCtorInitializer *Init = MemInits[i];
3853206084Srdivacky
3854208600Srdivacky    // Set the source order index.
3855208600Srdivacky    Init->setSourceOrder(i);
3856208600Srdivacky
3857218893Sdim    if (Init->isAnyMemberInitializer()) {
3858218893Sdim      FieldDecl *Field = Init->getAnyMember();
3859207619Srdivacky      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3860207619Srdivacky          CheckRedundantUnionInit(*this, Init, MemberUnions))
3861207619Srdivacky        HadError = true;
3862221345Sdim    } else if (Init->isBaseInitializer()) {
3863263508Sdim      const void *Key =
3864263508Sdim          GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3865207619Srdivacky      if (CheckRedundantInit(*this, Init, Members[Key]))
3866207619Srdivacky        HadError = true;
3867221345Sdim    } else {
3868221345Sdim      assert(Init->isDelegatingInitializer());
3869221345Sdim      // This must be the only initializer
3870249423Sdim      if (MemInits.size() != 1) {
3871243830Sdim        Diag(Init->getSourceLocation(),
3872221345Sdim             diag::err_delegating_initializer_alone)
3873243830Sdim          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3874221345Sdim        // We will treat this as being the only initializer.
3875221345Sdim      }
3876223017Sdim      SetDelegatingInitializer(Constructor, MemInits[i]);
3877221345Sdim      // Return immediately as the initializer is set.
3878221345Sdim      return;
3879206084Srdivacky    }
3880206084Srdivacky  }
3881206084Srdivacky
3882206084Srdivacky  if (HadError)
3883206084Srdivacky    return;
3884206084Srdivacky
3885249423Sdim  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3886206084Srdivacky
3887249423Sdim  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3888263508Sdim
3889263508Sdim  DiagnoseUninitializedFields(*this, Constructor);
3890206084Srdivacky}
3891206084Srdivacky
3892198092Srdivackyvoid
3893205408SrdivackySema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3894205408Srdivacky                                             CXXRecordDecl *ClassDecl) {
3895226633Sdim  // Ignore dependent contexts. Also ignore unions, since their members never
3896226633Sdim  // have destructors implicitly called.
3897226633Sdim  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3898199482Srdivacky    return;
3899205219Srdivacky
3900205219Srdivacky  // FIXME: all the access-control diagnostics are positioned on the
3901205219Srdivacky  // field/base declaration.  That's probably good; that said, the
3902205219Srdivacky  // user might reasonably want to know why the destructor is being
3903205219Srdivacky  // emitted, and we currently don't say.
3904199482Srdivacky
3905199482Srdivacky  // Non-static data members.
3906199482Srdivacky  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3907199482Srdivacky       E = ClassDecl->field_end(); I != E; ++I) {
3908199482Srdivacky    FieldDecl *Field = *I;
3909208600Srdivacky    if (Field->isInvalidDecl())
3910208600Srdivacky      continue;
3911234353Sdim
3912234353Sdim    // Don't destroy incomplete or zero-length arrays.
3913234353Sdim    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3914234353Sdim      continue;
3915234353Sdim
3916199482Srdivacky    QualType FieldType = Context.getBaseElementType(Field->getType());
3917199482Srdivacky
3918199482Srdivacky    const RecordType* RT = FieldType->getAs<RecordType>();
3919199482Srdivacky    if (!RT)
3920195341Sed      continue;
3921199482Srdivacky
3922199482Srdivacky    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3923221345Sdim    if (FieldClassDecl->isInvalidDecl())
3924221345Sdim      continue;
3925234353Sdim    if (FieldClassDecl->hasIrrelevantDestructor())
3926198092Srdivacky      continue;
3927234353Sdim    // The destructor for an implicit anonymous union member is never invoked.
3928234353Sdim    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3929234353Sdim      continue;
3930198092Srdivacky
3931210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3932221345Sdim    assert(Dtor && "No dtor found for FieldClassDecl!");
3933205219Srdivacky    CheckDestructorAccess(Field->getLocation(), Dtor,
3934206084Srdivacky                          PDiag(diag::err_access_dtor_field)
3935205219Srdivacky                            << Field->getDeclName()
3936205219Srdivacky                            << FieldType);
3937205219Srdivacky
3938263508Sdim    MarkFunctionReferenced(Location, Dtor);
3939234353Sdim    DiagnoseUseOfDecl(Dtor, Location);
3940198092Srdivacky  }
3941199482Srdivacky
3942205219Srdivacky  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3943205219Srdivacky
3944199482Srdivacky  // Bases.
3945199482Srdivacky  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3946198092Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
3947205219Srdivacky    // Bases are always records in a well-formed non-dependent class.
3948205219Srdivacky    const RecordType *RT = Base->getType()->getAs<RecordType>();
3949205219Srdivacky
3950205219Srdivacky    // Remember direct virtual bases.
3951198092Srdivacky    if (Base->isVirtual())
3952205219Srdivacky      DirectVirtualBases.insert(RT);
3953199482Srdivacky
3954221345Sdim    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3955221345Sdim    // If our base class is invalid, we probably can't get its dtor anyway.
3956221345Sdim    if (BaseClassDecl->isInvalidDecl())
3957221345Sdim      continue;
3958234353Sdim    if (BaseClassDecl->hasIrrelevantDestructor())
3959198092Srdivacky      continue;
3960205219Srdivacky
3961210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3962221345Sdim    assert(Dtor && "No dtor found for BaseClassDecl!");
3963205219Srdivacky
3964205219Srdivacky    // FIXME: caret should be on the start of the class name
3965234353Sdim    CheckDestructorAccess(Base->getLocStart(), Dtor,
3966206084Srdivacky                          PDiag(diag::err_access_dtor_base)
3967205219Srdivacky                            << Base->getType()
3968234353Sdim                            << Base->getSourceRange(),
3969234353Sdim                          Context.getTypeDeclType(ClassDecl));
3970199482Srdivacky
3971263508Sdim    MarkFunctionReferenced(Location, Dtor);
3972234353Sdim    DiagnoseUseOfDecl(Dtor, Location);
3973199482Srdivacky  }
3974199482Srdivacky
3975199482Srdivacky  // Virtual bases.
3976199482Srdivacky  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3977199482Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3978205219Srdivacky
3979205219Srdivacky    // Bases are always records in a well-formed non-dependent class.
3980234353Sdim    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3981205219Srdivacky
3982205219Srdivacky    // Ignore direct virtual bases.
3983205219Srdivacky    if (DirectVirtualBases.count(RT))
3984205219Srdivacky      continue;
3985205219Srdivacky
3986221345Sdim    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3987221345Sdim    // If our base class is invalid, we probably can't get its dtor anyway.
3988221345Sdim    if (BaseClassDecl->isInvalidDecl())
3989221345Sdim      continue;
3990234353Sdim    if (BaseClassDecl->hasIrrelevantDestructor())
3991198092Srdivacky      continue;
3992205219Srdivacky
3993210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3994221345Sdim    assert(Dtor && "No dtor found for BaseClassDecl!");
3995263508Sdim    if (CheckDestructorAccess(
3996263508Sdim            ClassDecl->getLocation(), Dtor,
3997263508Sdim            PDiag(diag::err_access_dtor_vbase)
3998263508Sdim                << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3999263508Sdim            Context.getTypeDeclType(ClassDecl)) ==
4000263508Sdim        AR_accessible) {
4001263508Sdim      CheckDerivedToBaseConversion(
4002263508Sdim          Context.getTypeDeclType(ClassDecl), VBase->getType(),
4003263508Sdim          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4004263508Sdim          SourceRange(), DeclarationName(), 0);
4005263508Sdim    }
4006205219Srdivacky
4007263508Sdim    MarkFunctionReferenced(Location, Dtor);
4008234353Sdim    DiagnoseUseOfDecl(Dtor, Location);
4009198092Srdivacky  }
4010193326Sed}
4011193326Sed
4012212904Sdimvoid Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4013198092Srdivacky  if (!CDtorDecl)
4014198092Srdivacky    return;
4015198092Srdivacky
4016198092Srdivacky  if (CXXConstructorDecl *Constructor
4017263508Sdim      = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4018249423Sdim    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4019263508Sdim    DiagnoseUninitializedFields(*this, Constructor);
4020263508Sdim  }
4021198092Srdivacky}
4022198092Srdivacky
4023198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4024212904Sdim                                  unsigned DiagID, AbstractDiagSelID SelID) {
4025239462Sdim  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4026239462Sdim    unsigned DiagID;
4027239462Sdim    AbstractDiagSelID SelID;
4028239462Sdim
4029239462Sdim  public:
4030239462Sdim    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4031239462Sdim      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4032263508Sdim
4033263508Sdim    void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
4034239462Sdim      if (Suppressed) return;
4035239462Sdim      if (SelID == -1)
4036239462Sdim        S.Diag(Loc, DiagID) << T;
4037239462Sdim      else
4038239462Sdim        S.Diag(Loc, DiagID) << SelID << T;
4039239462Sdim    }
4040239462Sdim  } Diagnoser(DiagID, SelID);
4041239462Sdim
4042239462Sdim  return RequireNonAbstractType(Loc, T, Diagnoser);
4043198092Srdivacky}
4044198092Srdivacky
4045198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4046239462Sdim                                  TypeDiagnoser &Diagnoser) {
4047234353Sdim  if (!getLangOpts().CPlusPlus)
4048193326Sed    return false;
4049198092Srdivacky
4050193326Sed  if (const ArrayType *AT = Context.getAsArrayType(T))
4051239462Sdim    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4052198092Srdivacky
4053198092Srdivacky  if (const PointerType *PT = T->getAs<PointerType>()) {
4054193326Sed    // Find the innermost pointer type.
4055198092Srdivacky    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4056193326Sed      PT = T;
4057198092Srdivacky
4058193326Sed    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4059239462Sdim      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4060193326Sed  }
4061198092Srdivacky
4062198092Srdivacky  const RecordType *RT = T->getAs<RecordType>();
4063193326Sed  if (!RT)
4064193326Sed    return false;
4065198092Srdivacky
4066203955Srdivacky  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4067193326Sed
4068212904Sdim  // We can't answer whether something is abstract until it has a
4069212904Sdim  // definition.  If it's currently being defined, we'll walk back
4070212904Sdim  // over all the declarations when we have a full definition.
4071212904Sdim  const CXXRecordDecl *Def = RD->getDefinition();
4072212904Sdim  if (!Def || Def->isBeingDefined())
4073193326Sed    return false;
4074198092Srdivacky
4075193326Sed  if (!RD->isAbstract())
4076193326Sed    return false;
4077198092Srdivacky
4078239462Sdim  Diagnoser.diagnose(*this, Loc, T);
4079212904Sdim  DiagnoseAbstractType(RD);
4080198092Srdivacky
4081212904Sdim  return true;
4082212904Sdim}
4083212904Sdim
4084212904Sdimvoid Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4085212904Sdim  // Check if we've already emitted the list of pure virtual functions
4086212904Sdim  // for this class.
4087193326Sed  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4088212904Sdim    return;
4089198092Srdivacky
4090263508Sdim  // If the diagnostic is suppressed, don't emit the notes. We're only
4091263508Sdim  // going to emit them once, so try to attach them to a diagnostic we're
4092263508Sdim  // actually going to show.
4093263508Sdim  if (Diags.isLastDiagnosticIgnored())
4094263508Sdim    return;
4095263508Sdim
4096206084Srdivacky  CXXFinalOverriderMap FinalOverriders;
4097206084Srdivacky  RD->getFinalOverriders(FinalOverriders);
4098198092Srdivacky
4099210299Sed  // Keep a set of seen pure methods so we won't diagnose the same method
4100210299Sed  // more than once.
4101210299Sed  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4102210299Sed
4103206084Srdivacky  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4104206084Srdivacky                                   MEnd = FinalOverriders.end();
4105206084Srdivacky       M != MEnd;
4106206084Srdivacky       ++M) {
4107206084Srdivacky    for (OverridingMethods::iterator SO = M->second.begin(),
4108206084Srdivacky                                  SOEnd = M->second.end();
4109206084Srdivacky         SO != SOEnd; ++SO) {
4110206084Srdivacky      // C++ [class.abstract]p4:
4111206084Srdivacky      //   A class is abstract if it contains or inherits at least one
4112206084Srdivacky      //   pure virtual function for which the final overrider is pure
4113206084Srdivacky      //   virtual.
4114198092Srdivacky
4115206084Srdivacky      //
4116206084Srdivacky      if (SO->second.size() != 1)
4117206084Srdivacky        continue;
4118206084Srdivacky
4119206084Srdivacky      if (!SO->second.front().Method->isPure())
4120206084Srdivacky        continue;
4121206084Srdivacky
4122210299Sed      if (!SeenPureMethods.insert(SO->second.front().Method))
4123210299Sed        continue;
4124210299Sed
4125206084Srdivacky      Diag(SO->second.front().Method->getLocation(),
4126206084Srdivacky           diag::note_pure_virtual_function)
4127218893Sdim        << SO->second.front().Method->getDeclName() << RD->getDeclName();
4128206084Srdivacky    }
4129193326Sed  }
4130193326Sed
4131193326Sed  if (!PureVirtualClassDiagSet)
4132193326Sed    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4133193326Sed  PureVirtualClassDiagSet->insert(RD);
4134193326Sed}
4135193326Sed
4136193326Sednamespace {
4137212904Sdimstruct AbstractUsageInfo {
4138212904Sdim  Sema &S;
4139212904Sdim  CXXRecordDecl *Record;
4140212904Sdim  CanQualType AbstractType;
4141212904Sdim  bool Invalid;
4142198092Srdivacky
4143212904Sdim  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4144212904Sdim    : S(S), Record(Record),
4145212904Sdim      AbstractType(S.Context.getCanonicalType(
4146212904Sdim                   S.Context.getTypeDeclType(Record))),
4147212904Sdim      Invalid(false) {}
4148193326Sed
4149212904Sdim  void DiagnoseAbstractType() {
4150212904Sdim    if (Invalid) return;
4151212904Sdim    S.DiagnoseAbstractType(Record);
4152212904Sdim    Invalid = true;
4153212904Sdim  }
4154193326Sed
4155212904Sdim  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4156212904Sdim};
4157212904Sdim
4158212904Sdimstruct CheckAbstractUsage {
4159212904Sdim  AbstractUsageInfo &Info;
4160212904Sdim  const NamedDecl *Ctx;
4161212904Sdim
4162212904Sdim  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4163212904Sdim    : Info(Info), Ctx(Ctx) {}
4164212904Sdim
4165212904Sdim  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4166212904Sdim    switch (TL.getTypeLocClass()) {
4167212904Sdim#define ABSTRACT_TYPELOC(CLASS, PARENT)
4168212904Sdim#define TYPELOC(CLASS, PARENT) \
4169249423Sdim    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4170212904Sdim#include "clang/AST/TypeLocNodes.def"
4171193326Sed    }
4172212904Sdim  }
4173198092Srdivacky
4174212904Sdim  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4175212904Sdim    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4176212904Sdim    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4177219077Sdim      if (!TL.getArg(I))
4178219077Sdim        continue;
4179219077Sdim
4180212904Sdim      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4181212904Sdim      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4182193326Sed    }
4183212904Sdim  }
4184193326Sed
4185212904Sdim  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4186212904Sdim    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4187212904Sdim  }
4188198092Srdivacky
4189212904Sdim  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4190212904Sdim    // Visit the type parameters from a permissive context.
4191212904Sdim    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4192212904Sdim      TemplateArgumentLoc TAL = TL.getArgLoc(I);
4193212904Sdim      if (TAL.getArgument().getKind() == TemplateArgument::Type)
4194212904Sdim        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4195212904Sdim          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4196212904Sdim      // TODO: other template argument types?
4197212904Sdim    }
4198212904Sdim  }
4199193326Sed
4200212904Sdim  // Visit pointee types from a permissive context.
4201212904Sdim#define CheckPolymorphic(Type) \
4202212904Sdim  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4203212904Sdim    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4204212904Sdim  }
4205212904Sdim  CheckPolymorphic(PointerTypeLoc)
4206212904Sdim  CheckPolymorphic(ReferenceTypeLoc)
4207212904Sdim  CheckPolymorphic(MemberPointerTypeLoc)
4208212904Sdim  CheckPolymorphic(BlockPointerTypeLoc)
4209226633Sdim  CheckPolymorphic(AtomicTypeLoc)
4210193326Sed
4211212904Sdim  /// Handle all the types we haven't given a more specific
4212212904Sdim  /// implementation for above.
4213212904Sdim  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214212904Sdim    // Every other kind of type that we haven't called out already
4215212904Sdim    // that has an inner type is either (1) sugar or (2) contains that
4216212904Sdim    // inner type in some way as a subobject.
4217212904Sdim    if (TypeLoc Next = TL.getNextTypeLoc())
4218212904Sdim      return Visit(Next, Sel);
4219212904Sdim
4220212904Sdim    // If there's no inner type and we're in a permissive context,
4221212904Sdim    // don't diagnose.
4222212904Sdim    if (Sel == Sema::AbstractNone) return;
4223212904Sdim
4224212904Sdim    // Check whether the type matches the abstract type.
4225212904Sdim    QualType T = TL.getType();
4226212904Sdim    if (T->isArrayType()) {
4227212904Sdim      Sel = Sema::AbstractArrayType;
4228212904Sdim      T = Info.S.Context.getBaseElementType(T);
4229193326Sed    }
4230212904Sdim    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4231212904Sdim    if (CT != Info.AbstractType) return;
4232198092Srdivacky
4233212904Sdim    // It matched; do some magic.
4234212904Sdim    if (Sel == Sema::AbstractArrayType) {
4235212904Sdim      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4236212904Sdim        << T << TL.getSourceRange();
4237212904Sdim    } else {
4238212904Sdim      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4239212904Sdim        << Sel << T << TL.getSourceRange();
4240212904Sdim    }
4241212904Sdim    Info.DiagnoseAbstractType();
4242212904Sdim  }
4243212904Sdim};
4244198092Srdivacky
4245212904Sdimvoid AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4246212904Sdim                                  Sema::AbstractDiagSelID Sel) {
4247212904Sdim  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4248212904Sdim}
4249212904Sdim
4250212904Sdim}
4251212904Sdim
4252212904Sdim/// Check for invalid uses of an abstract type in a method declaration.
4253212904Sdimstatic void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4254212904Sdim                                    CXXMethodDecl *MD) {
4255212904Sdim  // No need to do the check on definitions, which require that
4256212904Sdim  // the return/param types be complete.
4257223017Sdim  if (MD->doesThisDeclarationHaveABody())
4258212904Sdim    return;
4259212904Sdim
4260212904Sdim  // For safety's sake, just ignore it if we don't have type source
4261212904Sdim  // information.  This should never happen for non-implicit methods,
4262212904Sdim  // but...
4263212904Sdim  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4264212904Sdim    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4265212904Sdim}
4266212904Sdim
4267212904Sdim/// Check for invalid uses of an abstract type within a class definition.
4268212904Sdimstatic void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4269212904Sdim                                    CXXRecordDecl *RD) {
4270212904Sdim  for (CXXRecordDecl::decl_iterator
4271212904Sdim         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4272212904Sdim    Decl *D = *I;
4273212904Sdim    if (D->isImplicit()) continue;
4274212904Sdim
4275212904Sdim    // Methods and method templates.
4276212904Sdim    if (isa<CXXMethodDecl>(D)) {
4277212904Sdim      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4278212904Sdim    } else if (isa<FunctionTemplateDecl>(D)) {
4279212904Sdim      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4280212904Sdim      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4281212904Sdim
4282212904Sdim    // Fields and static variables.
4283212904Sdim    } else if (isa<FieldDecl>(D)) {
4284212904Sdim      FieldDecl *FD = cast<FieldDecl>(D);
4285212904Sdim      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4286212904Sdim        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4287212904Sdim    } else if (isa<VarDecl>(D)) {
4288212904Sdim      VarDecl *VD = cast<VarDecl>(D);
4289212904Sdim      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4290212904Sdim        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4291212904Sdim
4292212904Sdim    // Nested classes and class templates.
4293212904Sdim    } else if (isa<CXXRecordDecl>(D)) {
4294212904Sdim      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4295212904Sdim    } else if (isa<ClassTemplateDecl>(D)) {
4296212904Sdim      CheckAbstractClassUsage(Info,
4297212904Sdim                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4298193326Sed    }
4299212904Sdim  }
4300193326Sed}
4301193326Sed
4302200583Srdivacky/// \brief Perform semantic checks on a class definition that has been
4303200583Srdivacky/// completing, introducing implicitly-declared members, checking for
4304200583Srdivacky/// abstract types, etc.
4305210299Sedvoid Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4306218893Sdim  if (!Record)
4307200583Srdivacky    return;
4308200583Srdivacky
4309212904Sdim  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4310212904Sdim    AbstractUsageInfo Info(*this, Record);
4311212904Sdim    CheckAbstractClassUsage(Info, Record);
4312212904Sdim  }
4313207619Srdivacky
4314207619Srdivacky  // If this is not an aggregate type and has no user-declared constructor,
4315207619Srdivacky  // complain about any non-static data members of reference or const scalar
4316207619Srdivacky  // type, since they will never get initializers.
4317207619Srdivacky  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4318234353Sdim      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4319234353Sdim      !Record->isLambda()) {
4320207619Srdivacky    bool Complained = false;
4321207619Srdivacky    for (RecordDecl::field_iterator F = Record->field_begin(),
4322207619Srdivacky                                 FEnd = Record->field_end();
4323207619Srdivacky         F != FEnd; ++F) {
4324226633Sdim      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4325223017Sdim        continue;
4326223017Sdim
4327207619Srdivacky      if (F->getType()->isReferenceType() ||
4328207619Srdivacky          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4329207619Srdivacky        if (!Complained) {
4330207619Srdivacky          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4331207619Srdivacky            << Record->getTagKind() << Record;
4332207619Srdivacky          Complained = true;
4333207619Srdivacky        }
4334207619Srdivacky
4335207619Srdivacky        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4336207619Srdivacky          << F->getType()->isReferenceType()
4337207619Srdivacky          << F->getDeclName();
4338207619Srdivacky      }
4339207619Srdivacky    }
4340207619Srdivacky  }
4341208600Srdivacky
4342218893Sdim  if (Record->isDynamicClass() && !Record->isDependentType())
4343208600Srdivacky    DynamicClasses.push_back(Record);
4344218893Sdim
4345218893Sdim  if (Record->getIdentifier()) {
4346218893Sdim    // C++ [class.mem]p13:
4347218893Sdim    //   If T is the name of a class, then each of the following shall have a
4348218893Sdim    //   name different from T:
4349218893Sdim    //     - every member of every anonymous union that is a member of class T.
4350218893Sdim    //
4351218893Sdim    // C++ [class.mem]p14:
4352218893Sdim    //   In addition, if class T has a user-declared constructor (12.1), every
4353218893Sdim    //   non-static data member of class T shall have a name different from T.
4354249423Sdim    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4355249423Sdim    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4356249423Sdim         ++I) {
4357249423Sdim      NamedDecl *D = *I;
4358218893Sdim      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4359218893Sdim          isa<IndirectFieldDecl>(D)) {
4360218893Sdim        Diag(D->getLocation(), diag::err_member_name_of_class)
4361218893Sdim          << D->getDeclName();
4362218893Sdim        break;
4363218893Sdim      }
4364218893Sdim    }
4365218893Sdim  }
4366218893Sdim
4367218893Sdim  // Warn if the class has virtual methods but non-virtual public destructor.
4368218893Sdim  if (Record->isPolymorphic() && !Record->isDependentType()) {
4369218893Sdim    CXXDestructorDecl *dtor = Record->getDestructor();
4370218893Sdim    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4371218893Sdim      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4372218893Sdim           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4373218893Sdim  }
4374218893Sdim
4375263508Sdim  if (Record->isAbstract()) {
4376263508Sdim    if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4377263508Sdim      Diag(Record->getLocation(), diag::warn_abstract_final_class)
4378263508Sdim        << FA->isSpelledAsSealed();
4379263508Sdim      DiagnoseAbstractType(Record);
4380263508Sdim    }
4381243830Sdim  }
4382243830Sdim
4383218893Sdim  if (!Record->isDependentType()) {
4384218893Sdim    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4385218893Sdim                                     MEnd = Record->method_end();
4386218893Sdim         M != MEnd; ++M) {
4387249423Sdim      // See if a method overloads virtual methods in a base
4388249423Sdim      // class without overriding any.
4389239462Sdim      if (!M->isStatic())
4390263508Sdim        DiagnoseHiddenVirtualMethods(*M);
4391249423Sdim
4392249423Sdim      // Check whether the explicitly-defaulted special members are valid.
4393249423Sdim      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4394249423Sdim        CheckExplicitlyDefaultedSpecialMember(*M);
4395249423Sdim
4396249423Sdim      // For an explicitly defaulted or deleted special member, we defer
4397249423Sdim      // determining triviality until the class is complete. That time is now!
4398249423Sdim      if (!M->isImplicit() && !M->isUserProvided()) {
4399249423Sdim        CXXSpecialMember CSM = getSpecialMember(*M);
4400249423Sdim        if (CSM != CXXInvalid) {
4401249423Sdim          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4402249423Sdim
4403249423Sdim          // Inform the class that we've finished declaring this member.
4404249423Sdim          Record->finishedDefaultedOrDeletedMember(*M);
4405249423Sdim        }
4406249423Sdim      }
4407218893Sdim    }
4408218893Sdim  }
4409218893Sdim
4410249423Sdim  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4411226633Sdim  // function that is not a constructor declares that member function to be
4412226633Sdim  // const. [...] The class of which that function is a member shall be
4413226633Sdim  // a literal type.
4414226633Sdim  //
4415226633Sdim  // If the class has virtual bases, any constexpr members will already have
4416226633Sdim  // been diagnosed by the checks performed on the member declaration, so
4417226633Sdim  // suppress this (less useful) diagnostic.
4418249423Sdim  //
4419249423Sdim  // We delay this until we know whether an explicitly-defaulted (or deleted)
4420249423Sdim  // destructor for the class is trivial.
4421249423Sdim  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4422226633Sdim      !Record->isLiteral() && !Record->getNumVBases()) {
4423226633Sdim    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4424226633Sdim                                     MEnd = Record->method_end();
4425226633Sdim         M != MEnd; ++M) {
4426234353Sdim      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4427226633Sdim        switch (Record->getTemplateSpecializationKind()) {
4428226633Sdim        case TSK_ImplicitInstantiation:
4429226633Sdim        case TSK_ExplicitInstantiationDeclaration:
4430226633Sdim        case TSK_ExplicitInstantiationDefinition:
4431226633Sdim          // If a template instantiates to a non-literal type, but its members
4432226633Sdim          // instantiate to constexpr functions, the template is technically
4433234353Sdim          // ill-formed, but we allow it for sanity.
4434226633Sdim          continue;
4435226633Sdim
4436226633Sdim        case TSK_Undeclared:
4437226633Sdim        case TSK_ExplicitSpecialization:
4438239462Sdim          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4439239462Sdim                             diag::err_constexpr_method_non_literal);
4440226633Sdim          break;
4441226633Sdim        }
4442226633Sdim
4443226633Sdim        // Only produce one error per class.
4444226633Sdim        break;
4445226633Sdim      }
4446226633Sdim    }
4447226633Sdim  }
4448226633Sdim
4449263508Sdim  // Check to see if we're trying to lay out a struct using the ms_struct
4450263508Sdim  // attribute that is dynamic.
4451263508Sdim  if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4452263508Sdim    Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4453263508Sdim    Record->dropAttr<MsStructAttr>();
4454263508Sdim  }
4455263508Sdim
4456249423Sdim  // Declare inheriting constructors. We do this eagerly here because:
4457249423Sdim  // - The standard requires an eager diagnostic for conflicting inheriting
4458218893Sdim  //   constructors from different classes.
4459218893Sdim  // - The lazy declaration of the other implicit constructors is so as to not
4460218893Sdim  //   waste space and performance on classes that are not meant to be
4461218893Sdim  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4462249423Sdim  //   have inheriting constructors.
4463249423Sdim  DeclareInheritingConstructors(Record);
4464200583Srdivacky}
4465200583Srdivacky
4466239462Sdim/// Is the special member function which would be selected to perform the
4467239462Sdim/// specified operation on the specified class type a constexpr constructor?
4468239462Sdimstatic bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4469239462Sdim                                     Sema::CXXSpecialMember CSM,
4470239462Sdim                                     bool ConstArg) {
4471239462Sdim  Sema::SpecialMemberOverloadResult *SMOR =
4472239462Sdim      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4473239462Sdim                            false, false, false, false);
4474239462Sdim  if (!SMOR || !SMOR->getMethod())
4475239462Sdim    // A constructor we wouldn't select can't be "involved in initializing"
4476239462Sdim    // anything.
4477239462Sdim    return true;
4478239462Sdim  return SMOR->getMethod()->isConstexpr();
4479239462Sdim}
4480223017Sdim
4481239462Sdim/// Determine whether the specified special member function would be constexpr
4482239462Sdim/// if it were implicitly defined.
4483239462Sdimstatic bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4484239462Sdim                                              Sema::CXXSpecialMember CSM,
4485239462Sdim                                              bool ConstArg) {
4486249423Sdim  if (!S.getLangOpts().CPlusPlus11)
4487239462Sdim    return false;
4488223017Sdim
4489239462Sdim  // C++11 [dcl.constexpr]p4:
4490239462Sdim  // In the definition of a constexpr constructor [...]
4491263508Sdim  bool Ctor = true;
4492239462Sdim  switch (CSM) {
4493239462Sdim  case Sema::CXXDefaultConstructor:
4494239462Sdim    // Since default constructor lookup is essentially trivial (and cannot
4495239462Sdim    // involve, for instance, template instantiation), we compute whether a
4496239462Sdim    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4497239462Sdim    //
4498239462Sdim    // This is important for performance; we need to know whether the default
4499239462Sdim    // constructor is constexpr to determine whether the type is a literal type.
4500239462Sdim    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4501223017Sdim
4502239462Sdim  case Sema::CXXCopyConstructor:
4503239462Sdim  case Sema::CXXMoveConstructor:
4504239462Sdim    // For copy or move constructors, we need to perform overload resolution.
4505239462Sdim    break;
4506226633Sdim
4507239462Sdim  case Sema::CXXCopyAssignment:
4508239462Sdim  case Sema::CXXMoveAssignment:
4509263508Sdim    if (!S.getLangOpts().CPlusPlus1y)
4510263508Sdim      return false;
4511263508Sdim    // In C++1y, we need to perform overload resolution.
4512263508Sdim    Ctor = false;
4513263508Sdim    break;
4514263508Sdim
4515239462Sdim  case Sema::CXXDestructor:
4516239462Sdim  case Sema::CXXInvalid:
4517239462Sdim    return false;
4518223017Sdim  }
4519223017Sdim
4520239462Sdim  //   -- if the class is a non-empty union, or for each non-empty anonymous
4521239462Sdim  //      union member of a non-union class, exactly one non-static data member
4522239462Sdim  //      shall be initialized; [DR1359]
4523239462Sdim  //
4524239462Sdim  // If we squint, this is guaranteed, since exactly one non-static data member
4525239462Sdim  // will be initialized (if the constructor isn't deleted), we just don't know
4526239462Sdim  // which one.
4527263508Sdim  if (Ctor && ClassDecl->isUnion())
4528239462Sdim    return true;
4529223017Sdim
4530239462Sdim  //   -- the class shall not have any virtual base classes;
4531263508Sdim  if (Ctor && ClassDecl->getNumVBases())
4532239462Sdim    return false;
4533223017Sdim
4534263508Sdim  // C++1y [class.copy]p26:
4535263508Sdim  //   -- [the class] is a literal type, and
4536263508Sdim  if (!Ctor && !ClassDecl->isLiteral())
4537263508Sdim    return false;
4538263508Sdim
4539239462Sdim  //   -- every constructor involved in initializing [...] base class
4540239462Sdim  //      sub-objects shall be a constexpr constructor;
4541263508Sdim  //   -- the assignment operator selected to copy/move each direct base
4542263508Sdim  //      class is a constexpr function, and
4543239462Sdim  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4544239462Sdim                                       BEnd = ClassDecl->bases_end();
4545239462Sdim       B != BEnd; ++B) {
4546239462Sdim    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4547239462Sdim    if (!BaseType) continue;
4548223017Sdim
4549239462Sdim    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4550239462Sdim    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4551239462Sdim      return false;
4552223017Sdim  }
4553223017Sdim
4554239462Sdim  //   -- every constructor involved in initializing non-static data members
4555239462Sdim  //      [...] shall be a constexpr constructor;
4556239462Sdim  //   -- every non-static data member and base class sub-object shall be
4557239462Sdim  //      initialized
4558263508Sdim  //   -- for each non-stastic data member of X that is of class type (or array
4559263508Sdim  //      thereof), the assignment operator selected to copy/move that member is
4560263508Sdim  //      a constexpr function
4561239462Sdim  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4562239462Sdim                               FEnd = ClassDecl->field_end();
4563239462Sdim       F != FEnd; ++F) {
4564239462Sdim    if (F->isInvalidDecl())
4565239462Sdim      continue;
4566239462Sdim    if (const RecordType *RecordTy =
4567239462Sdim            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4568239462Sdim      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4569239462Sdim      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4570239462Sdim        return false;
4571234353Sdim    }
4572234353Sdim  }
4573234353Sdim
4574239462Sdim  // All OK, it's constexpr!
4575239462Sdim  return true;
4576239462Sdim}
4577234353Sdim
4578239462Sdimstatic Sema::ImplicitExceptionSpecification
4579239462SdimcomputeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4580239462Sdim  switch (S.getSpecialMember(MD)) {
4581239462Sdim  case Sema::CXXDefaultConstructor:
4582239462Sdim    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4583239462Sdim  case Sema::CXXCopyConstructor:
4584239462Sdim    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4585239462Sdim  case Sema::CXXCopyAssignment:
4586239462Sdim    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4587239462Sdim  case Sema::CXXMoveConstructor:
4588239462Sdim    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4589239462Sdim  case Sema::CXXMoveAssignment:
4590239462Sdim    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4591239462Sdim  case Sema::CXXDestructor:
4592239462Sdim    return S.ComputeDefaultedDtorExceptionSpec(MD);
4593239462Sdim  case Sema::CXXInvalid:
4594239462Sdim    break;
4595223017Sdim  }
4596249423Sdim  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4597249423Sdim         "only special members have implicit exception specs");
4598249423Sdim  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4599239462Sdim}
4600223017Sdim
4601239462Sdimstatic void
4602239462SdimupdateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4603239462Sdim                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4604239462Sdim  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4605239462Sdim  ExceptSpec.getEPI(EPI);
4606251662Sdim  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4607251662Sdim                                        FPT->getArgTypes(), EPI));
4608223017Sdim}
4609223017Sdim
4610263508Sdimstatic FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4611263508Sdim                                                            CXXMethodDecl *MD) {
4612263508Sdim  FunctionProtoType::ExtProtoInfo EPI;
4613263508Sdim
4614263508Sdim  // Build an exception specification pointing back at this member.
4615263508Sdim  EPI.ExceptionSpecType = EST_Unevaluated;
4616263508Sdim  EPI.ExceptionSpecDecl = MD;
4617263508Sdim
4618263508Sdim  // Set the calling convention to the default for C++ instance methods.
4619263508Sdim  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4620263508Sdim      S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4621263508Sdim                                            /*IsCXXMethod=*/true));
4622263508Sdim  return EPI;
4623263508Sdim}
4624263508Sdim
4625239462Sdimvoid Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4626239462Sdim  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4627239462Sdim  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4628239462Sdim    return;
4629223017Sdim
4630239462Sdim  // Evaluate the exception specification.
4631239462Sdim  ImplicitExceptionSpecification ExceptSpec =
4632239462Sdim      computeImplicitExceptionSpec(*this, Loc, MD);
4633223017Sdim
4634239462Sdim  // Update the type of the special member to use it.
4635239462Sdim  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4636223017Sdim
4637239462Sdim  // A user-provided destructor can be defined outside the class. When that
4638239462Sdim  // happens, be sure to update the exception specification on both
4639239462Sdim  // declarations.
4640239462Sdim  const FunctionProtoType *CanonicalFPT =
4641239462Sdim    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4642239462Sdim  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4643239462Sdim    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4644239462Sdim                        CanonicalFPT, ExceptSpec);
4645239462Sdim}
4646223017Sdim
4647239462Sdimvoid Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4648239462Sdim  CXXRecordDecl *RD = MD->getParent();
4649239462Sdim  CXXSpecialMember CSM = getSpecialMember(MD);
4650234353Sdim
4651239462Sdim  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4652239462Sdim         "not an explicitly-defaulted special member");
4653234353Sdim
4654239462Sdim  // Whether this was the first-declared instance of the constructor.
4655239462Sdim  // This affects whether we implicitly add an exception spec and constexpr.
4656223017Sdim  bool First = MD == MD->getCanonicalDecl();
4657223017Sdim
4658223017Sdim  bool HadError = false;
4659239462Sdim
4660239462Sdim  // C++11 [dcl.fct.def.default]p1:
4661239462Sdim  //   A function that is explicitly defaulted shall
4662239462Sdim  //     -- be a special member function (checked elsewhere),
4663239462Sdim  //     -- have the same type (except for ref-qualifiers, and except that a
4664239462Sdim  //        copy operation can take a non-const reference) as an implicit
4665239462Sdim  //        declaration, and
4666239462Sdim  //     -- not have default arguments.
4667239462Sdim  unsigned ExpectedParams = 1;
4668239462Sdim  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4669239462Sdim    ExpectedParams = 0;
4670239462Sdim  if (MD->getNumParams() != ExpectedParams) {
4671239462Sdim    // This also checks for default arguments: a copy or move constructor with a
4672239462Sdim    // default argument is classified as a default constructor, and assignment
4673239462Sdim    // operations and destructors can't have default arguments.
4674239462Sdim    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4675239462Sdim      << CSM << MD->getSourceRange();
4676223017Sdim    HadError = true;
4677249423Sdim  } else if (MD->isVariadic()) {
4678249423Sdim    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4679249423Sdim      << CSM << MD->getSourceRange();
4680249423Sdim    HadError = true;
4681223017Sdim  }
4682223017Sdim
4683239462Sdim  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4684239462Sdim
4685239462Sdim  bool CanHaveConstParam = false;
4686249423Sdim  if (CSM == CXXCopyConstructor)
4687249423Sdim    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4688249423Sdim  else if (CSM == CXXCopyAssignment)
4689249423Sdim    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4690223017Sdim
4691239462Sdim  QualType ReturnType = Context.VoidTy;
4692239462Sdim  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4693239462Sdim    // Check for return type matching.
4694239462Sdim    ReturnType = Type->getResultType();
4695239462Sdim    QualType ExpectedReturnType =
4696239462Sdim        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4697239462Sdim    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4698239462Sdim      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4699239462Sdim        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4700223017Sdim      HadError = true;
4701223017Sdim    }
4702239462Sdim
4703239462Sdim    // A defaulted special member cannot have cv-qualifiers.
4704239462Sdim    if (Type->getTypeQuals()) {
4705239462Sdim      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4706263508Sdim        << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4707223017Sdim      HadError = true;
4708223017Sdim    }
4709223017Sdim  }
4710223017Sdim
4711239462Sdim  // Check for parameter type matching.
4712239462Sdim  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4713239462Sdim  bool HasConstParam = false;
4714239462Sdim  if (ExpectedParams && ArgType->isReferenceType()) {
4715239462Sdim    // Argument must be reference to possibly-const T.
4716239462Sdim    QualType ReferentType = ArgType->getPointeeType();
4717239462Sdim    HasConstParam = ReferentType.isConstQualified();
4718223017Sdim
4719239462Sdim    if (ReferentType.isVolatileQualified()) {
4720239462Sdim      Diag(MD->getLocation(),
4721239462Sdim           diag::err_defaulted_special_member_volatile_param) << CSM;
4722223017Sdim      HadError = true;
4723223017Sdim    }
4724234353Sdim
4725239462Sdim    if (HasConstParam && !CanHaveConstParam) {
4726239462Sdim      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4727239462Sdim        Diag(MD->getLocation(),
4728239462Sdim             diag::err_defaulted_special_member_copy_const_param)
4729239462Sdim          << (CSM == CXXCopyAssignment);
4730239462Sdim        // FIXME: Explain why this special member can't be const.
4731239462Sdim      } else {
4732239462Sdim        Diag(MD->getLocation(),
4733239462Sdim             diag::err_defaulted_special_member_move_const_param)
4734239462Sdim          << (CSM == CXXMoveAssignment);
4735239462Sdim      }
4736239462Sdim      HadError = true;
4737223017Sdim    }
4738239462Sdim  } else if (ExpectedParams) {
4739239462Sdim    // A copy assignment operator can take its argument by value, but a
4740239462Sdim    // defaulted one cannot.
4741239462Sdim    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4742239462Sdim    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4743226633Sdim    HadError = true;
4744226633Sdim  }
4745226633Sdim
4746234353Sdim  // C++11 [dcl.fct.def.default]p2:
4747234353Sdim  //   An explicitly-defaulted function may be declared constexpr only if it
4748234353Sdim  //   would have been implicitly declared as constexpr,
4749239462Sdim  // Do not apply this rule to members of class templates, since core issue 1358
4750239462Sdim  // makes such functions always instantiate to constexpr functions. For
4751263508Sdim  // functions which cannot be constexpr (for non-constructors in C++11 and for
4752263508Sdim  // destructors in C++1y), this is checked elsewhere.
4753239462Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4754239462Sdim                                                     HasConstParam);
4755263508Sdim  if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4756263508Sdim                                 : isa<CXXConstructorDecl>(MD)) &&
4757263508Sdim      MD->isConstexpr() && !Constexpr &&
4758239462Sdim      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4759239462Sdim    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4760263508Sdim    // FIXME: Explain why the special member can't be constexpr.
4761239462Sdim    HadError = true;
4762234353Sdim  }
4763249423Sdim
4764234353Sdim  //   and may have an explicit exception-specification only if it is compatible
4765234353Sdim  //   with the exception-specification on the implicit declaration.
4766249423Sdim  if (Type->hasExceptionSpec()) {
4767249423Sdim    // Delay the check if this is the first declaration of the special member,
4768249423Sdim    // since we may not have parsed some necessary in-class initializers yet.
4769249423Sdim    if (First) {
4770249423Sdim      // If the exception specification needs to be instantiated, do so now,
4771249423Sdim      // before we clobber it with an EST_Unevaluated specification below.
4772249423Sdim      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4773249423Sdim        InstantiateExceptionSpec(MD->getLocStart(), MD);
4774249423Sdim        Type = MD->getType()->getAs<FunctionProtoType>();
4775249423Sdim      }
4776249423Sdim      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4777249423Sdim    } else
4778249423Sdim      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4779249423Sdim  }
4780234353Sdim
4781234353Sdim  //   If a function is explicitly defaulted on its first declaration,
4782234353Sdim  if (First) {
4783234353Sdim    //  -- it is implicitly considered to be constexpr if the implicit
4784234353Sdim    //     definition would be,
4785239462Sdim    MD->setConstexpr(Constexpr);
4786234353Sdim
4787239462Sdim    //  -- it is implicitly considered to have the same exception-specification
4788239462Sdim    //     as if it had been implicitly declared,
4789249423Sdim    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4790249423Sdim    EPI.ExceptionSpecType = EST_Unevaluated;
4791249423Sdim    EPI.ExceptionSpecDecl = MD;
4792249423Sdim    MD->setType(Context.getFunctionType(ReturnType,
4793249423Sdim                                        ArrayRef<QualType>(&ArgType,
4794249423Sdim                                                           ExpectedParams),
4795249423Sdim                                        EPI));
4796226633Sdim  }
4797226633Sdim
4798239462Sdim  if (ShouldDeleteSpecialMember(MD, CSM)) {
4799226633Sdim    if (First) {
4800249423Sdim      SetDeclDeleted(MD, MD->getLocation());
4801226633Sdim    } else {
4802239462Sdim      // C++11 [dcl.fct.def.default]p4:
4803239462Sdim      //   [For a] user-provided explicitly-defaulted function [...] if such a
4804239462Sdim      //   function is implicitly defined as deleted, the program is ill-formed.
4805239462Sdim      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4806226633Sdim      HadError = true;
4807226633Sdim    }
4808226633Sdim  }
4809226633Sdim
4810239462Sdim  if (HadError)
4811226633Sdim    MD->setInvalidDecl();
4812226633Sdim}
4813226633Sdim
4814249423Sdim/// Check whether the exception specification provided for an
4815249423Sdim/// explicitly-defaulted special member matches the exception specification
4816249423Sdim/// that would have been generated for an implicit special member, per
4817249423Sdim/// C++11 [dcl.fct.def.default]p2.
4818249423Sdimvoid Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4819249423Sdim    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4820249423Sdim  // Compute the implicit exception specification.
4821263508Sdim  CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4822263508Sdim                                                       /*IsCXXMethod=*/true);
4823263508Sdim  FunctionProtoType::ExtProtoInfo EPI(CC);
4824249423Sdim  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4825249423Sdim  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4826251662Sdim    Context.getFunctionType(Context.VoidTy, None, EPI));
4827249423Sdim
4828249423Sdim  // Ensure that it matches.
4829249423Sdim  CheckEquivalentExceptionSpec(
4830249423Sdim    PDiag(diag::err_incorrect_defaulted_exception_spec)
4831249423Sdim      << getSpecialMember(MD), PDiag(),
4832249423Sdim    ImplicitType, SourceLocation(),
4833249423Sdim    SpecifiedType, MD->getLocation());
4834249423Sdim}
4835249423Sdim
4836263508Sdimvoid Sema::CheckDelayedMemberExceptionSpecs() {
4837263508Sdim  SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4838263508Sdim              2> Checks;
4839263508Sdim  SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4840249423Sdim
4841263508Sdim  std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4842263508Sdim  std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4843263508Sdim
4844263508Sdim  // Perform any deferred checking of exception specifications for virtual
4845263508Sdim  // destructors.
4846263508Sdim  for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4847263508Sdim    const CXXDestructorDecl *Dtor = Checks[i].first;
4848263508Sdim    assert(!Dtor->getParent()->isDependentType() &&
4849263508Sdim           "Should not ever add destructors of templates into the list.");
4850263508Sdim    CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4851263508Sdim  }
4852263508Sdim
4853263508Sdim  // Check that any explicitly-defaulted methods have exception specifications
4854263508Sdim  // compatible with their implicit exception specifications.
4855263508Sdim  for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4856263508Sdim    CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4857263508Sdim                                                Specs[I].second);
4858249423Sdim}
4859249423Sdim
4860234353Sdimnamespace {
4861234353Sdimstruct SpecialMemberDeletionInfo {
4862234353Sdim  Sema &S;
4863234353Sdim  CXXMethodDecl *MD;
4864234353Sdim  Sema::CXXSpecialMember CSM;
4865234353Sdim  bool Diagnose;
4866223017Sdim
4867234353Sdim  // Properties of the special member, computed for convenience.
4868234353Sdim  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4869234353Sdim  SourceLocation Loc;
4870223017Sdim
4871234353Sdim  bool AllFieldsAreConst;
4872223017Sdim
4873234353Sdim  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4874234353Sdim                            Sema::CXXSpecialMember CSM, bool Diagnose)
4875234353Sdim    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4876234353Sdim      IsConstructor(false), IsAssignment(false), IsMove(false),
4877234353Sdim      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4878234353Sdim      AllFieldsAreConst(true) {
4879234353Sdim    switch (CSM) {
4880234353Sdim      case Sema::CXXDefaultConstructor:
4881234353Sdim      case Sema::CXXCopyConstructor:
4882234353Sdim        IsConstructor = true;
4883234353Sdim        break;
4884234353Sdim      case Sema::CXXMoveConstructor:
4885234353Sdim        IsConstructor = true;
4886234353Sdim        IsMove = true;
4887234353Sdim        break;
4888234353Sdim      case Sema::CXXCopyAssignment:
4889234353Sdim        IsAssignment = true;
4890234353Sdim        break;
4891234353Sdim      case Sema::CXXMoveAssignment:
4892234353Sdim        IsAssignment = true;
4893234353Sdim        IsMove = true;
4894234353Sdim        break;
4895234353Sdim      case Sema::CXXDestructor:
4896234353Sdim        break;
4897234353Sdim      case Sema::CXXInvalid:
4898234353Sdim        llvm_unreachable("invalid special member kind");
4899226633Sdim    }
4900223017Sdim
4901234353Sdim    if (MD->getNumParams()) {
4902234353Sdim      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4903234353Sdim      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4904226633Sdim    }
4905223017Sdim  }
4906223017Sdim
4907234353Sdim  bool inUnion() const { return MD->getParent()->isUnion(); }
4908223017Sdim
4909234353Sdim  /// Look up the corresponding special member in the given class.
4910239462Sdim  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4911239462Sdim                                              unsigned Quals) {
4912234353Sdim    unsigned TQ = MD->getTypeQualifiers();
4913239462Sdim    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4914239462Sdim    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4915239462Sdim      Quals = 0;
4916263508Sdim    // cv-qualifiers on class members affect the type of both '*this' and the
4917263508Sdim    // argument for an assignment.
4918263508Sdim    if (IsAssignment)
4919263508Sdim      TQ |= Quals;
4920239462Sdim    return S.LookupSpecialMember(Class, CSM,
4921239462Sdim                                 ConstArg || (Quals & Qualifiers::Const),
4922239462Sdim                                 VolatileArg || (Quals & Qualifiers::Volatile),
4923234353Sdim                                 MD->getRefQualifier() == RQ_RValue,
4924234353Sdim                                 TQ & Qualifiers::Const,
4925234353Sdim                                 TQ & Qualifiers::Volatile);
4926223017Sdim  }
4927223017Sdim
4928234353Sdim  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4929223017Sdim
4930234353Sdim  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4931234353Sdim  bool shouldDeleteForField(FieldDecl *FD);
4932234353Sdim  bool shouldDeleteForAllConstMembers();
4933223017Sdim
4934239462Sdim  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4935239462Sdim                                     unsigned Quals);
4936234353Sdim  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4937234353Sdim                                    Sema::SpecialMemberOverloadResult *SMOR,
4938234353Sdim                                    bool IsDtorCallInCtor);
4939223017Sdim
4940234353Sdim  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4941234353Sdim};
4942234353Sdim}
4943223017Sdim
4944234353Sdim/// Is the given special member inaccessible when used on the given
4945234353Sdim/// sub-object.
4946234353Sdimbool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4947234353Sdim                                             CXXMethodDecl *target) {
4948234353Sdim  /// If we're operating on a base class, the object type is the
4949234353Sdim  /// type of this special member.
4950234353Sdim  QualType objectTy;
4951243830Sdim  AccessSpecifier access = target->getAccess();
4952234353Sdim  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4953234353Sdim    objectTy = S.Context.getTypeDeclType(MD->getParent());
4954234353Sdim    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4955223017Sdim
4956234353Sdim  // If we're operating on a field, the object type is the type of the field.
4957234353Sdim  } else {
4958234353Sdim    objectTy = S.Context.getTypeDeclType(target->getParent());
4959234353Sdim  }
4960223017Sdim
4961234353Sdim  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4962234353Sdim}
4963226633Sdim
4964234353Sdim/// Check whether we should delete a special member due to the implicit
4965234353Sdim/// definition containing a call to a special member of a subobject.
4966234353Sdimbool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4967234353Sdim    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4968234353Sdim    bool IsDtorCallInCtor) {
4969234353Sdim  CXXMethodDecl *Decl = SMOR->getMethod();
4970234353Sdim  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4971226633Sdim
4972234353Sdim  int DiagKind = -1;
4973226633Sdim
4974234353Sdim  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4975234353Sdim    DiagKind = !Decl ? 0 : 1;
4976234353Sdim  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4977234353Sdim    DiagKind = 2;
4978234353Sdim  else if (!isAccessible(Subobj, Decl))
4979234353Sdim    DiagKind = 3;
4980234353Sdim  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4981234353Sdim           !Decl->isTrivial()) {
4982234353Sdim    // A member of a union must have a trivial corresponding special member.
4983234353Sdim    // As a weird special case, a destructor call from a union's constructor
4984234353Sdim    // must be accessible and non-deleted, but need not be trivial. Such a
4985234353Sdim    // destructor is never actually called, but is semantically checked as
4986234353Sdim    // if it were.
4987234353Sdim    DiagKind = 4;
4988234353Sdim  }
4989223017Sdim
4990234353Sdim  if (DiagKind == -1)
4991234353Sdim    return false;
4992223017Sdim
4993234353Sdim  if (Diagnose) {
4994234353Sdim    if (Field) {
4995234353Sdim      S.Diag(Field->getLocation(),
4996234353Sdim             diag::note_deleted_special_member_class_subobject)
4997234353Sdim        << CSM << MD->getParent() << /*IsField*/true
4998234353Sdim        << Field << DiagKind << IsDtorCallInCtor;
4999234353Sdim    } else {
5000234353Sdim      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5001234353Sdim      S.Diag(Base->getLocStart(),
5002234353Sdim             diag::note_deleted_special_member_class_subobject)
5003234353Sdim        << CSM << MD->getParent() << /*IsField*/false
5004234353Sdim        << Base->getType() << DiagKind << IsDtorCallInCtor;
5005234353Sdim    }
5006223017Sdim
5007234353Sdim    if (DiagKind == 1)
5008234353Sdim      S.NoteDeletedFunction(Decl);
5009234353Sdim    // FIXME: Explain inaccessibility if DiagKind == 3.
5010234353Sdim  }
5011226633Sdim
5012234353Sdim  return true;
5013234353Sdim}
5014226633Sdim
5015234353Sdim/// Check whether we should delete a special member function due to having a
5016239462Sdim/// direct or virtual base class or non-static data member of class type M.
5017234353Sdimbool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5018239462Sdim    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5019234353Sdim  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5020226633Sdim
5021234353Sdim  // C++11 [class.ctor]p5:
5022234353Sdim  // -- any direct or virtual base class, or non-static data member with no
5023234353Sdim  //    brace-or-equal-initializer, has class type M (or array thereof) and
5024234353Sdim  //    either M has no default constructor or overload resolution as applied
5025234353Sdim  //    to M's default constructor results in an ambiguity or in a function
5026234353Sdim  //    that is deleted or inaccessible
5027234353Sdim  // C++11 [class.copy]p11, C++11 [class.copy]p23:
5028234353Sdim  // -- a direct or virtual base class B that cannot be copied/moved because
5029234353Sdim  //    overload resolution, as applied to B's corresponding special member,
5030234353Sdim  //    results in an ambiguity or a function that is deleted or inaccessible
5031234353Sdim  //    from the defaulted special member
5032234353Sdim  // C++11 [class.dtor]p5:
5033234353Sdim  // -- any direct or virtual base class [...] has a type with a destructor
5034234353Sdim  //    that is deleted or inaccessible
5035234353Sdim  if (!(CSM == Sema::CXXDefaultConstructor &&
5036234353Sdim        Field && Field->hasInClassInitializer()) &&
5037239462Sdim      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
5038234353Sdim    return true;
5039226633Sdim
5040234353Sdim  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5041234353Sdim  // -- any direct or virtual base class or non-static data member has a
5042234353Sdim  //    type with a destructor that is deleted or inaccessible
5043234353Sdim  if (IsConstructor) {
5044234353Sdim    Sema::SpecialMemberOverloadResult *SMOR =
5045234353Sdim        S.LookupSpecialMember(Class, Sema::CXXDestructor,
5046234353Sdim                              false, false, false, false, false);
5047234353Sdim    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5048223017Sdim      return true;
5049223017Sdim  }
5050223017Sdim
5051223017Sdim  return false;
5052223017Sdim}
5053223017Sdim
5054234353Sdim/// Check whether we should delete a special member function due to the class
5055234353Sdim/// having a particular direct or virtual base class.
5056234353Sdimbool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5057234353Sdim  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5058239462Sdim  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5059234353Sdim}
5060223017Sdim
5061234353Sdim/// Check whether we should delete a special member function due to the class
5062234353Sdim/// having a particular non-static data member.
5063234353Sdimbool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5064234353Sdim  QualType FieldType = S.Context.getBaseElementType(FD->getType());
5065234353Sdim  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5066223017Sdim
5067234353Sdim  if (CSM == Sema::CXXDefaultConstructor) {
5068234353Sdim    // For a default constructor, all references must be initialized in-class
5069234353Sdim    // and, if a union, it must have a non-const member.
5070234353Sdim    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5071234353Sdim      if (Diagnose)
5072234353Sdim        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5073234353Sdim          << MD->getParent() << FD << FieldType << /*Reference*/0;
5074223017Sdim      return true;
5075234353Sdim    }
5076234353Sdim    // C++11 [class.ctor]p5: any non-variant non-static data member of
5077234353Sdim    // const-qualified type (or array thereof) with no
5078234353Sdim    // brace-or-equal-initializer does not have a user-provided default
5079234353Sdim    // constructor.
5080234353Sdim    if (!inUnion() && FieldType.isConstQualified() &&
5081234353Sdim        !FD->hasInClassInitializer() &&
5082234353Sdim        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5083234353Sdim      if (Diagnose)
5084234353Sdim        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5085239462Sdim          << MD->getParent() << FD << FD->getType() << /*Const*/1;
5086223017Sdim      return true;
5087234353Sdim    }
5088223017Sdim
5089234353Sdim    if (inUnion() && !FieldType.isConstQualified())
5090234353Sdim      AllFieldsAreConst = false;
5091234353Sdim  } else if (CSM == Sema::CXXCopyConstructor) {
5092234353Sdim    // For a copy constructor, data members must not be of rvalue reference
5093234353Sdim    // type.
5094234353Sdim    if (FieldType->isRValueReferenceType()) {
5095234353Sdim      if (Diagnose)
5096234353Sdim        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5097234353Sdim          << MD->getParent() << FD << FieldType;
5098223017Sdim      return true;
5099234353Sdim    }
5100234353Sdim  } else if (IsAssignment) {
5101234353Sdim    // For an assignment operator, data members must not be of reference type.
5102234353Sdim    if (FieldType->isReferenceType()) {
5103234353Sdim      if (Diagnose)
5104234353Sdim        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5105234353Sdim          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5106223017Sdim      return true;
5107234353Sdim    }
5108234353Sdim    if (!FieldRecord && FieldType.isConstQualified()) {
5109234353Sdim      // C++11 [class.copy]p23:
5110234353Sdim      // -- a non-static data member of const non-class type (or array thereof)
5111234353Sdim      if (Diagnose)
5112234353Sdim        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5113239462Sdim          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5114234353Sdim      return true;
5115234353Sdim    }
5116223017Sdim  }
5117223017Sdim
5118234353Sdim  if (FieldRecord) {
5119234353Sdim    // Some additional restrictions exist on the variant members.
5120234353Sdim    if (!inUnion() && FieldRecord->isUnion() &&
5121234353Sdim        FieldRecord->isAnonymousStructOrUnion()) {
5122234353Sdim      bool AllVariantFieldsAreConst = true;
5123226633Sdim
5124234353Sdim      // FIXME: Handle anonymous unions declared within anonymous unions.
5125234353Sdim      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5126234353Sdim                                         UE = FieldRecord->field_end();
5127234353Sdim           UI != UE; ++UI) {
5128234353Sdim        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5129223017Sdim
5130234353Sdim        if (!UnionFieldType.isConstQualified())
5131234353Sdim          AllVariantFieldsAreConst = false;
5132223017Sdim
5133234353Sdim        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5134234353Sdim        if (UnionFieldRecord &&
5135239462Sdim            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5136239462Sdim                                          UnionFieldType.getCVRQualifiers()))
5137223017Sdim          return true;
5138223017Sdim      }
5139223017Sdim
5140234353Sdim      // At least one member in each anonymous union must be non-const
5141234353Sdim      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5142234353Sdim          FieldRecord->field_begin() != FieldRecord->field_end()) {
5143234353Sdim        if (Diagnose)
5144234353Sdim          S.Diag(FieldRecord->getLocation(),
5145234353Sdim                 diag::note_deleted_default_ctor_all_const)
5146234353Sdim            << MD->getParent() << /*anonymous union*/1;
5147223017Sdim        return true;
5148234353Sdim      }
5149234353Sdim
5150234353Sdim      // Don't check the implicit member of the anonymous union type.
5151234353Sdim      // This is technically non-conformant, but sanity demands it.
5152234353Sdim      return false;
5153223017Sdim    }
5154234353Sdim
5155239462Sdim    if (shouldDeleteForClassSubobject(FieldRecord, FD,
5156239462Sdim                                      FieldType.getCVRQualifiers()))
5157234353Sdim      return true;
5158223017Sdim  }
5159223017Sdim
5160223017Sdim  return false;
5161223017Sdim}
5162223017Sdim
5163234353Sdim/// C++11 [class.ctor] p5:
5164234353Sdim///   A defaulted default constructor for a class X is defined as deleted if
5165234353Sdim/// X is a union and all of its variant members are of const-qualified type.
5166234353Sdimbool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5167234353Sdim  // This is a silly definition, because it gives an empty union a deleted
5168234353Sdim  // default constructor. Don't do that.
5169234353Sdim  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5170234353Sdim      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5171234353Sdim    if (Diagnose)
5172234353Sdim      S.Diag(MD->getParent()->getLocation(),
5173234353Sdim             diag::note_deleted_default_ctor_all_const)
5174234353Sdim        << MD->getParent() << /*not anonymous union*/0;
5175234353Sdim    return true;
5176234353Sdim  }
5177234353Sdim  return false;
5178234353Sdim}
5179234353Sdim
5180234353Sdim/// Determine whether a defaulted special member function should be defined as
5181234353Sdim/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5182234353Sdim/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5183234353Sdimbool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5184234353Sdim                                     bool Diagnose) {
5185239462Sdim  if (MD->isInvalidDecl())
5186239462Sdim    return false;
5187223017Sdim  CXXRecordDecl *RD = MD->getParent();
5188223017Sdim  assert(!RD->isDependentType() && "do deletion after instantiation");
5189249423Sdim  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5190223017Sdim    return false;
5191223017Sdim
5192234353Sdim  // C++11 [expr.lambda.prim]p19:
5193234353Sdim  //   The closure type associated with a lambda-expression has a
5194234353Sdim  //   deleted (8.4.3) default constructor and a deleted copy
5195234353Sdim  //   assignment operator.
5196234353Sdim  if (RD->isLambda() &&
5197234353Sdim      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5198234353Sdim    if (Diagnose)
5199234353Sdim      Diag(RD->getLocation(), diag::note_lambda_decl);
5200234353Sdim    return true;
5201234353Sdim  }
5202223017Sdim
5203234353Sdim  // For an anonymous struct or union, the copy and assignment special members
5204234353Sdim  // will never be used, so skip the check. For an anonymous union declared at
5205234353Sdim  // namespace scope, the constructor and destructor are used.
5206234353Sdim  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5207234353Sdim      RD->isAnonymousStructOrUnion())
5208223017Sdim    return false;
5209223017Sdim
5210234353Sdim  // C++11 [class.copy]p7, p18:
5211234353Sdim  //   If the class definition declares a move constructor or move assignment
5212234353Sdim  //   operator, an implicitly declared copy constructor or copy assignment
5213234353Sdim  //   operator is defined as deleted.
5214234353Sdim  if (MD->isImplicit() &&
5215234353Sdim      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5216234353Sdim    CXXMethodDecl *UserDeclaredMove = 0;
5217223017Sdim
5218234353Sdim    // In Microsoft mode, a user-declared move only causes the deletion of the
5219234353Sdim    // corresponding copy operation, not both copy operations.
5220234353Sdim    if (RD->hasUserDeclaredMoveConstructor() &&
5221234353Sdim        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5222234353Sdim      if (!Diagnose) return true;
5223249423Sdim
5224249423Sdim      // Find any user-declared move constructor.
5225249423Sdim      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5226249423Sdim                                        E = RD->ctor_end(); I != E; ++I) {
5227249423Sdim        if (I->isMoveConstructor()) {
5228249423Sdim          UserDeclaredMove = *I;
5229249423Sdim          break;
5230249423Sdim        }
5231249423Sdim      }
5232234353Sdim      assert(UserDeclaredMove);
5233234353Sdim    } else if (RD->hasUserDeclaredMoveAssignment() &&
5234234353Sdim               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5235234353Sdim      if (!Diagnose) return true;
5236249423Sdim
5237249423Sdim      // Find any user-declared move assignment operator.
5238249423Sdim      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5239249423Sdim                                          E = RD->method_end(); I != E; ++I) {
5240249423Sdim        if (I->isMoveAssignmentOperator()) {
5241249423Sdim          UserDeclaredMove = *I;
5242249423Sdim          break;
5243249423Sdim        }
5244249423Sdim      }
5245234353Sdim      assert(UserDeclaredMove);
5246234353Sdim    }
5247226633Sdim
5248234353Sdim    if (UserDeclaredMove) {
5249234353Sdim      Diag(UserDeclaredMove->getLocation(),
5250234353Sdim           diag::note_deleted_copy_user_declared_move)
5251234353Sdim        << (CSM == CXXCopyAssignment) << RD
5252234353Sdim        << UserDeclaredMove->isMoveAssignmentOperator();
5253223017Sdim      return true;
5254234353Sdim    }
5255223017Sdim  }
5256223017Sdim
5257234353Sdim  // Do access control from the special member function
5258234353Sdim  ContextRAII MethodContext(*this, MD);
5259223017Sdim
5260234353Sdim  // C++11 [class.dtor]p5:
5261234353Sdim  // -- for a virtual destructor, lookup of the non-array deallocation function
5262234353Sdim  //    results in an ambiguity or in a function that is deleted or inaccessible
5263234353Sdim  if (CSM == CXXDestructor && MD->isVirtual()) {
5264234353Sdim    FunctionDecl *OperatorDelete = 0;
5265234353Sdim    DeclarationName Name =
5266234353Sdim      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5267234353Sdim    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5268234353Sdim                                 OperatorDelete, false)) {
5269234353Sdim      if (Diagnose)
5270234353Sdim        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5271223017Sdim      return true;
5272223017Sdim    }
5273223017Sdim  }
5274223017Sdim
5275234353Sdim  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5276223017Sdim
5277223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5278234353Sdim                                          BE = RD->bases_end(); BI != BE; ++BI)
5279234353Sdim    if (!BI->isVirtual() &&
5280234353Sdim        SMI.shouldDeleteForBase(BI))
5281223017Sdim      return true;
5282223017Sdim
5283263508Sdim  // Per DR1611, do not consider virtual bases of constructors of abstract
5284263508Sdim  // classes, since we are not going to construct them.
5285263508Sdim  if (!RD->isAbstract() || !SMI.IsConstructor) {
5286263508Sdim    for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5287263508Sdim                                            BE = RD->vbases_end();
5288263508Sdim         BI != BE; ++BI)
5289263508Sdim      if (SMI.shouldDeleteForBase(BI))
5290263508Sdim        return true;
5291263508Sdim  }
5292223017Sdim
5293223017Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5294234353Sdim                                     FE = RD->field_end(); FI != FE; ++FI)
5295234353Sdim    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5296234353Sdim        SMI.shouldDeleteForField(*FI))
5297223017Sdim      return true;
5298223017Sdim
5299234353Sdim  if (SMI.shouldDeleteForAllConstMembers())
5300234353Sdim    return true;
5301223017Sdim
5302223017Sdim  return false;
5303223017Sdim}
5304223017Sdim
5305249423Sdim/// Perform lookup for a special member of the specified kind, and determine
5306249423Sdim/// whether it is trivial. If the triviality can be determined without the
5307249423Sdim/// lookup, skip it. This is intended for use when determining whether a
5308249423Sdim/// special member of a containing object is trivial, and thus does not ever
5309249423Sdim/// perform overload resolution for default constructors.
5310249423Sdim///
5311249423Sdim/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5312249423Sdim/// member that was most likely to be intended to be trivial, if any.
5313249423Sdimstatic bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5314249423Sdim                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5315249423Sdim                                     CXXMethodDecl **Selected) {
5316249423Sdim  if (Selected)
5317249423Sdim    *Selected = 0;
5318249423Sdim
5319249423Sdim  switch (CSM) {
5320249423Sdim  case Sema::CXXInvalid:
5321249423Sdim    llvm_unreachable("not a special member");
5322249423Sdim
5323249423Sdim  case Sema::CXXDefaultConstructor:
5324249423Sdim    // C++11 [class.ctor]p5:
5325249423Sdim    //   A default constructor is trivial if:
5326249423Sdim    //    - all the [direct subobjects] have trivial default constructors
5327249423Sdim    //
5328249423Sdim    // Note, no overload resolution is performed in this case.
5329249423Sdim    if (RD->hasTrivialDefaultConstructor())
5330249423Sdim      return true;
5331249423Sdim
5332249423Sdim    if (Selected) {
5333249423Sdim      // If there's a default constructor which could have been trivial, dig it
5334249423Sdim      // out. Otherwise, if there's any user-provided default constructor, point
5335249423Sdim      // to that as an example of why there's not a trivial one.
5336249423Sdim      CXXConstructorDecl *DefCtor = 0;
5337249423Sdim      if (RD->needsImplicitDefaultConstructor())
5338249423Sdim        S.DeclareImplicitDefaultConstructor(RD);
5339249423Sdim      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5340249423Sdim                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5341249423Sdim        if (!CI->isDefaultConstructor())
5342249423Sdim          continue;
5343249423Sdim        DefCtor = *CI;
5344249423Sdim        if (!DefCtor->isUserProvided())
5345249423Sdim          break;
5346249423Sdim      }
5347249423Sdim
5348249423Sdim      *Selected = DefCtor;
5349249423Sdim    }
5350249423Sdim
5351249423Sdim    return false;
5352249423Sdim
5353249423Sdim  case Sema::CXXDestructor:
5354249423Sdim    // C++11 [class.dtor]p5:
5355249423Sdim    //   A destructor is trivial if:
5356249423Sdim    //    - all the direct [subobjects] have trivial destructors
5357249423Sdim    if (RD->hasTrivialDestructor())
5358249423Sdim      return true;
5359249423Sdim
5360249423Sdim    if (Selected) {
5361249423Sdim      if (RD->needsImplicitDestructor())
5362249423Sdim        S.DeclareImplicitDestructor(RD);
5363249423Sdim      *Selected = RD->getDestructor();
5364249423Sdim    }
5365249423Sdim
5366249423Sdim    return false;
5367249423Sdim
5368249423Sdim  case Sema::CXXCopyConstructor:
5369249423Sdim    // C++11 [class.copy]p12:
5370249423Sdim    //   A copy constructor is trivial if:
5371249423Sdim    //    - the constructor selected to copy each direct [subobject] is trivial
5372249423Sdim    if (RD->hasTrivialCopyConstructor()) {
5373249423Sdim      if (Quals == Qualifiers::Const)
5374249423Sdim        // We must either select the trivial copy constructor or reach an
5375249423Sdim        // ambiguity; no need to actually perform overload resolution.
5376249423Sdim        return true;
5377249423Sdim    } else if (!Selected) {
5378249423Sdim      return false;
5379249423Sdim    }
5380249423Sdim    // In C++98, we are not supposed to perform overload resolution here, but we
5381249423Sdim    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5382249423Sdim    // cases like B as having a non-trivial copy constructor:
5383249423Sdim    //   struct A { template<typename T> A(T&); };
5384249423Sdim    //   struct B { mutable A a; };
5385249423Sdim    goto NeedOverloadResolution;
5386249423Sdim
5387249423Sdim  case Sema::CXXCopyAssignment:
5388249423Sdim    // C++11 [class.copy]p25:
5389249423Sdim    //   A copy assignment operator is trivial if:
5390249423Sdim    //    - the assignment operator selected to copy each direct [subobject] is
5391249423Sdim    //      trivial
5392249423Sdim    if (RD->hasTrivialCopyAssignment()) {
5393249423Sdim      if (Quals == Qualifiers::Const)
5394249423Sdim        return true;
5395249423Sdim    } else if (!Selected) {
5396249423Sdim      return false;
5397249423Sdim    }
5398249423Sdim    // In C++98, we are not supposed to perform overload resolution here, but we
5399249423Sdim    // treat that as a language defect.
5400249423Sdim    goto NeedOverloadResolution;
5401249423Sdim
5402249423Sdim  case Sema::CXXMoveConstructor:
5403249423Sdim  case Sema::CXXMoveAssignment:
5404249423Sdim  NeedOverloadResolution:
5405249423Sdim    Sema::SpecialMemberOverloadResult *SMOR =
5406249423Sdim      S.LookupSpecialMember(RD, CSM,
5407249423Sdim                            Quals & Qualifiers::Const,
5408249423Sdim                            Quals & Qualifiers::Volatile,
5409249423Sdim                            /*RValueThis*/false, /*ConstThis*/false,
5410249423Sdim                            /*VolatileThis*/false);
5411249423Sdim
5412249423Sdim    // The standard doesn't describe how to behave if the lookup is ambiguous.
5413249423Sdim    // We treat it as not making the member non-trivial, just like the standard
5414249423Sdim    // mandates for the default constructor. This should rarely matter, because
5415249423Sdim    // the member will also be deleted.
5416249423Sdim    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5417249423Sdim      return true;
5418249423Sdim
5419249423Sdim    if (!SMOR->getMethod()) {
5420249423Sdim      assert(SMOR->getKind() ==
5421249423Sdim             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5422249423Sdim      return false;
5423249423Sdim    }
5424249423Sdim
5425249423Sdim    // We deliberately don't check if we found a deleted special member. We're
5426249423Sdim    // not supposed to!
5427249423Sdim    if (Selected)
5428249423Sdim      *Selected = SMOR->getMethod();
5429249423Sdim    return SMOR->getMethod()->isTrivial();
5430249423Sdim  }
5431249423Sdim
5432249423Sdim  llvm_unreachable("unknown special method kind");
5433249423Sdim}
5434249423Sdim
5435249423Sdimstatic CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5436249423Sdim  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5437249423Sdim       CI != CE; ++CI)
5438249423Sdim    if (!CI->isImplicit())
5439249423Sdim      return *CI;
5440249423Sdim
5441249423Sdim  // Look for constructor templates.
5442249423Sdim  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5443249423Sdim  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5444249423Sdim    if (CXXConstructorDecl *CD =
5445249423Sdim          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5446249423Sdim      return CD;
5447249423Sdim  }
5448249423Sdim
5449249423Sdim  return 0;
5450249423Sdim}
5451249423Sdim
5452249423Sdim/// The kind of subobject we are checking for triviality. The values of this
5453249423Sdim/// enumeration are used in diagnostics.
5454249423Sdimenum TrivialSubobjectKind {
5455249423Sdim  /// The subobject is a base class.
5456249423Sdim  TSK_BaseClass,
5457249423Sdim  /// The subobject is a non-static data member.
5458249423Sdim  TSK_Field,
5459249423Sdim  /// The object is actually the complete object.
5460249423Sdim  TSK_CompleteObject
5461249423Sdim};
5462249423Sdim
5463249423Sdim/// Check whether the special member selected for a given type would be trivial.
5464249423Sdimstatic bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5465249423Sdim                                      QualType SubType,
5466249423Sdim                                      Sema::CXXSpecialMember CSM,
5467249423Sdim                                      TrivialSubobjectKind Kind,
5468249423Sdim                                      bool Diagnose) {
5469249423Sdim  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5470249423Sdim  if (!SubRD)
5471249423Sdim    return true;
5472249423Sdim
5473249423Sdim  CXXMethodDecl *Selected;
5474249423Sdim  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5475249423Sdim                               Diagnose ? &Selected : 0))
5476249423Sdim    return true;
5477249423Sdim
5478249423Sdim  if (Diagnose) {
5479249423Sdim    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5480249423Sdim      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5481249423Sdim        << Kind << SubType.getUnqualifiedType();
5482249423Sdim      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5483249423Sdim        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5484249423Sdim    } else if (!Selected)
5485249423Sdim      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5486249423Sdim        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5487249423Sdim    else if (Selected->isUserProvided()) {
5488249423Sdim      if (Kind == TSK_CompleteObject)
5489249423Sdim        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5490249423Sdim          << Kind << SubType.getUnqualifiedType() << CSM;
5491249423Sdim      else {
5492249423Sdim        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5493249423Sdim          << Kind << SubType.getUnqualifiedType() << CSM;
5494249423Sdim        S.Diag(Selected->getLocation(), diag::note_declared_at);
5495249423Sdim      }
5496249423Sdim    } else {
5497249423Sdim      if (Kind != TSK_CompleteObject)
5498249423Sdim        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5499249423Sdim          << Kind << SubType.getUnqualifiedType() << CSM;
5500249423Sdim
5501249423Sdim      // Explain why the defaulted or deleted special member isn't trivial.
5502249423Sdim      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5503249423Sdim    }
5504249423Sdim  }
5505249423Sdim
5506249423Sdim  return false;
5507249423Sdim}
5508249423Sdim
5509249423Sdim/// Check whether the members of a class type allow a special member to be
5510249423Sdim/// trivial.
5511249423Sdimstatic bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5512249423Sdim                                     Sema::CXXSpecialMember CSM,
5513249423Sdim                                     bool ConstArg, bool Diagnose) {
5514249423Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5515249423Sdim                                     FE = RD->field_end(); FI != FE; ++FI) {
5516249423Sdim    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5517249423Sdim      continue;
5518249423Sdim
5519249423Sdim    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5520249423Sdim
5521249423Sdim    // Pretend anonymous struct or union members are members of this class.
5522249423Sdim    if (FI->isAnonymousStructOrUnion()) {
5523249423Sdim      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5524249423Sdim                                    CSM, ConstArg, Diagnose))
5525249423Sdim        return false;
5526249423Sdim      continue;
5527249423Sdim    }
5528249423Sdim
5529249423Sdim    // C++11 [class.ctor]p5:
5530249423Sdim    //   A default constructor is trivial if [...]
5531249423Sdim    //    -- no non-static data member of its class has a
5532249423Sdim    //       brace-or-equal-initializer
5533249423Sdim    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5534249423Sdim      if (Diagnose)
5535249423Sdim        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5536249423Sdim      return false;
5537249423Sdim    }
5538249423Sdim
5539249423Sdim    // Objective C ARC 4.3.5:
5540249423Sdim    //   [...] nontrivally ownership-qualified types are [...] not trivially
5541249423Sdim    //   default constructible, copy constructible, move constructible, copy
5542249423Sdim    //   assignable, move assignable, or destructible [...]
5543249423Sdim    if (S.getLangOpts().ObjCAutoRefCount &&
5544249423Sdim        FieldType.hasNonTrivialObjCLifetime()) {
5545249423Sdim      if (Diagnose)
5546249423Sdim        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5547249423Sdim          << RD << FieldType.getObjCLifetime();
5548249423Sdim      return false;
5549249423Sdim    }
5550249423Sdim
5551249423Sdim    if (ConstArg && !FI->isMutable())
5552249423Sdim      FieldType.addConst();
5553249423Sdim    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5554249423Sdim                                   TSK_Field, Diagnose))
5555249423Sdim      return false;
5556249423Sdim  }
5557249423Sdim
5558249423Sdim  return true;
5559249423Sdim}
5560249423Sdim
5561249423Sdim/// Diagnose why the specified class does not have a trivial special member of
5562249423Sdim/// the given kind.
5563249423Sdimvoid Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5564249423Sdim  QualType Ty = Context.getRecordType(RD);
5565249423Sdim  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5566249423Sdim    Ty.addConst();
5567249423Sdim
5568249423Sdim  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5569249423Sdim                            TSK_CompleteObject, /*Diagnose*/true);
5570249423Sdim}
5571249423Sdim
5572249423Sdim/// Determine whether a defaulted or deleted special member function is trivial,
5573249423Sdim/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5574249423Sdim/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5575249423Sdimbool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5576249423Sdim                                  bool Diagnose) {
5577249423Sdim  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5578249423Sdim
5579249423Sdim  CXXRecordDecl *RD = MD->getParent();
5580249423Sdim
5581249423Sdim  bool ConstArg = false;
5582249423Sdim
5583263508Sdim  // C++11 [class.copy]p12, p25: [DR1593]
5584263508Sdim  //   A [special member] is trivial if [...] its parameter-type-list is
5585263508Sdim  //   equivalent to the parameter-type-list of an implicit declaration [...]
5586249423Sdim  switch (CSM) {
5587249423Sdim  case CXXDefaultConstructor:
5588249423Sdim  case CXXDestructor:
5589249423Sdim    // Trivial default constructors and destructors cannot have parameters.
5590249423Sdim    break;
5591249423Sdim
5592249423Sdim  case CXXCopyConstructor:
5593249423Sdim  case CXXCopyAssignment: {
5594249423Sdim    // Trivial copy operations always have const, non-volatile parameter types.
5595249423Sdim    ConstArg = true;
5596249423Sdim    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5597249423Sdim    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5598249423Sdim    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5599249423Sdim      if (Diagnose)
5600249423Sdim        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5601249423Sdim          << Param0->getSourceRange() << Param0->getType()
5602249423Sdim          << Context.getLValueReferenceType(
5603249423Sdim               Context.getRecordType(RD).withConst());
5604249423Sdim      return false;
5605249423Sdim    }
5606249423Sdim    break;
5607249423Sdim  }
5608249423Sdim
5609249423Sdim  case CXXMoveConstructor:
5610249423Sdim  case CXXMoveAssignment: {
5611249423Sdim    // Trivial move operations always have non-cv-qualified parameters.
5612249423Sdim    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5613249423Sdim    const RValueReferenceType *RT =
5614249423Sdim      Param0->getType()->getAs<RValueReferenceType>();
5615249423Sdim    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5616249423Sdim      if (Diagnose)
5617249423Sdim        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5618249423Sdim          << Param0->getSourceRange() << Param0->getType()
5619249423Sdim          << Context.getRValueReferenceType(Context.getRecordType(RD));
5620249423Sdim      return false;
5621249423Sdim    }
5622249423Sdim    break;
5623249423Sdim  }
5624249423Sdim
5625249423Sdim  case CXXInvalid:
5626249423Sdim    llvm_unreachable("not a special member");
5627249423Sdim  }
5628249423Sdim
5629249423Sdim  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5630249423Sdim    if (Diagnose)
5631249423Sdim      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5632249423Sdim           diag::note_nontrivial_default_arg)
5633249423Sdim        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5634249423Sdim    return false;
5635249423Sdim  }
5636249423Sdim  if (MD->isVariadic()) {
5637249423Sdim    if (Diagnose)
5638249423Sdim      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5639249423Sdim    return false;
5640249423Sdim  }
5641249423Sdim
5642249423Sdim  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5643249423Sdim  //   A copy/move [constructor or assignment operator] is trivial if
5644249423Sdim  //    -- the [member] selected to copy/move each direct base class subobject
5645249423Sdim  //       is trivial
5646249423Sdim  //
5647249423Sdim  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5648249423Sdim  //   A [default constructor or destructor] is trivial if
5649249423Sdim  //    -- all the direct base classes have trivial [default constructors or
5650249423Sdim  //       destructors]
5651249423Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5652249423Sdim                                          BE = RD->bases_end(); BI != BE; ++BI)
5653249423Sdim    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5654249423Sdim                                   ConstArg ? BI->getType().withConst()
5655249423Sdim                                            : BI->getType(),
5656249423Sdim                                   CSM, TSK_BaseClass, Diagnose))
5657249423Sdim      return false;
5658249423Sdim
5659249423Sdim  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5660249423Sdim  //   A copy/move [constructor or assignment operator] for a class X is
5661249423Sdim  //   trivial if
5662249423Sdim  //    -- for each non-static data member of X that is of class type (or array
5663249423Sdim  //       thereof), the constructor selected to copy/move that member is
5664249423Sdim  //       trivial
5665249423Sdim  //
5666249423Sdim  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5667249423Sdim  //   A [default constructor or destructor] is trivial if
5668249423Sdim  //    -- for all of the non-static data members of its class that are of class
5669249423Sdim  //       type (or array thereof), each such class has a trivial [default
5670249423Sdim  //       constructor or destructor]
5671249423Sdim  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5672249423Sdim    return false;
5673249423Sdim
5674249423Sdim  // C++11 [class.dtor]p5:
5675249423Sdim  //   A destructor is trivial if [...]
5676249423Sdim  //    -- the destructor is not virtual
5677249423Sdim  if (CSM == CXXDestructor && MD->isVirtual()) {
5678249423Sdim    if (Diagnose)
5679249423Sdim      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5680249423Sdim    return false;
5681249423Sdim  }
5682249423Sdim
5683249423Sdim  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5684249423Sdim  //   A [special member] for class X is trivial if [...]
5685249423Sdim  //    -- class X has no virtual functions and no virtual base classes
5686249423Sdim  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5687249423Sdim    if (!Diagnose)
5688249423Sdim      return false;
5689249423Sdim
5690249423Sdim    if (RD->getNumVBases()) {
5691249423Sdim      // Check for virtual bases. We already know that the corresponding
5692249423Sdim      // member in all bases is trivial, so vbases must all be direct.
5693249423Sdim      CXXBaseSpecifier &BS = *RD->vbases_begin();
5694249423Sdim      assert(BS.isVirtual());
5695249423Sdim      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5696249423Sdim      return false;
5697249423Sdim    }
5698249423Sdim
5699249423Sdim    // Must have a virtual method.
5700249423Sdim    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5701249423Sdim                                        ME = RD->method_end(); MI != ME; ++MI) {
5702249423Sdim      if (MI->isVirtual()) {
5703249423Sdim        SourceLocation MLoc = MI->getLocStart();
5704249423Sdim        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5705249423Sdim        return false;
5706249423Sdim      }
5707249423Sdim    }
5708249423Sdim
5709249423Sdim    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5710249423Sdim  }
5711249423Sdim
5712249423Sdim  // Looks like it's trivial!
5713249423Sdim  return true;
5714249423Sdim}
5715249423Sdim
5716218893Sdim/// \brief Data used with FindHiddenVirtualMethod
5717221345Sdimnamespace {
5718221345Sdim  struct FindHiddenVirtualMethodData {
5719221345Sdim    Sema *S;
5720221345Sdim    CXXMethodDecl *Method;
5721221345Sdim    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5722226633Sdim    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5723221345Sdim  };
5724221345Sdim}
5725218893Sdim
5726243830Sdim/// \brief Check whether any most overriden method from MD in Methods
5727243830Sdimstatic bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5728243830Sdim                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5729243830Sdim  if (MD->size_overridden_methods() == 0)
5730243830Sdim    return Methods.count(MD->getCanonicalDecl());
5731243830Sdim  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5732243830Sdim                                      E = MD->end_overridden_methods();
5733243830Sdim       I != E; ++I)
5734243830Sdim    if (CheckMostOverridenMethods(*I, Methods))
5735243830Sdim      return true;
5736243830Sdim  return false;
5737243830Sdim}
5738243830Sdim
5739218893Sdim/// \brief Member lookup function that determines whether a given C++
5740218893Sdim/// method overloads virtual methods in a base class without overriding any,
5741218893Sdim/// to be used with CXXRecordDecl::lookupInBases().
5742218893Sdimstatic bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5743218893Sdim                                    CXXBasePath &Path,
5744218893Sdim                                    void *UserData) {
5745218893Sdim  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5746218893Sdim
5747218893Sdim  FindHiddenVirtualMethodData &Data
5748218893Sdim    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5749218893Sdim
5750218893Sdim  DeclarationName Name = Data.Method->getDeclName();
5751218893Sdim  assert(Name.getNameKind() == DeclarationName::Identifier);
5752218893Sdim
5753218893Sdim  bool foundSameNameMethod = false;
5754226633Sdim  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5755218893Sdim  for (Path.Decls = BaseRecord->lookup(Name);
5756249423Sdim       !Path.Decls.empty();
5757249423Sdim       Path.Decls = Path.Decls.slice(1)) {
5758249423Sdim    NamedDecl *D = Path.Decls.front();
5759218893Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5760218893Sdim      MD = MD->getCanonicalDecl();
5761218893Sdim      foundSameNameMethod = true;
5762218893Sdim      // Interested only in hidden virtual methods.
5763218893Sdim      if (!MD->isVirtual())
5764218893Sdim        continue;
5765218893Sdim      // If the method we are checking overrides a method from its base
5766218893Sdim      // don't warn about the other overloaded methods.
5767218893Sdim      if (!Data.S->IsOverload(Data.Method, MD, false))
5768218893Sdim        return true;
5769218893Sdim      // Collect the overload only if its hidden.
5770243830Sdim      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5771218893Sdim        overloadedMethods.push_back(MD);
5772218893Sdim    }
5773218893Sdim  }
5774218893Sdim
5775218893Sdim  if (foundSameNameMethod)
5776218893Sdim    Data.OverloadedMethods.append(overloadedMethods.begin(),
5777218893Sdim                                   overloadedMethods.end());
5778218893Sdim  return foundSameNameMethod;
5779218893Sdim}
5780218893Sdim
5781243830Sdim/// \brief Add the most overriden methods from MD to Methods
5782243830Sdimstatic void AddMostOverridenMethods(const CXXMethodDecl *MD,
5783243830Sdim                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5784243830Sdim  if (MD->size_overridden_methods() == 0)
5785243830Sdim    Methods.insert(MD->getCanonicalDecl());
5786243830Sdim  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5787243830Sdim                                      E = MD->end_overridden_methods();
5788243830Sdim       I != E; ++I)
5789243830Sdim    AddMostOverridenMethods(*I, Methods);
5790243830Sdim}
5791243830Sdim
5792263508Sdim/// \brief Check if a method overloads virtual methods in a base class without
5793218893Sdim/// overriding any.
5794263508Sdimvoid Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5795263508Sdim                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5796239462Sdim  if (!MD->getDeclName().isIdentifier())
5797218893Sdim    return;
5798218893Sdim
5799218893Sdim  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5800218893Sdim                     /*bool RecordPaths=*/false,
5801218893Sdim                     /*bool DetectVirtual=*/false);
5802218893Sdim  FindHiddenVirtualMethodData Data;
5803218893Sdim  Data.Method = MD;
5804218893Sdim  Data.S = this;
5805218893Sdim
5806218893Sdim  // Keep the base methods that were overriden or introduced in the subclass
5807218893Sdim  // by 'using' in a set. A base method not in this set is hidden.
5808263508Sdim  CXXRecordDecl *DC = MD->getParent();
5809249423Sdim  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5810249423Sdim  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5811249423Sdim    NamedDecl *ND = *I;
5812249423Sdim    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5813243830Sdim      ND = shad->getTargetDecl();
5814243830Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5815243830Sdim      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5816218893Sdim  }
5817218893Sdim
5818263508Sdim  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5819263508Sdim    OverloadedMethods = Data.OverloadedMethods;
5820263508Sdim}
5821263508Sdim
5822263508Sdimvoid Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5823263508Sdim                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5824263508Sdim  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5825263508Sdim    CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5826263508Sdim    PartialDiagnostic PD = PDiag(
5827263508Sdim         diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5828263508Sdim    HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5829263508Sdim    Diag(overloadedMD->getLocation(), PD);
5830263508Sdim  }
5831263508Sdim}
5832263508Sdim
5833263508Sdim/// \brief Diagnose methods which overload virtual methods in a base class
5834263508Sdim/// without overriding any.
5835263508Sdimvoid Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5836263508Sdim  if (MD->isInvalidDecl())
5837263508Sdim    return;
5838263508Sdim
5839263508Sdim  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5840263508Sdim                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5841263508Sdim    return;
5842263508Sdim
5843263508Sdim  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5844263508Sdim  FindHiddenVirtualMethods(MD, OverloadedMethods);
5845263508Sdim  if (!OverloadedMethods.empty()) {
5846218893Sdim    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5847263508Sdim      << MD << (OverloadedMethods.size() > 1);
5848218893Sdim
5849263508Sdim    NoteHiddenVirtualMethods(MD, OverloadedMethods);
5850218893Sdim  }
5851218893Sdim}
5852218893Sdim
5853193326Sedvoid Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5854212904Sdim                                             Decl *TagDecl,
5855193326Sed                                             SourceLocation LBrac,
5856206084Srdivacky                                             SourceLocation RBrac,
5857206084Srdivacky                                             AttributeList *AttrList) {
5858194711Sed  if (!TagDecl)
5859194711Sed    return;
5860198092Srdivacky
5861193326Sed  AdjustDeclIfTemplate(TagDecl);
5862200583Srdivacky
5863239462Sdim  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5864239462Sdim    if (l->getKind() != AttributeList::AT_Visibility)
5865239462Sdim      continue;
5866239462Sdim    l->setInvalid();
5867239462Sdim    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5868239462Sdim      l->getName();
5869239462Sdim  }
5870239462Sdim
5871226633Sdim  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5872212904Sdim              // strict aliasing violation!
5873212904Sdim              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5874226633Sdim              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5875193326Sed
5876210299Sed  CheckCompletedCXXClass(
5877212904Sdim                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5878193326Sed}
5879193326Sed
5880193326Sed/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5881193326Sed/// special functions, such as the default constructor, copy
5882193326Sed/// constructor, or destructor, to the given C++ class (C++
5883193326Sed/// [special]p1).  This routine can only be executed just before the
5884193326Sed/// definition of the class is complete.
5885210299Sedvoid Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5886210299Sed  if (!ClassDecl->hasUserDeclaredConstructor())
5887210299Sed    ++ASTContext::NumImplicitDefaultConstructors;
5888193326Sed
5889249423Sdim  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5890210299Sed    ++ASTContext::NumImplicitCopyConstructors;
5891193326Sed
5892249423Sdim    // If the properties or semantics of the copy constructor couldn't be
5893249423Sdim    // determined while the class was being declared, force a declaration
5894249423Sdim    // of it now.
5895249423Sdim    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5896249423Sdim      DeclareImplicitCopyConstructor(ClassDecl);
5897249423Sdim  }
5898249423Sdim
5899249423Sdim  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5900234353Sdim    ++ASTContext::NumImplicitMoveConstructors;
5901234353Sdim
5902249423Sdim    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5903249423Sdim      DeclareImplicitMoveConstructor(ClassDecl);
5904249423Sdim  }
5905249423Sdim
5906193326Sed  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5907210299Sed    ++ASTContext::NumImplicitCopyAssignmentOperators;
5908249423Sdim
5909249423Sdim    // If we have a dynamic class, then the copy assignment operator may be
5910210299Sed    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5911249423Sdim    // it shows up in the right place in the vtable and that we diagnose
5912249423Sdim    // problems with the implicit exception specification.
5913249423Sdim    if (ClassDecl->isDynamicClass() ||
5914249423Sdim        ClassDecl->needsOverloadResolutionForCopyAssignment())
5915210299Sed      DeclareImplicitCopyAssignment(ClassDecl);
5916193326Sed  }
5917193326Sed
5918249423Sdim  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5919234353Sdim    ++ASTContext::NumImplicitMoveAssignmentOperators;
5920234353Sdim
5921234353Sdim    // Likewise for the move assignment operator.
5922249423Sdim    if (ClassDecl->isDynamicClass() ||
5923249423Sdim        ClassDecl->needsOverloadResolutionForMoveAssignment())
5924234353Sdim      DeclareImplicitMoveAssignment(ClassDecl);
5925234353Sdim  }
5926234353Sdim
5927193326Sed  if (!ClassDecl->hasUserDeclaredDestructor()) {
5928210299Sed    ++ASTContext::NumImplicitDestructors;
5929249423Sdim
5930249423Sdim    // If we have a dynamic class, then the destructor may be virtual, so we
5931210299Sed    // have to declare the destructor immediately. This ensures that, e.g., it
5932210299Sed    // shows up in the right place in the vtable and that we diagnose problems
5933210299Sed    // with the implicit exception specification.
5934249423Sdim    if (ClassDecl->isDynamicClass() ||
5935249423Sdim        ClassDecl->needsOverloadResolutionForDestructor())
5936210299Sed      DeclareImplicitDestructor(ClassDecl);
5937193326Sed  }
5938193326Sed}
5939193326Sed
5940221345Sdimvoid Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5941221345Sdim  if (!D)
5942221345Sdim    return;
5943221345Sdim
5944221345Sdim  int NumParamList = D->getNumTemplateParameterLists();
5945221345Sdim  for (int i = 0; i < NumParamList; i++) {
5946221345Sdim    TemplateParameterList* Params = D->getTemplateParameterList(i);
5947221345Sdim    for (TemplateParameterList::iterator Param = Params->begin(),
5948221345Sdim                                      ParamEnd = Params->end();
5949221345Sdim          Param != ParamEnd; ++Param) {
5950221345Sdim      NamedDecl *Named = cast<NamedDecl>(*Param);
5951221345Sdim      if (Named->getDeclName()) {
5952221345Sdim        S->AddDecl(Named);
5953221345Sdim        IdResolver.AddDecl(Named);
5954221345Sdim      }
5955221345Sdim    }
5956221345Sdim  }
5957221345Sdim}
5958221345Sdim
5959212904Sdimvoid Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5960198092Srdivacky  if (!D)
5961193326Sed    return;
5962198092Srdivacky
5963198092Srdivacky  TemplateParameterList *Params = 0;
5964198092Srdivacky  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5965198092Srdivacky    Params = Template->getTemplateParameters();
5966198092Srdivacky  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5967198092Srdivacky           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5968198092Srdivacky    Params = PartialSpec->getTemplateParameters();
5969198092Srdivacky  else
5970198092Srdivacky    return;
5971193326Sed
5972193326Sed  for (TemplateParameterList::iterator Param = Params->begin(),
5973193326Sed                                    ParamEnd = Params->end();
5974193326Sed       Param != ParamEnd; ++Param) {
5975193326Sed    NamedDecl *Named = cast<NamedDecl>(*Param);
5976193326Sed    if (Named->getDeclName()) {
5977212904Sdim      S->AddDecl(Named);
5978193326Sed      IdResolver.AddDecl(Named);
5979193326Sed    }
5980193326Sed  }
5981193326Sed}
5982193326Sed
5983212904Sdimvoid Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5984201361Srdivacky  if (!RecordD) return;
5985201361Srdivacky  AdjustDeclIfTemplate(RecordD);
5986212904Sdim  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5987201361Srdivacky  PushDeclContext(S, Record);
5988201361Srdivacky}
5989201361Srdivacky
5990212904Sdimvoid Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5991201361Srdivacky  if (!RecordD) return;
5992201361Srdivacky  PopDeclContext();
5993201361Srdivacky}
5994201361Srdivacky
5995193326Sed/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5996193326Sed/// parsing a top-level (non-nested) C++ class, and we are now
5997193326Sed/// parsing those parts of the given Method declaration that could
5998193326Sed/// not be parsed earlier (C++ [class.mem]p2), such as default
5999193326Sed/// arguments. This action should enter the scope of the given
6000193326Sed/// Method declaration as if we had just parsed the qualified method
6001193326Sed/// name. However, it should not bring the parameters into scope;
6002193326Sed/// that will be performed by ActOnDelayedCXXMethodParameter.
6003212904Sdimvoid Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6004193326Sed}
6005193326Sed
6006193326Sed/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6007193326Sed/// C++ method declaration. We're (re-)introducing the given
6008193326Sed/// function parameter into scope for use in parsing later parts of
6009193326Sed/// the method declaration. For example, we could see an
6010193326Sed/// ActOnParamDefaultArgument event for this parameter.
6011212904Sdimvoid Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6012194711Sed  if (!ParamD)
6013194711Sed    return;
6014198092Srdivacky
6015212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6016193326Sed
6017193326Sed  // If this parameter has an unparsed default argument, clear it out
6018193326Sed  // to make way for the parsed default argument.
6019193326Sed  if (Param->hasUnparsedDefaultArg())
6020193326Sed    Param->setDefaultArg(0);
6021193326Sed
6022212904Sdim  S->AddDecl(Param);
6023193326Sed  if (Param->getDeclName())
6024193326Sed    IdResolver.AddDecl(Param);
6025193326Sed}
6026193326Sed
6027193326Sed/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6028193326Sed/// processing the delayed method declaration for Method. The method
6029193326Sed/// declaration is now considered finished. There may be a separate
6030193326Sed/// ActOnStartOfFunctionDef action later (not necessarily
6031193326Sed/// immediately!) for this method, if it was also defined inside the
6032193326Sed/// class body.
6033212904Sdimvoid Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6034194711Sed  if (!MethodD)
6035194711Sed    return;
6036198092Srdivacky
6037198092Srdivacky  AdjustDeclIfTemplate(MethodD);
6038198092Srdivacky
6039212904Sdim  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6040193326Sed
6041193326Sed  // Now that we have our default arguments, check the constructor
6042193326Sed  // again. It could produce additional diagnostics or affect whether
6043193326Sed  // the class has implicitly-declared destructors, among other
6044193326Sed  // things.
6045193326Sed  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6046193326Sed    CheckConstructor(Constructor);
6047193326Sed
6048193326Sed  // Check the default arguments, which we may have added.
6049193326Sed  if (!Method->isInvalidDecl())
6050193326Sed    CheckCXXDefaultArguments(Method);
6051193326Sed}
6052193326Sed
6053193326Sed/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6054193326Sed/// the well-formedness of the constructor declarator @p D with type @p
6055193326Sed/// R. If there are any errors in the declarator, this routine will
6056193326Sed/// emit diagnostics and set the invalid bit to true.  In any case, the type
6057193326Sed/// will be updated to reflect a well-formed type for the constructor and
6058193326Sed/// returned.
6059193326SedQualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6060212904Sdim                                          StorageClass &SC) {
6061193326Sed  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6062193326Sed
6063193326Sed  // C++ [class.ctor]p3:
6064193326Sed  //   A constructor shall not be virtual (10.3) or static (9.4). A
6065193326Sed  //   constructor can be invoked for a const, volatile or const
6066193326Sed  //   volatile object. A constructor shall not be declared const,
6067193326Sed  //   volatile, or const volatile (9.3.2).
6068193326Sed  if (isVirtual) {
6069193326Sed    if (!D.isInvalidType())
6070193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6071193326Sed        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6072193326Sed        << SourceRange(D.getIdentifierLoc());
6073193326Sed    D.setInvalidType();
6074193326Sed  }
6075212904Sdim  if (SC == SC_Static) {
6076193326Sed    if (!D.isInvalidType())
6077193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6078193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6079193326Sed        << SourceRange(D.getIdentifierLoc());
6080193326Sed    D.setInvalidType();
6081212904Sdim    SC = SC_None;
6082193326Sed  }
6083198092Srdivacky
6084218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6085193326Sed  if (FTI.TypeQuals != 0) {
6086198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Const)
6087193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6088193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
6089198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Volatile)
6090193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6091193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
6092198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Restrict)
6093193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6094193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
6095218893Sdim    D.setInvalidType();
6096193326Sed  }
6097198092Srdivacky
6098218893Sdim  // C++0x [class.ctor]p4:
6099218893Sdim  //   A constructor shall not be declared with a ref-qualifier.
6100218893Sdim  if (FTI.hasRefQualifier()) {
6101218893Sdim    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6102218893Sdim      << FTI.RefQualifierIsLValueRef
6103218893Sdim      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6104218893Sdim    D.setInvalidType();
6105218893Sdim  }
6106218893Sdim
6107193326Sed  // Rebuild the function type "R" without any type qualifiers (in
6108193326Sed  // case any of the errors above fired) and with "void" as the
6109210299Sed  // return type, since constructors don't have return types.
6110198092Srdivacky  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6111218893Sdim  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6112218893Sdim    return R;
6113218893Sdim
6114218893Sdim  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6115218893Sdim  EPI.TypeQuals = 0;
6116218893Sdim  EPI.RefQualifier = RQ_None;
6117218893Sdim
6118249423Sdim  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
6119193326Sed}
6120193326Sed
6121193326Sed/// CheckConstructor - Checks a fully-formed constructor for
6122193326Sed/// well-formedness, issuing any diagnostics required. Returns true if
6123193326Sed/// the constructor declarator is invalid.
6124193326Sedvoid Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6125198092Srdivacky  CXXRecordDecl *ClassDecl
6126193326Sed    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6127193326Sed  if (!ClassDecl)
6128193326Sed    return Constructor->setInvalidDecl();
6129193326Sed
6130193326Sed  // C++ [class.copy]p3:
6131193326Sed  //   A declaration of a constructor for a class X is ill-formed if
6132193326Sed  //   its first parameter is of type (optionally cv-qualified) X and
6133193326Sed  //   either there are no other parameters or else all other
6134193326Sed  //   parameters have default arguments.
6135193326Sed  if (!Constructor->isInvalidDecl() &&
6136198092Srdivacky      ((Constructor->getNumParams() == 1) ||
6137198092Srdivacky       (Constructor->getNumParams() > 1 &&
6138199482Srdivacky        Constructor->getParamDecl(1)->hasDefaultArg())) &&
6139199482Srdivacky      Constructor->getTemplateSpecializationKind()
6140199482Srdivacky                                              != TSK_ImplicitInstantiation) {
6141193326Sed    QualType ParamType = Constructor->getParamDecl(0)->getType();
6142193326Sed    QualType ClassTy = Context.getTagDeclType(ClassDecl);
6143193326Sed    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6144193326Sed      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6145210299Sed      const char *ConstRef
6146210299Sed        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6147210299Sed                                                        : " const &";
6148193326Sed      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6149210299Sed        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6150199482Srdivacky
6151199482Srdivacky      // FIXME: Rather that making the constructor invalid, we should endeavor
6152199482Srdivacky      // to fix the type.
6153193326Sed      Constructor->setInvalidDecl();
6154193326Sed    }
6155193326Sed  }
6156193326Sed}
6157193326Sed
6158212904Sdim/// CheckDestructor - Checks a fully-formed destructor definition for
6159212904Sdim/// well-formedness, issuing any diagnostics required.  Returns true
6160212904Sdim/// on error.
6161199990Srdivackybool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6162199482Srdivacky  CXXRecordDecl *RD = Destructor->getParent();
6163199482Srdivacky
6164263508Sdim  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6165199482Srdivacky    SourceLocation Loc;
6166199482Srdivacky
6167199482Srdivacky    if (!Destructor->isImplicit())
6168199482Srdivacky      Loc = Destructor->getLocation();
6169199482Srdivacky    else
6170199482Srdivacky      Loc = RD->getLocation();
6171199482Srdivacky
6172199482Srdivacky    // If we have a virtual destructor, look up the deallocation function
6173199482Srdivacky    FunctionDecl *OperatorDelete = 0;
6174199482Srdivacky    DeclarationName Name =
6175199482Srdivacky    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6176199990Srdivacky    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6177199990Srdivacky      return true;
6178263508Sdim    // If there's no class-specific operator delete, look up the global
6179263508Sdim    // non-array delete.
6180263508Sdim    if (!OperatorDelete)
6181263508Sdim      OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6182210299Sed
6183234353Sdim    MarkFunctionReferenced(Loc, OperatorDelete);
6184199990Srdivacky
6185199990Srdivacky    Destructor->setOperatorDelete(OperatorDelete);
6186199482Srdivacky  }
6187199990Srdivacky
6188199990Srdivacky  return false;
6189199482Srdivacky}
6190199482Srdivacky
6191198092Srdivackystatic inline bool
6192193326SedFTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6193193326Sed  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6194193326Sed          FTI.ArgInfo[0].Param &&
6195212904Sdim          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
6196193326Sed}
6197193326Sed
6198193326Sed/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6199193326Sed/// the well-formednes of the destructor declarator @p D with type @p
6200193326Sed/// R. If there are any errors in the declarator, this routine will
6201193326Sed/// emit diagnostics and set the declarator to invalid.  Even if this happens,
6202193326Sed/// will be updated to reflect a well-formed type for the destructor and
6203193326Sed/// returned.
6204210299SedQualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6205212904Sdim                                         StorageClass& SC) {
6206193326Sed  // C++ [class.dtor]p1:
6207193326Sed  //   [...] A typedef-name that names a class is a class-name
6208193326Sed  //   (7.1.3); however, a typedef-name that names a class shall not
6209193326Sed  //   be used as the identifier in the declarator for a destructor
6210193326Sed  //   declaration.
6211198893Srdivacky  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6212221345Sdim  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6213193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6214221345Sdim      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6215223017Sdim  else if (const TemplateSpecializationType *TST =
6216223017Sdim             DeclaratorType->getAs<TemplateSpecializationType>())
6217223017Sdim    if (TST->isTypeAlias())
6218223017Sdim      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6219223017Sdim        << DeclaratorType << 1;
6220193326Sed
6221193326Sed  // C++ [class.dtor]p2:
6222193326Sed  //   A destructor is used to destroy objects of its class type. A
6223193326Sed  //   destructor takes no parameters, and no return type can be
6224193326Sed  //   specified for it (not even void). The address of a destructor
6225193326Sed  //   shall not be taken. A destructor shall not be static. A
6226193326Sed  //   destructor can be invoked for a const, volatile or const
6227193326Sed  //   volatile object. A destructor shall not be declared const,
6228193326Sed  //   volatile or const volatile (9.3.2).
6229212904Sdim  if (SC == SC_Static) {
6230193326Sed    if (!D.isInvalidType())
6231193326Sed      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6232193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6233210299Sed        << SourceRange(D.getIdentifierLoc())
6234210299Sed        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6235210299Sed
6236212904Sdim    SC = SC_None;
6237193326Sed  }
6238193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6239193326Sed    // Destructors don't have return types, but the parser will
6240193326Sed    // happily parse something like:
6241193326Sed    //
6242193326Sed    //   class X {
6243193326Sed    //     float ~X();
6244193326Sed    //   };
6245193326Sed    //
6246193326Sed    // The return type will be eliminated later.
6247193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6248193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6249193326Sed      << SourceRange(D.getIdentifierLoc());
6250193326Sed  }
6251198092Srdivacky
6252218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6253193326Sed  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6254198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Const)
6255193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6256193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
6257198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Volatile)
6258193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6259193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
6260198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Restrict)
6261193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6262193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
6263193326Sed    D.setInvalidType();
6264193326Sed  }
6265193326Sed
6266218893Sdim  // C++0x [class.dtor]p2:
6267218893Sdim  //   A destructor shall not be declared with a ref-qualifier.
6268218893Sdim  if (FTI.hasRefQualifier()) {
6269218893Sdim    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6270218893Sdim      << FTI.RefQualifierIsLValueRef
6271218893Sdim      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6272218893Sdim    D.setInvalidType();
6273218893Sdim  }
6274218893Sdim
6275193326Sed  // Make sure we don't have any parameters.
6276193326Sed  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6277193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6278193326Sed
6279193326Sed    // Delete the parameters.
6280193326Sed    FTI.freeArgs();
6281193326Sed    D.setInvalidType();
6282193326Sed  }
6283193326Sed
6284198092Srdivacky  // Make sure the destructor isn't variadic.
6285193326Sed  if (FTI.isVariadic) {
6286193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6287193326Sed    D.setInvalidType();
6288193326Sed  }
6289193326Sed
6290193326Sed  // Rebuild the function type "R" without any type qualifiers or
6291193326Sed  // parameters (in case any of the errors above fired) and with
6292193326Sed  // "void" as the return type, since destructors don't have return
6293210299Sed  // types.
6294218893Sdim  if (!D.isInvalidType())
6295218893Sdim    return R;
6296218893Sdim
6297210299Sed  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6298218893Sdim  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6299218893Sdim  EPI.Variadic = false;
6300218893Sdim  EPI.TypeQuals = 0;
6301218893Sdim  EPI.RefQualifier = RQ_None;
6302251662Sdim  return Context.getFunctionType(Context.VoidTy, None, EPI);
6303193326Sed}
6304193326Sed
6305193326Sed/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6306193326Sed/// well-formednes of the conversion function declarator @p D with
6307193326Sed/// type @p R. If there are any errors in the declarator, this routine
6308193326Sed/// will emit diagnostics and return true. Otherwise, it will return
6309193326Sed/// false. Either way, the type @p R will be updated to reflect a
6310193326Sed/// well-formed type for the conversion operator.
6311193326Sedvoid Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6312212904Sdim                                     StorageClass& SC) {
6313193326Sed  // C++ [class.conv.fct]p1:
6314193326Sed  //   Neither parameter types nor return type can be specified. The
6315198092Srdivacky  //   type of a conversion function (8.3.5) is "function taking no
6316198092Srdivacky  //   parameter returning conversion-type-id."
6317212904Sdim  if (SC == SC_Static) {
6318193326Sed    if (!D.isInvalidType())
6319193326Sed      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6320263508Sdim        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6321263508Sdim        << D.getName().getSourceRange();
6322193326Sed    D.setInvalidType();
6323212904Sdim    SC = SC_None;
6324193326Sed  }
6325207619Srdivacky
6326207619Srdivacky  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6327207619Srdivacky
6328193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6329193326Sed    // Conversion functions don't have return types, but the parser will
6330193326Sed    // happily parse something like:
6331193326Sed    //
6332193326Sed    //   class X {
6333193326Sed    //     float operator bool();
6334193326Sed    //   };
6335193326Sed    //
6336193326Sed    // The return type will be changed later anyway.
6337193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6338193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6339193326Sed      << SourceRange(D.getIdentifierLoc());
6340207619Srdivacky    D.setInvalidType();
6341193326Sed  }
6342193326Sed
6343207619Srdivacky  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6344207619Srdivacky
6345193326Sed  // Make sure we don't have any parameters.
6346207619Srdivacky  if (Proto->getNumArgs() > 0) {
6347193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6348193326Sed
6349193326Sed    // Delete the parameters.
6350218893Sdim    D.getFunctionTypeInfo().freeArgs();
6351193326Sed    D.setInvalidType();
6352207619Srdivacky  } else if (Proto->isVariadic()) {
6353207619Srdivacky    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6354207619Srdivacky    D.setInvalidType();
6355193326Sed  }
6356193326Sed
6357207619Srdivacky  // Diagnose "&operator bool()" and other such nonsense.  This
6358207619Srdivacky  // is actually a gcc extension which we don't support.
6359207619Srdivacky  if (Proto->getResultType() != ConvType) {
6360207619Srdivacky    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6361207619Srdivacky      << Proto->getResultType();
6362193326Sed    D.setInvalidType();
6363207619Srdivacky    ConvType = Proto->getResultType();
6364193326Sed  }
6365193326Sed
6366193326Sed  // C++ [class.conv.fct]p4:
6367193326Sed  //   The conversion-type-id shall not represent a function type nor
6368193326Sed  //   an array type.
6369193326Sed  if (ConvType->isArrayType()) {
6370193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6371193326Sed    ConvType = Context.getPointerType(ConvType);
6372193326Sed    D.setInvalidType();
6373193326Sed  } else if (ConvType->isFunctionType()) {
6374193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6375193326Sed    ConvType = Context.getPointerType(ConvType);
6376193326Sed    D.setInvalidType();
6377193326Sed  }
6378193326Sed
6379193326Sed  // Rebuild the function type "R" without any parameters (in case any
6380193326Sed  // of the errors above fired) and with the conversion type as the
6381198092Srdivacky  // return type.
6382218893Sdim  if (D.isInvalidType())
6383251662Sdim    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6384193326Sed
6385193326Sed  // C++0x explicit conversion operators.
6386234353Sdim  if (D.getDeclSpec().isExplicitSpecified())
6387198092Srdivacky    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6388249423Sdim         getLangOpts().CPlusPlus11 ?
6389234353Sdim           diag::warn_cxx98_compat_explicit_conversion_functions :
6390234353Sdim           diag::ext_explicit_conversion_functions)
6391193326Sed      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6392193326Sed}
6393193326Sed
6394193326Sed/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6395193326Sed/// the declaration of the given C++ conversion function. This routine
6396193326Sed/// is responsible for recording the conversion function in the C++
6397193326Sed/// class, if possible.
6398212904SdimDecl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6399193326Sed  assert(Conversion && "Expected to receive a conversion function declaration");
6400193326Sed
6401193326Sed  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6402193326Sed
6403193326Sed  // Make sure we aren't redeclaring the conversion function.
6404193326Sed  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6405193326Sed
6406193326Sed  // C++ [class.conv.fct]p1:
6407193326Sed  //   [...] A conversion function is never used to convert a
6408193326Sed  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6409193326Sed  //   same object type (or a reference to it), to a (possibly
6410193326Sed  //   cv-qualified) base class of that type (or a reference to it),
6411193326Sed  //   or to (possibly cv-qualified) void.
6412193326Sed  // FIXME: Suppress this warning if the conversion function ends up being a
6413193326Sed  // virtual function that overrides a virtual function in a base class.
6414198092Srdivacky  QualType ClassType
6415193326Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6416198092Srdivacky  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6417193326Sed    ConvType = ConvTypeRef->getPointeeType();
6418218893Sdim  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6419218893Sdim      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6420218893Sdim    /* Suppress diagnostics for instantiations. */;
6421218893Sdim  else if (ConvType->isRecordType()) {
6422193326Sed    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6423193326Sed    if (ConvType == ClassType)
6424193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6425193326Sed        << ClassType;
6426193326Sed    else if (IsDerivedFrom(ClassType, ConvType))
6427193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6428193326Sed        <<  ClassType << ConvType;
6429193326Sed  } else if (ConvType->isVoidType()) {
6430193326Sed    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6431193326Sed      << ClassType << ConvType;
6432193326Sed  }
6433193326Sed
6434218893Sdim  if (FunctionTemplateDecl *ConversionTemplate
6435218893Sdim                                = Conversion->getDescribedFunctionTemplate())
6436218893Sdim    return ConversionTemplate;
6437218893Sdim
6438212904Sdim  return Conversion;
6439193326Sed}
6440193326Sed
6441193326Sed//===----------------------------------------------------------------------===//
6442193326Sed// Namespace Handling
6443193326Sed//===----------------------------------------------------------------------===//
6444193326Sed
6445243830Sdim/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6446243830Sdim/// reopened.
6447243830Sdimstatic void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6448243830Sdim                                            SourceLocation Loc,
6449243830Sdim                                            IdentifierInfo *II, bool *IsInline,
6450243830Sdim                                            NamespaceDecl *PrevNS) {
6451243830Sdim  assert(*IsInline != PrevNS->isInline());
6452212904Sdim
6453243830Sdim  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6454243830Sdim  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6455243830Sdim  // inline namespaces, with the intention of bringing names into namespace std.
6456243830Sdim  //
6457243830Sdim  // We support this just well enough to get that case working; this is not
6458243830Sdim  // sufficient to support reopening namespaces as inline in general.
6459243830Sdim  if (*IsInline && II && II->getName().startswith("__atomic") &&
6460243830Sdim      S.getSourceManager().isInSystemHeader(Loc)) {
6461243830Sdim    // Mark all prior declarations of the namespace as inline.
6462243830Sdim    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6463243830Sdim         NS = NS->getPreviousDecl())
6464243830Sdim      NS->setInline(*IsInline);
6465243830Sdim    // Patch up the lookup table for the containing namespace. This isn't really
6466243830Sdim    // correct, but it's good enough for this particular case.
6467243830Sdim    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6468243830Sdim                                    E = PrevNS->decls_end(); I != E; ++I)
6469243830Sdim      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6470243830Sdim        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6471243830Sdim    return;
6472243830Sdim  }
6473212904Sdim
6474243830Sdim  if (PrevNS->isInline())
6475243830Sdim    // The user probably just forgot the 'inline', so suggest that it
6476243830Sdim    // be added back.
6477243830Sdim    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6478243830Sdim      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6479243830Sdim  else
6480243830Sdim    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6481243830Sdim      << IsInline;
6482243830Sdim
6483243830Sdim  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6484243830Sdim  *IsInline = PrevNS->isInline();
6485243830Sdim}
6486243830Sdim
6487193326Sed/// ActOnStartNamespaceDef - This is called at the start of a namespace
6488193326Sed/// definition.
6489212904SdimDecl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6490212904Sdim                                   SourceLocation InlineLoc,
6491221345Sdim                                   SourceLocation NamespaceLoc,
6492212904Sdim                                   SourceLocation IdentLoc,
6493212904Sdim                                   IdentifierInfo *II,
6494212904Sdim                                   SourceLocation LBrace,
6495212904Sdim                                   AttributeList *AttrList) {
6496221345Sdim  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6497221345Sdim  // For anonymous namespace, take the location of the left brace.
6498221345Sdim  SourceLocation Loc = II ? IdentLoc : LBrace;
6499234353Sdim  bool IsInline = InlineLoc.isValid();
6500234353Sdim  bool IsInvalid = false;
6501234353Sdim  bool IsStd = false;
6502234353Sdim  bool AddToKnown = false;
6503193326Sed  Scope *DeclRegionScope = NamespcScope->getParent();
6504193326Sed
6505234353Sdim  NamespaceDecl *PrevNS = 0;
6506193326Sed  if (II) {
6507193326Sed    // C++ [namespace.def]p2:
6508218893Sdim    //   The identifier in an original-namespace-definition shall not
6509218893Sdim    //   have been previously defined in the declarative region in
6510218893Sdim    //   which the original-namespace-definition appears. The
6511218893Sdim    //   identifier in an original-namespace-definition is the name of
6512218893Sdim    //   the namespace. Subsequently in that declarative region, it is
6513218893Sdim    //   treated as an original-namespace-name.
6514218893Sdim    //
6515218893Sdim    // Since namespace names are unique in their scope, and we don't
6516223017Sdim    // look through using directives, just look for any ordinary names.
6517223017Sdim
6518223017Sdim    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6519234353Sdim    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6520234353Sdim    Decl::IDNS_Namespace;
6521223017Sdim    NamedDecl *PrevDecl = 0;
6522249423Sdim    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6523249423Sdim    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6524249423Sdim         ++I) {
6525249423Sdim      if ((*I)->getIdentifierNamespace() & IDNS) {
6526249423Sdim        PrevDecl = *I;
6527223017Sdim        break;
6528223017Sdim      }
6529223017Sdim    }
6530223017Sdim
6531234353Sdim    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6532234353Sdim
6533234353Sdim    if (PrevNS) {
6534193326Sed      // This is an extended namespace definition.
6535243830Sdim      if (IsInline != PrevNS->isInline())
6536243830Sdim        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6537243830Sdim                                        &IsInline, PrevNS);
6538193326Sed    } else if (PrevDecl) {
6539193326Sed      // This is an invalid name redefinition.
6540234353Sdim      Diag(Loc, diag::err_redefinition_different_kind)
6541234353Sdim        << II;
6542193326Sed      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6543234353Sdim      IsInvalid = true;
6544193326Sed      // Continue on to push Namespc as current DeclContext and return it.
6545234353Sdim    } else if (II->isStr("std") &&
6546212904Sdim               CurContext->getRedeclContext()->isTranslationUnit()) {
6547198092Srdivacky      // This is the first "real" definition of the namespace "std", so update
6548198092Srdivacky      // our cache of the "std" namespace to point at this definition.
6549234353Sdim      PrevNS = getStdNamespace();
6550234353Sdim      IsStd = true;
6551234353Sdim      AddToKnown = !IsInline;
6552234353Sdim    } else {
6553234353Sdim      // We've seen this namespace for the first time.
6554234353Sdim      AddToKnown = !IsInline;
6555234353Sdim    }
6556234353Sdim  } else {
6557234353Sdim    // Anonymous namespaces.
6558234353Sdim
6559234353Sdim    // Determine whether the parent already has an anonymous namespace.
6560234353Sdim    DeclContext *Parent = CurContext->getRedeclContext();
6561234353Sdim    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6562234353Sdim      PrevNS = TU->getAnonymousNamespace();
6563234353Sdim    } else {
6564234353Sdim      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6565234353Sdim      PrevNS = ND->getAnonymousNamespace();
6566234353Sdim    }
6567234353Sdim
6568243830Sdim    if (PrevNS && IsInline != PrevNS->isInline())
6569243830Sdim      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6570243830Sdim                                      &IsInline, PrevNS);
6571234353Sdim  }
6572234353Sdim
6573234353Sdim  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6574234353Sdim                                                 StartLoc, Loc, II, PrevNS);
6575234353Sdim  if (IsInvalid)
6576234353Sdim    Namespc->setInvalidDecl();
6577234353Sdim
6578234353Sdim  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6579193326Sed
6580234353Sdim  // FIXME: Should we be merging attributes?
6581234353Sdim  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6582234353Sdim    PushNamespaceVisibilityAttr(Attr, Loc);
6583234353Sdim
6584234353Sdim  if (IsStd)
6585234353Sdim    StdNamespace = Namespc;
6586234353Sdim  if (AddToKnown)
6587234353Sdim    KnownNamespaces[Namespc] = false;
6588234353Sdim
6589234353Sdim  if (II) {
6590193326Sed    PushOnScopeChains(Namespc, DeclRegionScope);
6591193326Sed  } else {
6592201361Srdivacky    // Link the anonymous namespace into its parent.
6593212904Sdim    DeclContext *Parent = CurContext->getRedeclContext();
6594201361Srdivacky    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6595201361Srdivacky      TU->setAnonymousNamespace(Namespc);
6596201361Srdivacky    } else {
6597234353Sdim      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6598201361Srdivacky    }
6599201361Srdivacky
6600206084Srdivacky    CurContext->addDecl(Namespc);
6601206084Srdivacky
6602198092Srdivacky    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6603198092Srdivacky    //   behaves as if it were replaced by
6604198092Srdivacky    //     namespace unique { /* empty body */ }
6605198092Srdivacky    //     using namespace unique;
6606198092Srdivacky    //     namespace unique { namespace-body }
6607198092Srdivacky    //   where all occurrences of 'unique' in a translation unit are
6608198092Srdivacky    //   replaced by the same identifier and this identifier differs
6609198092Srdivacky    //   from all other identifiers in the entire program.
6610198092Srdivacky
6611198092Srdivacky    // We just create the namespace with an empty name and then add an
6612198092Srdivacky    // implicit using declaration, just like the standard suggests.
6613198092Srdivacky    //
6614198092Srdivacky    // CodeGen enforces the "universally unique" aspect by giving all
6615198092Srdivacky    // declarations semantically contained within an anonymous
6616198092Srdivacky    // namespace internal linkage.
6617198092Srdivacky
6618234353Sdim    if (!PrevNS) {
6619201361Srdivacky      UsingDirectiveDecl* UD
6620243830Sdim        = UsingDirectiveDecl::Create(Context, Parent,
6621201361Srdivacky                                     /* 'using' */ LBrace,
6622201361Srdivacky                                     /* 'namespace' */ SourceLocation(),
6623219077Sdim                                     /* qualifier */ NestedNameSpecifierLoc(),
6624201361Srdivacky                                     /* identifier */ SourceLocation(),
6625201361Srdivacky                                     Namespc,
6626243830Sdim                                     /* Ancestor */ Parent);
6627201361Srdivacky      UD->setImplicit();
6628243830Sdim      Parent->addDecl(UD);
6629201361Srdivacky    }
6630193326Sed  }
6631193326Sed
6632239462Sdim  ActOnDocumentableDecl(Namespc);
6633239462Sdim
6634193326Sed  // Although we could have an invalid decl (i.e. the namespace name is a
6635193326Sed  // redefinition), push it as current DeclContext and try to continue parsing.
6636193326Sed  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6637193326Sed  // for the namespace has the declarations that showed up in that particular
6638193326Sed  // namespace definition.
6639193326Sed  PushDeclContext(NamespcScope, Namespc);
6640212904Sdim  return Namespc;
6641193326Sed}
6642193326Sed
6643199990Srdivacky/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6644199990Srdivacky/// is a namespace alias, returns the namespace it points to.
6645199990Srdivackystatic inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6646199990Srdivacky  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6647199990Srdivacky    return AD->getNamespace();
6648199990Srdivacky  return dyn_cast_or_null<NamespaceDecl>(D);
6649199990Srdivacky}
6650199990Srdivacky
6651193326Sed/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6652193326Sed/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6653212904Sdimvoid Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6654193326Sed  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6655193326Sed  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6656221345Sdim  Namespc->setRBraceLoc(RBrace);
6657193326Sed  PopDeclContext();
6658212904Sdim  if (Namespc->hasAttr<VisibilityAttr>())
6659234353Sdim    PopPragmaVisibility(true, RBrace);
6660193326Sed}
6661193326Sed
6662212904SdimCXXRecordDecl *Sema::getStdBadAlloc() const {
6663212904Sdim  return cast_or_null<CXXRecordDecl>(
6664212904Sdim                                  StdBadAlloc.get(Context.getExternalSource()));
6665212904Sdim}
6666212904Sdim
6667212904SdimNamespaceDecl *Sema::getStdNamespace() const {
6668212904Sdim  return cast_or_null<NamespaceDecl>(
6669212904Sdim                                 StdNamespace.get(Context.getExternalSource()));
6670212904Sdim}
6671212904Sdim
6672210299Sed/// \brief Retrieve the special "std" namespace, which may require us to
6673210299Sed/// implicitly define the namespace.
6674212904SdimNamespaceDecl *Sema::getOrCreateStdNamespace() {
6675210299Sed  if (!StdNamespace) {
6676210299Sed    // The "std" namespace has not yet been defined, so build one implicitly.
6677210299Sed    StdNamespace = NamespaceDecl::Create(Context,
6678210299Sed                                         Context.getTranslationUnitDecl(),
6679234353Sdim                                         /*Inline=*/false,
6680221345Sdim                                         SourceLocation(), SourceLocation(),
6681234353Sdim                                         &PP.getIdentifierTable().get("std"),
6682234353Sdim                                         /*PrevDecl=*/0);
6683212904Sdim    getStdNamespace()->setImplicit(true);
6684210299Sed  }
6685210299Sed
6686212904Sdim  return getStdNamespace();
6687210299Sed}
6688210299Sed
6689234353Sdimbool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6690234353Sdim  assert(getLangOpts().CPlusPlus &&
6691234353Sdim         "Looking for std::initializer_list outside of C++.");
6692234353Sdim
6693234353Sdim  // We're looking for implicit instantiations of
6694234353Sdim  // template <typename E> class std::initializer_list.
6695234353Sdim
6696234353Sdim  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6697234353Sdim    return false;
6698234353Sdim
6699234353Sdim  ClassTemplateDecl *Template = 0;
6700234353Sdim  const TemplateArgument *Arguments = 0;
6701234353Sdim
6702234353Sdim  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6703234353Sdim
6704234353Sdim    ClassTemplateSpecializationDecl *Specialization =
6705234353Sdim        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6706234353Sdim    if (!Specialization)
6707234353Sdim      return false;
6708234353Sdim
6709234353Sdim    Template = Specialization->getSpecializedTemplate();
6710234353Sdim    Arguments = Specialization->getTemplateArgs().data();
6711234353Sdim  } else if (const TemplateSpecializationType *TST =
6712234353Sdim                 Ty->getAs<TemplateSpecializationType>()) {
6713234353Sdim    Template = dyn_cast_or_null<ClassTemplateDecl>(
6714234353Sdim        TST->getTemplateName().getAsTemplateDecl());
6715234353Sdim    Arguments = TST->getArgs();
6716234353Sdim  }
6717234353Sdim  if (!Template)
6718234353Sdim    return false;
6719234353Sdim
6720234353Sdim  if (!StdInitializerList) {
6721234353Sdim    // Haven't recognized std::initializer_list yet, maybe this is it.
6722234353Sdim    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6723234353Sdim    if (TemplateClass->getIdentifier() !=
6724234353Sdim            &PP.getIdentifierTable().get("initializer_list") ||
6725234353Sdim        !getStdNamespace()->InEnclosingNamespaceSetOf(
6726234353Sdim            TemplateClass->getDeclContext()))
6727234353Sdim      return false;
6728234353Sdim    // This is a template called std::initializer_list, but is it the right
6729234353Sdim    // template?
6730234353Sdim    TemplateParameterList *Params = Template->getTemplateParameters();
6731234353Sdim    if (Params->getMinRequiredArguments() != 1)
6732234353Sdim      return false;
6733234353Sdim    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6734234353Sdim      return false;
6735234353Sdim
6736234353Sdim    // It's the right template.
6737234353Sdim    StdInitializerList = Template;
6738234353Sdim  }
6739234353Sdim
6740234353Sdim  if (Template != StdInitializerList)
6741234353Sdim    return false;
6742234353Sdim
6743234353Sdim  // This is an instance of std::initializer_list. Find the argument type.
6744234353Sdim  if (Element)
6745234353Sdim    *Element = Arguments[0].getAsType();
6746234353Sdim  return true;
6747234353Sdim}
6748234353Sdim
6749234353Sdimstatic ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6750234353Sdim  NamespaceDecl *Std = S.getStdNamespace();
6751234353Sdim  if (!Std) {
6752234353Sdim    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6753234353Sdim    return 0;
6754234353Sdim  }
6755234353Sdim
6756234353Sdim  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6757234353Sdim                      Loc, Sema::LookupOrdinaryName);
6758234353Sdim  if (!S.LookupQualifiedName(Result, Std)) {
6759234353Sdim    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6760234353Sdim    return 0;
6761234353Sdim  }
6762234353Sdim  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6763234353Sdim  if (!Template) {
6764234353Sdim    Result.suppressDiagnostics();
6765234353Sdim    // We found something weird. Complain about the first thing we found.
6766234353Sdim    NamedDecl *Found = *Result.begin();
6767234353Sdim    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6768234353Sdim    return 0;
6769234353Sdim  }
6770234353Sdim
6771234353Sdim  // We found some template called std::initializer_list. Now verify that it's
6772234353Sdim  // correct.
6773234353Sdim  TemplateParameterList *Params = Template->getTemplateParameters();
6774234353Sdim  if (Params->getMinRequiredArguments() != 1 ||
6775234353Sdim      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6776234353Sdim    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6777234353Sdim    return 0;
6778234353Sdim  }
6779234353Sdim
6780234353Sdim  return Template;
6781234353Sdim}
6782234353Sdim
6783234353SdimQualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6784234353Sdim  if (!StdInitializerList) {
6785234353Sdim    StdInitializerList = LookupStdInitializerList(*this, Loc);
6786234353Sdim    if (!StdInitializerList)
6787234353Sdim      return QualType();
6788234353Sdim  }
6789234353Sdim
6790234353Sdim  TemplateArgumentListInfo Args(Loc, Loc);
6791234353Sdim  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6792234353Sdim                                       Context.getTrivialTypeSourceInfo(Element,
6793234353Sdim                                                                        Loc)));
6794234353Sdim  return Context.getCanonicalType(
6795234353Sdim      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6796234353Sdim}
6797234353Sdim
6798234353Sdimbool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6799234353Sdim  // C++ [dcl.init.list]p2:
6800234353Sdim  //   A constructor is an initializer-list constructor if its first parameter
6801234353Sdim  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6802234353Sdim  //   std::initializer_list<E> for some type E, and either there are no other
6803234353Sdim  //   parameters or else all other parameters have default arguments.
6804234353Sdim  if (Ctor->getNumParams() < 1 ||
6805234353Sdim      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6806234353Sdim    return false;
6807234353Sdim
6808234353Sdim  QualType ArgType = Ctor->getParamDecl(0)->getType();
6809234353Sdim  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6810234353Sdim    ArgType = RT->getPointeeType().getUnqualifiedType();
6811234353Sdim
6812234353Sdim  return isStdInitializerList(ArgType, 0);
6813234353Sdim}
6814234353Sdim
6815221345Sdim/// \brief Determine whether a using statement is in a context where it will be
6816221345Sdim/// apply in all contexts.
6817221345Sdimstatic bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6818221345Sdim  switch (CurContext->getDeclKind()) {
6819221345Sdim    case Decl::TranslationUnit:
6820221345Sdim      return true;
6821221345Sdim    case Decl::LinkageSpec:
6822221345Sdim      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6823221345Sdim    default:
6824221345Sdim      return false;
6825221345Sdim  }
6826221345Sdim}
6827221345Sdim
6828234353Sdimnamespace {
6829234353Sdim
6830234353Sdim// Callback to only accept typo corrections that are namespaces.
6831234353Sdimclass NamespaceValidatorCCC : public CorrectionCandidateCallback {
6832263508Sdimpublic:
6833263508Sdim  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6834263508Sdim    if (NamedDecl *ND = candidate.getCorrectionDecl())
6835234353Sdim      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6836234353Sdim    return false;
6837234353Sdim  }
6838234353Sdim};
6839234353Sdim
6840234353Sdim}
6841234353Sdim
6842224145Sdimstatic bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6843224145Sdim                                       CXXScopeSpec &SS,
6844224145Sdim                                       SourceLocation IdentLoc,
6845224145Sdim                                       IdentifierInfo *Ident) {
6846234353Sdim  NamespaceValidatorCCC Validator;
6847224145Sdim  R.clear();
6848224145Sdim  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6849234353Sdim                                               R.getLookupKind(), Sc, &SS,
6850234353Sdim                                               Validator)) {
6851263508Sdim    if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6852263508Sdim      std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6853263508Sdim      bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6854263508Sdim                              Ident->getName().equals(CorrectedStr);
6855263508Sdim      S.diagnoseTypo(Corrected,
6856263508Sdim                     S.PDiag(diag::err_using_directive_member_suggest)
6857263508Sdim                       << Ident << DC << DroppedSpecifier << SS.getRange(),
6858263508Sdim                     S.PDiag(diag::note_namespace_defined_here));
6859263508Sdim    } else {
6860263508Sdim      S.diagnoseTypo(Corrected,
6861263508Sdim                     S.PDiag(diag::err_using_directive_suggest) << Ident,
6862263508Sdim                     S.PDiag(diag::note_namespace_defined_here));
6863263508Sdim    }
6864234353Sdim    R.addDecl(Corrected.getCorrectionDecl());
6865234353Sdim    return true;
6866224145Sdim  }
6867224145Sdim  return false;
6868224145Sdim}
6869224145Sdim
6870212904SdimDecl *Sema::ActOnUsingDirective(Scope *S,
6871193326Sed                                          SourceLocation UsingLoc,
6872193326Sed                                          SourceLocation NamespcLoc,
6873207619Srdivacky                                          CXXScopeSpec &SS,
6874193326Sed                                          SourceLocation IdentLoc,
6875193326Sed                                          IdentifierInfo *NamespcName,
6876193326Sed                                          AttributeList *AttrList) {
6877193326Sed  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6878193326Sed  assert(NamespcName && "Invalid NamespcName.");
6879193326Sed  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6880218893Sdim
6881218893Sdim  // This can only happen along a recovery path.
6882218893Sdim  while (S->getFlags() & Scope::TemplateParamScope)
6883218893Sdim    S = S->getParent();
6884193326Sed  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6885193326Sed
6886193326Sed  UsingDirectiveDecl *UDir = 0;
6887210299Sed  NestedNameSpecifier *Qualifier = 0;
6888210299Sed  if (SS.isSet())
6889210299Sed    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6890210299Sed
6891193326Sed  // Lookup namespace name.
6892199482Srdivacky  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6893199482Srdivacky  LookupParsedName(R, S, &SS);
6894199482Srdivacky  if (R.isAmbiguous())
6895212904Sdim    return 0;
6896199482Srdivacky
6897210299Sed  if (R.empty()) {
6898224145Sdim    R.clear();
6899210299Sed    // Allow "using namespace std;" or "using namespace ::std;" even if
6900210299Sed    // "std" hasn't been defined yet, for GCC compatibility.
6901210299Sed    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6902210299Sed        NamespcName->isStr("std")) {
6903210299Sed      Diag(IdentLoc, diag::ext_using_undefined_std);
6904212904Sdim      R.addDecl(getOrCreateStdNamespace());
6905210299Sed      R.resolveKind();
6906210299Sed    }
6907210299Sed    // Otherwise, attempt typo correction.
6908224145Sdim    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6909210299Sed  }
6910210299Sed
6911198092Srdivacky  if (!R.empty()) {
6912199990Srdivacky    NamedDecl *Named = R.getFoundDecl();
6913199990Srdivacky    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6914199990Srdivacky        && "expected namespace decl");
6915193326Sed    // C++ [namespace.udir]p1:
6916193326Sed    //   A using-directive specifies that the names in the nominated
6917193326Sed    //   namespace can be used in the scope in which the
6918193326Sed    //   using-directive appears after the using-directive. During
6919193326Sed    //   unqualified name lookup (3.4.1), the names appear as if they
6920193326Sed    //   were declared in the nearest enclosing namespace which
6921193326Sed    //   contains both the using-directive and the nominated
6922198092Srdivacky    //   namespace. [Note: in this context, "contains" means "contains
6923198092Srdivacky    //   directly or indirectly". ]
6924193326Sed
6925193326Sed    // Find enclosing context containing both using-directive and
6926193326Sed    // nominated namespace.
6927199990Srdivacky    NamespaceDecl *NS = getNamespaceDecl(Named);
6928193326Sed    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6929193326Sed    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6930193326Sed      CommonAncestor = CommonAncestor->getParent();
6931193326Sed
6932199990Srdivacky    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6933219077Sdim                                      SS.getWithLocInContext(Context),
6934199990Srdivacky                                      IdentLoc, Named, CommonAncestor);
6935221345Sdim
6936221345Sdim    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6937263508Sdim        !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6938221345Sdim      Diag(IdentLoc, diag::warn_using_directive_in_header);
6939221345Sdim    }
6940221345Sdim
6941193326Sed    PushUsingDirective(S, UDir);
6942193326Sed  } else {
6943193326Sed    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6944193326Sed  }
6945193326Sed
6946249423Sdim  if (UDir)
6947249423Sdim    ProcessDeclAttributeList(S, UDir, AttrList);
6948249423Sdim
6949212904Sdim  return UDir;
6950193326Sed}
6951193326Sed
6952193326Sedvoid Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6953234353Sdim  // If the scope has an associated entity and the using directive is at
6954234353Sdim  // namespace or translation unit scope, add the UsingDirectiveDecl into
6955234353Sdim  // its lookup structure so qualified name lookup can find it.
6956263508Sdim  DeclContext *Ctx = S->getEntity();
6957234353Sdim  if (Ctx && !Ctx->isFunctionOrMethod())
6958195341Sed    Ctx->addDecl(UDir);
6959193326Sed  else
6960234353Sdim    // Otherwise, it is at block sope. The using-directives will affect lookup
6961234353Sdim    // only to the end of the scope.
6962212904Sdim    S->PushUsingDirective(UDir);
6963193326Sed}
6964193326Sed
6965194613Sed
6966212904SdimDecl *Sema::ActOnUsingDeclaration(Scope *S,
6967218893Sdim                                  AccessSpecifier AS,
6968218893Sdim                                  bool HasUsingKeyword,
6969218893Sdim                                  SourceLocation UsingLoc,
6970218893Sdim                                  CXXScopeSpec &SS,
6971218893Sdim                                  UnqualifiedId &Name,
6972218893Sdim                                  AttributeList *AttrList,
6973263508Sdim                                  bool HasTypenameKeyword,
6974218893Sdim                                  SourceLocation TypenameLoc) {
6975194613Sed  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6976194613Sed
6977198954Srdivacky  switch (Name.getKind()) {
6978224145Sdim  case UnqualifiedId::IK_ImplicitSelfParam:
6979198954Srdivacky  case UnqualifiedId::IK_Identifier:
6980198954Srdivacky  case UnqualifiedId::IK_OperatorFunctionId:
6981199990Srdivacky  case UnqualifiedId::IK_LiteralOperatorId:
6982198954Srdivacky  case UnqualifiedId::IK_ConversionFunctionId:
6983198954Srdivacky    break;
6984198954Srdivacky
6985198954Srdivacky  case UnqualifiedId::IK_ConstructorName:
6986202379Srdivacky  case UnqualifiedId::IK_ConstructorTemplateId:
6987234982Sdim    // C++11 inheriting constructors.
6988234353Sdim    Diag(Name.getLocStart(),
6989249423Sdim         getLangOpts().CPlusPlus11 ?
6990249423Sdim           diag::warn_cxx98_compat_using_decl_constructor :
6991234353Sdim           diag::err_using_decl_constructor)
6992234353Sdim      << SS.getRange();
6993200583Srdivacky
6994249423Sdim    if (getLangOpts().CPlusPlus11) break;
6995234353Sdim
6996212904Sdim    return 0;
6997198954Srdivacky
6998198954Srdivacky  case UnqualifiedId::IK_DestructorName:
6999234353Sdim    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7000198954Srdivacky      << SS.getRange();
7001212904Sdim    return 0;
7002198954Srdivacky
7003198954Srdivacky  case UnqualifiedId::IK_TemplateId:
7004234353Sdim    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7005198954Srdivacky      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7006212904Sdim    return 0;
7007198954Srdivacky  }
7008212904Sdim
7009212904Sdim  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7010212904Sdim  DeclarationName TargetName = TargetNameInfo.getName();
7011200583Srdivacky  if (!TargetName)
7012212904Sdim    return 0;
7013200583Srdivacky
7014249423Sdim  // Warn about access declarations.
7015200583Srdivacky  if (!HasUsingKeyword) {
7016263508Sdim    Diag(Name.getLocStart(),
7017263508Sdim         getLangOpts().CPlusPlus11 ? diag::err_access_decl
7018263508Sdim                                   : diag::warn_access_decl_deprecated)
7019206084Srdivacky      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7020200583Srdivacky  }
7021200583Srdivacky
7022218893Sdim  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7023218893Sdim      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7024218893Sdim    return 0;
7025218893Sdim
7026199482Srdivacky  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7027212904Sdim                                        TargetNameInfo, AttrList,
7028199482Srdivacky                                        /* IsInstantiation */ false,
7029263508Sdim                                        HasTypenameKeyword, TypenameLoc);
7030200583Srdivacky  if (UD)
7031200583Srdivacky    PushOnScopeChains(UD, S, /*AddToContext*/ false);
7032198092Srdivacky
7033212904Sdim  return UD;
7034198092Srdivacky}
7035198092Srdivacky
7036210299Sed/// \brief Determine whether a using declaration considers the given
7037210299Sed/// declarations as "equivalent", e.g., if they are redeclarations of
7038210299Sed/// the same entity or are both typedefs of the same type.
7039263508Sdimstatic bool
7040263508SdimIsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7041263508Sdim  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7042210299Sed    return true;
7043210299Sed
7044221345Sdim  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7045263508Sdim    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7046210299Sed      return Context.hasSameType(TD1->getUnderlyingType(),
7047210299Sed                                 TD2->getUnderlyingType());
7048210299Sed
7049210299Sed  return false;
7050210299Sed}
7051210299Sed
7052210299Sed
7053200583Srdivacky/// Determines whether to create a using shadow decl for a particular
7054200583Srdivacky/// decl, given the set of decls existing prior to this using lookup.
7055200583Srdivackybool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7056263508Sdim                                const LookupResult &Previous,
7057263508Sdim                                UsingShadowDecl *&PrevShadow) {
7058200583Srdivacky  // Diagnose finding a decl which is not from a base class of the
7059200583Srdivacky  // current class.  We do this now because there are cases where this
7060200583Srdivacky  // function will silently decide not to build a shadow decl, which
7061200583Srdivacky  // will pre-empt further diagnostics.
7062200583Srdivacky  //
7063200583Srdivacky  // We don't need to do this in C++0x because we do the check once on
7064200583Srdivacky  // the qualifier.
7065200583Srdivacky  //
7066200583Srdivacky  // FIXME: diagnose the following if we care enough:
7067200583Srdivacky  //   struct A { int foo; };
7068200583Srdivacky  //   struct B : A { using A::foo; };
7069200583Srdivacky  //   template <class T> struct C : A {};
7070200583Srdivacky  //   template <class T> struct D : C<T> { using B::foo; } // <---
7071200583Srdivacky  // This is invalid (during instantiation) in C++03 because B::foo
7072200583Srdivacky  // resolves to the using decl in B, which is not a base class of D<T>.
7073200583Srdivacky  // We can't diagnose it immediately because C<T> is an unknown
7074200583Srdivacky  // specialization.  The UsingShadowDecl in D<T> then points directly
7075200583Srdivacky  // to A::foo, which will look well-formed when we instantiate.
7076200583Srdivacky  // The right solution is to not collapse the shadow-decl chain.
7077249423Sdim  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7078200583Srdivacky    DeclContext *OrigDC = Orig->getDeclContext();
7079200583Srdivacky
7080200583Srdivacky    // Handle enums and anonymous structs.
7081200583Srdivacky    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7082200583Srdivacky    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7083200583Srdivacky    while (OrigRec->isAnonymousStructOrUnion())
7084200583Srdivacky      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7085200583Srdivacky
7086200583Srdivacky    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7087200583Srdivacky      if (OrigDC == CurContext) {
7088200583Srdivacky        Diag(Using->getLocation(),
7089200583Srdivacky             diag::err_using_decl_nested_name_specifier_is_current_class)
7090219077Sdim          << Using->getQualifierLoc().getSourceRange();
7091200583Srdivacky        Diag(Orig->getLocation(), diag::note_using_decl_target);
7092200583Srdivacky        return true;
7093200583Srdivacky      }
7094200583Srdivacky
7095219077Sdim      Diag(Using->getQualifierLoc().getBeginLoc(),
7096200583Srdivacky           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7097219077Sdim        << Using->getQualifier()
7098200583Srdivacky        << cast<CXXRecordDecl>(CurContext)
7099219077Sdim        << Using->getQualifierLoc().getSourceRange();
7100200583Srdivacky      Diag(Orig->getLocation(), diag::note_using_decl_target);
7101200583Srdivacky      return true;
7102200583Srdivacky    }
7103200583Srdivacky  }
7104200583Srdivacky
7105200583Srdivacky  if (Previous.empty()) return false;
7106200583Srdivacky
7107200583Srdivacky  NamedDecl *Target = Orig;
7108200583Srdivacky  if (isa<UsingShadowDecl>(Target))
7109200583Srdivacky    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7110200583Srdivacky
7111200583Srdivacky  // If the target happens to be one of the previous declarations, we
7112200583Srdivacky  // don't have a conflict.
7113200583Srdivacky  //
7114200583Srdivacky  // FIXME: but we might be increasing its access, in which case we
7115200583Srdivacky  // should redeclare it.
7116200583Srdivacky  NamedDecl *NonTag = 0, *Tag = 0;
7117263508Sdim  bool FoundEquivalentDecl = false;
7118200583Srdivacky  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7119200583Srdivacky         I != E; ++I) {
7120200583Srdivacky    NamedDecl *D = (*I)->getUnderlyingDecl();
7121263508Sdim    if (IsEquivalentForUsingDecl(Context, D, Target)) {
7122263508Sdim      if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7123263508Sdim        PrevShadow = Shadow;
7124263508Sdim      FoundEquivalentDecl = true;
7125263508Sdim    }
7126200583Srdivacky
7127200583Srdivacky    (isa<TagDecl>(D) ? Tag : NonTag) = D;
7128200583Srdivacky  }
7129200583Srdivacky
7130263508Sdim  if (FoundEquivalentDecl)
7131263508Sdim    return false;
7132263508Sdim
7133200583Srdivacky  if (Target->isFunctionOrFunctionTemplate()) {
7134200583Srdivacky    FunctionDecl *FD;
7135200583Srdivacky    if (isa<FunctionTemplateDecl>(Target))
7136200583Srdivacky      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7137200583Srdivacky    else
7138200583Srdivacky      FD = cast<FunctionDecl>(Target);
7139200583Srdivacky
7140200583Srdivacky    NamedDecl *OldDecl = 0;
7141210299Sed    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7142200583Srdivacky    case Ovl_Overload:
7143200583Srdivacky      return false;
7144200583Srdivacky
7145200583Srdivacky    case Ovl_NonFunction:
7146200583Srdivacky      Diag(Using->getLocation(), diag::err_using_decl_conflict);
7147200583Srdivacky      break;
7148200583Srdivacky
7149200583Srdivacky    // We found a decl with the exact signature.
7150200583Srdivacky    case Ovl_Match:
7151200583Srdivacky      // If we're in a record, we want to hide the target, so we
7152200583Srdivacky      // return true (without a diagnostic) to tell the caller not to
7153200583Srdivacky      // build a shadow decl.
7154200583Srdivacky      if (CurContext->isRecord())
7155200583Srdivacky        return true;
7156200583Srdivacky
7157200583Srdivacky      // If we're not in a record, this is an error.
7158200583Srdivacky      Diag(Using->getLocation(), diag::err_using_decl_conflict);
7159200583Srdivacky      break;
7160200583Srdivacky    }
7161200583Srdivacky
7162200583Srdivacky    Diag(Target->getLocation(), diag::note_using_decl_target);
7163200583Srdivacky    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7164200583Srdivacky    return true;
7165200583Srdivacky  }
7166200583Srdivacky
7167200583Srdivacky  // Target is not a function.
7168200583Srdivacky
7169200583Srdivacky  if (isa<TagDecl>(Target)) {
7170200583Srdivacky    // No conflict between a tag and a non-tag.
7171200583Srdivacky    if (!Tag) return false;
7172200583Srdivacky
7173200583Srdivacky    Diag(Using->getLocation(), diag::err_using_decl_conflict);
7174200583Srdivacky    Diag(Target->getLocation(), diag::note_using_decl_target);
7175200583Srdivacky    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7176200583Srdivacky    return true;
7177200583Srdivacky  }
7178200583Srdivacky
7179200583Srdivacky  // No conflict between a tag and a non-tag.
7180200583Srdivacky  if (!NonTag) return false;
7181200583Srdivacky
7182200583Srdivacky  Diag(Using->getLocation(), diag::err_using_decl_conflict);
7183200583Srdivacky  Diag(Target->getLocation(), diag::note_using_decl_target);
7184200583Srdivacky  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7185200583Srdivacky  return true;
7186200583Srdivacky}
7187200583Srdivacky
7188199482Srdivacky/// Builds a shadow declaration corresponding to a 'using' declaration.
7189200583SrdivackyUsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7190200583Srdivacky                                            UsingDecl *UD,
7191263508Sdim                                            NamedDecl *Orig,
7192263508Sdim                                            UsingShadowDecl *PrevDecl) {
7193199482Srdivacky
7194199482Srdivacky  // If we resolved to another shadow declaration, just coalesce them.
7195200583Srdivacky  NamedDecl *Target = Orig;
7196200583Srdivacky  if (isa<UsingShadowDecl>(Target)) {
7197200583Srdivacky    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7198200583Srdivacky    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7199199482Srdivacky  }
7200263508Sdim
7201199482Srdivacky  UsingShadowDecl *Shadow
7202200583Srdivacky    = UsingShadowDecl::Create(Context, CurContext,
7203200583Srdivacky                              UD->getLocation(), UD, Target);
7204199482Srdivacky  UD->addShadowDecl(Shadow);
7205263508Sdim
7206218893Sdim  Shadow->setAccess(UD->getAccess());
7207218893Sdim  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7208218893Sdim    Shadow->setInvalidDecl();
7209263508Sdim
7210263508Sdim  Shadow->setPreviousDecl(PrevDecl);
7211263508Sdim
7212199482Srdivacky  if (S)
7213200583Srdivacky    PushOnScopeChains(Shadow, S);
7214199482Srdivacky  else
7215200583Srdivacky    CurContext->addDecl(Shadow);
7216199482Srdivacky
7217206084Srdivacky
7218199482Srdivacky  return Shadow;
7219199482Srdivacky}
7220199482Srdivacky
7221200583Srdivacky/// Hides a using shadow declaration.  This is required by the current
7222200583Srdivacky/// using-decl implementation when a resolvable using declaration in a
7223200583Srdivacky/// class is followed by a declaration which would hide or override
7224200583Srdivacky/// one or more of the using decl's targets; for example:
7225200583Srdivacky///
7226200583Srdivacky///   struct Base { void foo(int); };
7227200583Srdivacky///   struct Derived : Base {
7228200583Srdivacky///     using Base::foo;
7229200583Srdivacky///     void foo(int);
7230200583Srdivacky///   };
7231200583Srdivacky///
7232200583Srdivacky/// The governing language is C++03 [namespace.udecl]p12:
7233200583Srdivacky///
7234200583Srdivacky///   When a using-declaration brings names from a base class into a
7235200583Srdivacky///   derived class scope, member functions in the derived class
7236200583Srdivacky///   override and/or hide member functions with the same name and
7237200583Srdivacky///   parameter types in a base class (rather than conflicting).
7238200583Srdivacky///
7239200583Srdivacky/// There are two ways to implement this:
7240200583Srdivacky///   (1) optimistically create shadow decls when they're not hidden
7241200583Srdivacky///       by existing declarations, or
7242200583Srdivacky///   (2) don't create any shadow decls (or at least don't make them
7243200583Srdivacky///       visible) until we've fully parsed/instantiated the class.
7244200583Srdivacky/// The problem with (1) is that we might have to retroactively remove
7245200583Srdivacky/// a shadow decl, which requires several O(n) operations because the
7246200583Srdivacky/// decl structures are (very reasonably) not designed for removal.
7247200583Srdivacky/// (2) avoids this but is very fiddly and phase-dependent.
7248200583Srdivackyvoid Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7249206084Srdivacky  if (Shadow->getDeclName().getNameKind() ==
7250206084Srdivacky        DeclarationName::CXXConversionFunctionName)
7251206084Srdivacky    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7252206084Srdivacky
7253200583Srdivacky  // Remove it from the DeclContext...
7254200583Srdivacky  Shadow->getDeclContext()->removeDecl(Shadow);
7255200583Srdivacky
7256200583Srdivacky  // ...and the scope, if applicable...
7257200583Srdivacky  if (S) {
7258212904Sdim    S->RemoveDecl(Shadow);
7259200583Srdivacky    IdResolver.RemoveDecl(Shadow);
7260200583Srdivacky  }
7261200583Srdivacky
7262200583Srdivacky  // ...and the using decl.
7263200583Srdivacky  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7264200583Srdivacky
7265200583Srdivacky  // TODO: complain somehow if Shadow was used.  It shouldn't
7266206084Srdivacky  // be possible for this to happen, because...?
7267200583Srdivacky}
7268200583Srdivacky
7269263508Sdimnamespace {
7270263508Sdimclass UsingValidatorCCC : public CorrectionCandidateCallback {
7271263508Sdimpublic:
7272263508Sdim  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7273263508Sdim                    bool RequireMember)
7274263508Sdim      : HasTypenameKeyword(HasTypenameKeyword),
7275263508Sdim        IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7276263508Sdim
7277263508Sdim  bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7278263508Sdim    NamedDecl *ND = Candidate.getCorrectionDecl();
7279263508Sdim
7280263508Sdim    // Keywords are not valid here.
7281263508Sdim    if (!ND || isa<NamespaceDecl>(ND))
7282263508Sdim      return false;
7283263508Sdim
7284263508Sdim    if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7285263508Sdim        !isa<TypeDecl>(ND))
7286263508Sdim      return false;
7287263508Sdim
7288263508Sdim    // Completely unqualified names are invalid for a 'using' declaration.
7289263508Sdim    if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7290263508Sdim      return false;
7291263508Sdim
7292263508Sdim    if (isa<TypeDecl>(ND))
7293263508Sdim      return HasTypenameKeyword || !IsInstantiation;
7294263508Sdim
7295263508Sdim    return !HasTypenameKeyword;
7296263508Sdim  }
7297263508Sdim
7298263508Sdimprivate:
7299263508Sdim  bool HasTypenameKeyword;
7300263508Sdim  bool IsInstantiation;
7301263508Sdim  bool RequireMember;
7302263508Sdim};
7303263508Sdim} // end anonymous namespace
7304263508Sdim
7305199482Srdivacky/// Builds a using declaration.
7306199482Srdivacky///
7307199482Srdivacky/// \param IsInstantiation - Whether this call arises from an
7308199482Srdivacky///   instantiation of an unresolved using declaration.  We treat
7309199482Srdivacky///   the lookup differently for these declarations.
7310199482SrdivackyNamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7311199482Srdivacky                                       SourceLocation UsingLoc,
7312207619Srdivacky                                       CXXScopeSpec &SS,
7313212904Sdim                                       const DeclarationNameInfo &NameInfo,
7314198092Srdivacky                                       AttributeList *AttrList,
7315199482Srdivacky                                       bool IsInstantiation,
7316263508Sdim                                       bool HasTypenameKeyword,
7317199482Srdivacky                                       SourceLocation TypenameLoc) {
7318198092Srdivacky  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7319212904Sdim  SourceLocation IdentLoc = NameInfo.getLoc();
7320198092Srdivacky  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7321198092Srdivacky
7322198092Srdivacky  // FIXME: We ignore attributes for now.
7323198092Srdivacky
7324198092Srdivacky  if (SS.isEmpty()) {
7325198092Srdivacky    Diag(IdentLoc, diag::err_using_requires_qualname);
7326198092Srdivacky    return 0;
7327198092Srdivacky  }
7328198092Srdivacky
7329200583Srdivacky  // Do the redeclaration lookup in the current scope.
7330212904Sdim  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7331200583Srdivacky                        ForRedeclaration);
7332200583Srdivacky  Previous.setHideTags(false);
7333200583Srdivacky  if (S) {
7334200583Srdivacky    LookupName(Previous, S);
7335200583Srdivacky
7336200583Srdivacky    // It is really dumb that we have to do this.
7337200583Srdivacky    LookupResult::Filter F = Previous.makeFilter();
7338200583Srdivacky    while (F.hasNext()) {
7339200583Srdivacky      NamedDecl *D = F.next();
7340200583Srdivacky      if (!isDeclInScope(D, CurContext, S))
7341200583Srdivacky        F.erase();
7342200583Srdivacky    }
7343200583Srdivacky    F.done();
7344200583Srdivacky  } else {
7345200583Srdivacky    assert(IsInstantiation && "no scope in non-instantiation");
7346200583Srdivacky    assert(CurContext->isRecord() && "scope not record in instantiation");
7347200583Srdivacky    LookupQualifiedName(Previous, CurContext);
7348200583Srdivacky  }
7349200583Srdivacky
7350200583Srdivacky  // Check for invalid redeclarations.
7351263508Sdim  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7352263508Sdim                                  SS, IdentLoc, Previous))
7353200583Srdivacky    return 0;
7354200583Srdivacky
7355200583Srdivacky  // Check for bad qualifiers.
7356200583Srdivacky  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7357200583Srdivacky    return 0;
7358200583Srdivacky
7359199482Srdivacky  DeclContext *LookupContext = computeDeclContext(SS);
7360200583Srdivacky  NamedDecl *D;
7361219077Sdim  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7362199482Srdivacky  if (!LookupContext) {
7363263508Sdim    if (HasTypenameKeyword) {
7364200583Srdivacky      // FIXME: not all declaration name kinds are legal here
7365200583Srdivacky      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7366200583Srdivacky                                              UsingLoc, TypenameLoc,
7367219077Sdim                                              QualifierLoc,
7368212904Sdim                                              IdentLoc, NameInfo.getName());
7369199482Srdivacky    } else {
7370219077Sdim      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7371219077Sdim                                           QualifierLoc, NameInfo);
7372199482Srdivacky    }
7373200583Srdivacky  } else {
7374219077Sdim    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7375263508Sdim                          NameInfo, HasTypenameKeyword);
7376198092Srdivacky  }
7377200583Srdivacky  D->setAccess(AS);
7378200583Srdivacky  CurContext->addDecl(D);
7379198092Srdivacky
7380200583Srdivacky  if (!LookupContext) return D;
7381200583Srdivacky  UsingDecl *UD = cast<UsingDecl>(D);
7382200583Srdivacky
7383207619Srdivacky  if (RequireCompleteDeclContext(SS, LookupContext)) {
7384200583Srdivacky    UD->setInvalidDecl();
7385200583Srdivacky    return UD;
7386194613Sed  }
7387194613Sed
7388234353Sdim  // The normal rules do not apply to inheriting constructor declarations.
7389218893Sdim  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7390234353Sdim    if (CheckInheritingConstructorUsingDecl(UD))
7391218893Sdim      UD->setInvalidDecl();
7392218893Sdim    return UD;
7393218893Sdim  }
7394200583Srdivacky
7395218893Sdim  // Otherwise, look up the target name.
7396218893Sdim
7397212904Sdim  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7398198092Srdivacky
7399200583Srdivacky  // Unlike most lookups, we don't always want to hide tag
7400200583Srdivacky  // declarations: tag names are visible through the using declaration
7401200583Srdivacky  // even if hidden by ordinary names, *except* in a dependent context
7402200583Srdivacky  // where it's important for the sanity of two-phase lookup.
7403199482Srdivacky  if (!IsInstantiation)
7404199482Srdivacky    R.setHideTags(false);
7405198092Srdivacky
7406234353Sdim  // For the purposes of this lookup, we have a base object type
7407234353Sdim  // equal to that of the current context.
7408234353Sdim  if (CurContext->isRecord()) {
7409234353Sdim    R.setBaseObjectType(
7410234353Sdim                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7411234353Sdim  }
7412234353Sdim
7413199482Srdivacky  LookupQualifiedName(R, LookupContext);
7414199482Srdivacky
7415263508Sdim  // Try to correct typos if possible.
7416198092Srdivacky  if (R.empty()) {
7417263508Sdim    UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7418263508Sdim                          CurContext->isRecord());
7419263508Sdim    if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7420263508Sdim                                               R.getLookupKind(), S, &SS, CCC)){
7421263508Sdim      // We reject any correction for which ND would be NULL.
7422263508Sdim      NamedDecl *ND = Corrected.getCorrectionDecl();
7423263508Sdim      R.setLookupName(Corrected.getCorrection());
7424263508Sdim      R.addDecl(ND);
7425263508Sdim      // We reject candidates where DroppedSpecifier == true, hence the
7426263508Sdim      // literal '0' below.
7427263508Sdim      diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7428263508Sdim                                << NameInfo.getName() << LookupContext << 0
7429263508Sdim                                << SS.getRange());
7430263508Sdim    } else {
7431263508Sdim      Diag(IdentLoc, diag::err_no_member)
7432263508Sdim        << NameInfo.getName() << LookupContext << SS.getRange();
7433263508Sdim      UD->setInvalidDecl();
7434263508Sdim      return UD;
7435263508Sdim    }
7436198092Srdivacky  }
7437198092Srdivacky
7438200583Srdivacky  if (R.isAmbiguous()) {
7439200583Srdivacky    UD->setInvalidDecl();
7440200583Srdivacky    return UD;
7441200583Srdivacky  }
7442198092Srdivacky
7443263508Sdim  if (HasTypenameKeyword) {
7444199482Srdivacky    // If we asked for a typename and got a non-type decl, error out.
7445200583Srdivacky    if (!R.getAsSingle<TypeDecl>()) {
7446199482Srdivacky      Diag(IdentLoc, diag::err_using_typename_non_type);
7447199482Srdivacky      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7448199482Srdivacky        Diag((*I)->getUnderlyingDecl()->getLocation(),
7449199482Srdivacky             diag::note_using_decl_target);
7450200583Srdivacky      UD->setInvalidDecl();
7451200583Srdivacky      return UD;
7452199482Srdivacky    }
7453199482Srdivacky  } else {
7454199482Srdivacky    // If we asked for a non-typename and we got a type, error out,
7455199482Srdivacky    // but only if this is an instantiation of an unresolved using
7456199482Srdivacky    // decl.  Otherwise just silently find the type name.
7457200583Srdivacky    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7458199482Srdivacky      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7459199482Srdivacky      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7460200583Srdivacky      UD->setInvalidDecl();
7461200583Srdivacky      return UD;
7462199482Srdivacky    }
7463198092Srdivacky  }
7464198092Srdivacky
7465198092Srdivacky  // C++0x N2914 [namespace.udecl]p6:
7466198092Srdivacky  // A using-declaration shall not name a namespace.
7467200583Srdivacky  if (R.getAsSingle<NamespaceDecl>()) {
7468198092Srdivacky    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7469198092Srdivacky      << SS.getRange();
7470200583Srdivacky    UD->setInvalidDecl();
7471200583Srdivacky    return UD;
7472198092Srdivacky  }
7473198092Srdivacky
7474200583Srdivacky  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7475263508Sdim    UsingShadowDecl *PrevDecl = 0;
7476263508Sdim    if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7477263508Sdim      BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7478200583Srdivacky  }
7479199482Srdivacky
7480199482Srdivacky  return UD;
7481194613Sed}
7482194613Sed
7483218893Sdim/// Additional checks for a using declaration referring to a constructor name.
7484234353Sdimbool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7485263508Sdim  assert(!UD->hasTypename() && "expecting a constructor name");
7486218893Sdim
7487219077Sdim  const Type *SourceType = UD->getQualifier()->getAsType();
7488218893Sdim  assert(SourceType &&
7489218893Sdim         "Using decl naming constructor doesn't have type in scope spec.");
7490218893Sdim  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7491218893Sdim
7492218893Sdim  // Check whether the named type is a direct base class.
7493218893Sdim  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7494218893Sdim  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7495218893Sdim  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7496218893Sdim       BaseIt != BaseE; ++BaseIt) {
7497218893Sdim    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7498218893Sdim    if (CanonicalSourceType == BaseType)
7499218893Sdim      break;
7500234353Sdim    if (BaseIt->getType()->isDependentType())
7501234353Sdim      break;
7502218893Sdim  }
7503218893Sdim
7504218893Sdim  if (BaseIt == BaseE) {
7505218893Sdim    // Did not find SourceType in the bases.
7506263508Sdim    Diag(UD->getUsingLoc(),
7507218893Sdim         diag::err_using_decl_constructor_not_in_direct_base)
7508218893Sdim      << UD->getNameInfo().getSourceRange()
7509218893Sdim      << QualType(SourceType, 0) << TargetClass;
7510218893Sdim    return true;
7511218893Sdim  }
7512218893Sdim
7513234353Sdim  if (!CurContext->isDependentContext())
7514234353Sdim    BaseIt->setInheritConstructors();
7515218893Sdim
7516218893Sdim  return false;
7517218893Sdim}
7518218893Sdim
7519200583Srdivacky/// Checks that the given using declaration is not an invalid
7520200583Srdivacky/// redeclaration.  Note that this is checking only for the using decl
7521200583Srdivacky/// itself, not for any ill-formedness among the UsingShadowDecls.
7522200583Srdivackybool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7523263508Sdim                                       bool HasTypenameKeyword,
7524200583Srdivacky                                       const CXXScopeSpec &SS,
7525200583Srdivacky                                       SourceLocation NameLoc,
7526200583Srdivacky                                       const LookupResult &Prev) {
7527200583Srdivacky  // C++03 [namespace.udecl]p8:
7528200583Srdivacky  // C++0x [namespace.udecl]p10:
7529200583Srdivacky  //   A using-declaration is a declaration and can therefore be used
7530200583Srdivacky  //   repeatedly where (and only where) multiple declarations are
7531200583Srdivacky  //   allowed.
7532208600Srdivacky  //
7533208600Srdivacky  // That's in non-member contexts.
7534212904Sdim  if (!CurContext->getRedeclContext()->isRecord())
7535200583Srdivacky    return false;
7536200583Srdivacky
7537200583Srdivacky  NestedNameSpecifier *Qual
7538200583Srdivacky    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7539200583Srdivacky
7540200583Srdivacky  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7541200583Srdivacky    NamedDecl *D = *I;
7542200583Srdivacky
7543200583Srdivacky    bool DTypename;
7544200583Srdivacky    NestedNameSpecifier *DQual;
7545200583Srdivacky    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7546263508Sdim      DTypename = UD->hasTypename();
7547219077Sdim      DQual = UD->getQualifier();
7548200583Srdivacky    } else if (UnresolvedUsingValueDecl *UD
7549200583Srdivacky                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7550200583Srdivacky      DTypename = false;
7551219077Sdim      DQual = UD->getQualifier();
7552200583Srdivacky    } else if (UnresolvedUsingTypenameDecl *UD
7553200583Srdivacky                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7554200583Srdivacky      DTypename = true;
7555219077Sdim      DQual = UD->getQualifier();
7556200583Srdivacky    } else continue;
7557200583Srdivacky
7558200583Srdivacky    // using decls differ if one says 'typename' and the other doesn't.
7559200583Srdivacky    // FIXME: non-dependent using decls?
7560263508Sdim    if (HasTypenameKeyword != DTypename) continue;
7561200583Srdivacky
7562200583Srdivacky    // using decls differ if they name different scopes (but note that
7563200583Srdivacky    // template instantiation can cause this check to trigger when it
7564200583Srdivacky    // didn't before instantiation).
7565200583Srdivacky    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7566200583Srdivacky        Context.getCanonicalNestedNameSpecifier(DQual))
7567200583Srdivacky      continue;
7568200583Srdivacky
7569200583Srdivacky    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7570200583Srdivacky    Diag(D->getLocation(), diag::note_using_decl) << 1;
7571200583Srdivacky    return true;
7572200583Srdivacky  }
7573200583Srdivacky
7574200583Srdivacky  return false;
7575200583Srdivacky}
7576200583Srdivacky
7577200583Srdivacky
7578200583Srdivacky/// Checks that the given nested-name qualifier used in a using decl
7579200583Srdivacky/// in the current context is appropriately related to the current
7580200583Srdivacky/// scope.  If an error is found, diagnoses it and returns true.
7581200583Srdivackybool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7582200583Srdivacky                                   const CXXScopeSpec &SS,
7583200583Srdivacky                                   SourceLocation NameLoc) {
7584200583Srdivacky  DeclContext *NamedContext = computeDeclContext(SS);
7585200583Srdivacky
7586200583Srdivacky  if (!CurContext->isRecord()) {
7587200583Srdivacky    // C++03 [namespace.udecl]p3:
7588200583Srdivacky    // C++0x [namespace.udecl]p8:
7589200583Srdivacky    //   A using-declaration for a class member shall be a member-declaration.
7590200583Srdivacky
7591200583Srdivacky    // If we weren't able to compute a valid scope, it must be a
7592200583Srdivacky    // dependent class scope.
7593200583Srdivacky    if (!NamedContext || NamedContext->isRecord()) {
7594200583Srdivacky      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7595200583Srdivacky        << SS.getRange();
7596200583Srdivacky      return true;
7597200583Srdivacky    }
7598200583Srdivacky
7599200583Srdivacky    // Otherwise, everything is known to be fine.
7600200583Srdivacky    return false;
7601200583Srdivacky  }
7602200583Srdivacky
7603200583Srdivacky  // The current scope is a record.
7604200583Srdivacky
7605200583Srdivacky  // If the named context is dependent, we can't decide much.
7606200583Srdivacky  if (!NamedContext) {
7607200583Srdivacky    // FIXME: in C++0x, we can diagnose if we can prove that the
7608200583Srdivacky    // nested-name-specifier does not refer to a base class, which is
7609200583Srdivacky    // still possible in some cases.
7610200583Srdivacky
7611200583Srdivacky    // Otherwise we have to conservatively report that things might be
7612200583Srdivacky    // okay.
7613200583Srdivacky    return false;
7614200583Srdivacky  }
7615200583Srdivacky
7616200583Srdivacky  if (!NamedContext->isRecord()) {
7617200583Srdivacky    // Ideally this would point at the last name in the specifier,
7618200583Srdivacky    // but we don't have that level of source info.
7619200583Srdivacky    Diag(SS.getRange().getBegin(),
7620200583Srdivacky         diag::err_using_decl_nested_name_specifier_is_not_class)
7621200583Srdivacky      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7622200583Srdivacky    return true;
7623200583Srdivacky  }
7624200583Srdivacky
7625218893Sdim  if (!NamedContext->isDependentContext() &&
7626218893Sdim      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7627218893Sdim    return true;
7628218893Sdim
7629249423Sdim  if (getLangOpts().CPlusPlus11) {
7630200583Srdivacky    // C++0x [namespace.udecl]p3:
7631200583Srdivacky    //   In a using-declaration used as a member-declaration, the
7632200583Srdivacky    //   nested-name-specifier shall name a base class of the class
7633200583Srdivacky    //   being defined.
7634200583Srdivacky
7635200583Srdivacky    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7636200583Srdivacky                                 cast<CXXRecordDecl>(NamedContext))) {
7637200583Srdivacky      if (CurContext == NamedContext) {
7638200583Srdivacky        Diag(NameLoc,
7639200583Srdivacky             diag::err_using_decl_nested_name_specifier_is_current_class)
7640200583Srdivacky          << SS.getRange();
7641200583Srdivacky        return true;
7642200583Srdivacky      }
7643200583Srdivacky
7644200583Srdivacky      Diag(SS.getRange().getBegin(),
7645200583Srdivacky           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7646200583Srdivacky        << (NestedNameSpecifier*) SS.getScopeRep()
7647200583Srdivacky        << cast<CXXRecordDecl>(CurContext)
7648200583Srdivacky        << SS.getRange();
7649200583Srdivacky      return true;
7650200583Srdivacky    }
7651200583Srdivacky
7652200583Srdivacky    return false;
7653200583Srdivacky  }
7654200583Srdivacky
7655200583Srdivacky  // C++03 [namespace.udecl]p4:
7656200583Srdivacky  //   A using-declaration used as a member-declaration shall refer
7657200583Srdivacky  //   to a member of a base class of the class being defined [etc.].
7658200583Srdivacky
7659200583Srdivacky  // Salient point: SS doesn't have to name a base class as long as
7660200583Srdivacky  // lookup only finds members from base classes.  Therefore we can
7661200583Srdivacky  // diagnose here only if we can prove that that can't happen,
7662200583Srdivacky  // i.e. if the class hierarchies provably don't intersect.
7663200583Srdivacky
7664200583Srdivacky  // TODO: it would be nice if "definitely valid" results were cached
7665200583Srdivacky  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7666200583Srdivacky  // need to be repeated.
7667200583Srdivacky
7668200583Srdivacky  struct UserData {
7669234353Sdim    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7670200583Srdivacky
7671200583Srdivacky    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7672200583Srdivacky      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7673200583Srdivacky      Data->Bases.insert(Base);
7674200583Srdivacky      return true;
7675200583Srdivacky    }
7676200583Srdivacky
7677200583Srdivacky    bool hasDependentBases(const CXXRecordDecl *Class) {
7678200583Srdivacky      return !Class->forallBases(collect, this);
7679200583Srdivacky    }
7680200583Srdivacky
7681200583Srdivacky    /// Returns true if the base is dependent or is one of the
7682200583Srdivacky    /// accumulated base classes.
7683200583Srdivacky    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7684200583Srdivacky      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7685200583Srdivacky      return !Data->Bases.count(Base);
7686200583Srdivacky    }
7687200583Srdivacky
7688200583Srdivacky    bool mightShareBases(const CXXRecordDecl *Class) {
7689200583Srdivacky      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7690200583Srdivacky    }
7691200583Srdivacky  };
7692200583Srdivacky
7693200583Srdivacky  UserData Data;
7694200583Srdivacky
7695200583Srdivacky  // Returns false if we find a dependent base.
7696200583Srdivacky  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7697200583Srdivacky    return false;
7698200583Srdivacky
7699200583Srdivacky  // Returns false if the class has a dependent base or if it or one
7700200583Srdivacky  // of its bases is present in the base set of the current context.
7701200583Srdivacky  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7702200583Srdivacky    return false;
7703200583Srdivacky
7704200583Srdivacky  Diag(SS.getRange().getBegin(),
7705200583Srdivacky       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7706200583Srdivacky    << (NestedNameSpecifier*) SS.getScopeRep()
7707200583Srdivacky    << cast<CXXRecordDecl>(CurContext)
7708200583Srdivacky    << SS.getRange();
7709200583Srdivacky
7710200583Srdivacky  return true;
7711200583Srdivacky}
7712200583Srdivacky
7713221345SdimDecl *Sema::ActOnAliasDeclaration(Scope *S,
7714221345Sdim                                  AccessSpecifier AS,
7715223017Sdim                                  MultiTemplateParamsArg TemplateParamLists,
7716221345Sdim                                  SourceLocation UsingLoc,
7717221345Sdim                                  UnqualifiedId &Name,
7718249423Sdim                                  AttributeList *AttrList,
7719221345Sdim                                  TypeResult Type) {
7720223017Sdim  // Skip up to the relevant declaration scope.
7721223017Sdim  while (S->getFlags() & Scope::TemplateParamScope)
7722223017Sdim    S = S->getParent();
7723221345Sdim  assert((S->getFlags() & Scope::DeclScope) &&
7724221345Sdim         "got alias-declaration outside of declaration scope");
7725221345Sdim
7726221345Sdim  if (Type.isInvalid())
7727221345Sdim    return 0;
7728221345Sdim
7729221345Sdim  bool Invalid = false;
7730221345Sdim  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7731221345Sdim  TypeSourceInfo *TInfo = 0;
7732221345Sdim  GetTypeFromParser(Type.get(), &TInfo);
7733221345Sdim
7734221345Sdim  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7735221345Sdim    return 0;
7736221345Sdim
7737221345Sdim  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7738223017Sdim                                      UPPC_DeclarationType)) {
7739221345Sdim    Invalid = true;
7740223017Sdim    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7741223017Sdim                                             TInfo->getTypeLoc().getBeginLoc());
7742223017Sdim  }
7743221345Sdim
7744221345Sdim  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7745221345Sdim  LookupName(Previous, S);
7746221345Sdim
7747221345Sdim  // Warn about shadowing the name of a template parameter.
7748221345Sdim  if (Previous.isSingleResult() &&
7749221345Sdim      Previous.getFoundDecl()->isTemplateParameter()) {
7750234353Sdim    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7751221345Sdim    Previous.clear();
7752221345Sdim  }
7753221345Sdim
7754221345Sdim  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7755221345Sdim         "name in alias declaration must be an identifier");
7756221345Sdim  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7757221345Sdim                                               Name.StartLocation,
7758221345Sdim                                               Name.Identifier, TInfo);
7759221345Sdim
7760221345Sdim  NewTD->setAccess(AS);
7761221345Sdim
7762221345Sdim  if (Invalid)
7763221345Sdim    NewTD->setInvalidDecl();
7764221345Sdim
7765249423Sdim  ProcessDeclAttributeList(S, NewTD, AttrList);
7766249423Sdim
7767223017Sdim  CheckTypedefForVariablyModifiedType(S, NewTD);
7768223017Sdim  Invalid |= NewTD->isInvalidDecl();
7769223017Sdim
7770221345Sdim  bool Redeclaration = false;
7771221345Sdim
7772223017Sdim  NamedDecl *NewND;
7773223017Sdim  if (TemplateParamLists.size()) {
7774223017Sdim    TypeAliasTemplateDecl *OldDecl = 0;
7775223017Sdim    TemplateParameterList *OldTemplateParams = 0;
7776223017Sdim
7777223017Sdim    if (TemplateParamLists.size() != 1) {
7778223017Sdim      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7779243830Sdim        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7780243830Sdim         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7781223017Sdim    }
7782243830Sdim    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7783223017Sdim
7784223017Sdim    // Only consider previous declarations in the same scope.
7785223017Sdim    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7786223017Sdim                         /*ExplicitInstantiationOrSpecialization*/false);
7787223017Sdim    if (!Previous.empty()) {
7788223017Sdim      Redeclaration = true;
7789223017Sdim
7790223017Sdim      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7791223017Sdim      if (!OldDecl && !Invalid) {
7792223017Sdim        Diag(UsingLoc, diag::err_redefinition_different_kind)
7793223017Sdim          << Name.Identifier;
7794223017Sdim
7795223017Sdim        NamedDecl *OldD = Previous.getRepresentativeDecl();
7796223017Sdim        if (OldD->getLocation().isValid())
7797223017Sdim          Diag(OldD->getLocation(), diag::note_previous_definition);
7798223017Sdim
7799223017Sdim        Invalid = true;
7800223017Sdim      }
7801223017Sdim
7802223017Sdim      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7803223017Sdim        if (TemplateParameterListsAreEqual(TemplateParams,
7804223017Sdim                                           OldDecl->getTemplateParameters(),
7805223017Sdim                                           /*Complain=*/true,
7806223017Sdim                                           TPL_TemplateMatch))
7807223017Sdim          OldTemplateParams = OldDecl->getTemplateParameters();
7808223017Sdim        else
7809223017Sdim          Invalid = true;
7810223017Sdim
7811223017Sdim        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7812223017Sdim        if (!Invalid &&
7813223017Sdim            !Context.hasSameType(OldTD->getUnderlyingType(),
7814223017Sdim                                 NewTD->getUnderlyingType())) {
7815223017Sdim          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7816223017Sdim          // but we can't reasonably accept it.
7817223017Sdim          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7818223017Sdim            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7819223017Sdim          if (OldTD->getLocation().isValid())
7820223017Sdim            Diag(OldTD->getLocation(), diag::note_previous_definition);
7821223017Sdim          Invalid = true;
7822223017Sdim        }
7823223017Sdim      }
7824223017Sdim    }
7825223017Sdim
7826223017Sdim    // Merge any previous default template arguments into our parameters,
7827223017Sdim    // and check the parameter list.
7828223017Sdim    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7829223017Sdim                                   TPC_TypeAliasTemplate))
7830223017Sdim      return 0;
7831223017Sdim
7832223017Sdim    TypeAliasTemplateDecl *NewDecl =
7833223017Sdim      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7834223017Sdim                                    Name.Identifier, TemplateParams,
7835223017Sdim                                    NewTD);
7836223017Sdim
7837223017Sdim    NewDecl->setAccess(AS);
7838223017Sdim
7839223017Sdim    if (Invalid)
7840223017Sdim      NewDecl->setInvalidDecl();
7841223017Sdim    else if (OldDecl)
7842263508Sdim      NewDecl->setPreviousDecl(OldDecl);
7843223017Sdim
7844223017Sdim    NewND = NewDecl;
7845223017Sdim  } else {
7846223017Sdim    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7847223017Sdim    NewND = NewTD;
7848223017Sdim  }
7849223017Sdim
7850221345Sdim  if (!Redeclaration)
7851223017Sdim    PushOnScopeChains(NewND, S);
7852221345Sdim
7853239462Sdim  ActOnDocumentableDecl(NewND);
7854223017Sdim  return NewND;
7855221345Sdim}
7856221345Sdim
7857212904SdimDecl *Sema::ActOnNamespaceAliasDef(Scope *S,
7858193326Sed                                             SourceLocation NamespaceLoc,
7859193326Sed                                             SourceLocation AliasLoc,
7860193326Sed                                             IdentifierInfo *Alias,
7861207619Srdivacky                                             CXXScopeSpec &SS,
7862193326Sed                                             SourceLocation IdentLoc,
7863193326Sed                                             IdentifierInfo *Ident) {
7864198092Srdivacky
7865193326Sed  // Lookup the namespace name.
7866199482Srdivacky  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7867199482Srdivacky  LookupParsedName(R, S, &SS);
7868193326Sed
7869193326Sed  // Check if we have a previous declaration with the same name.
7870207619Srdivacky  NamedDecl *PrevDecl
7871207619Srdivacky    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7872207619Srdivacky                       ForRedeclaration);
7873207619Srdivacky  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7874207619Srdivacky    PrevDecl = 0;
7875207619Srdivacky
7876207619Srdivacky  if (PrevDecl) {
7877193326Sed    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7878198092Srdivacky      // We already have an alias with the same name that points to the same
7879193326Sed      // namespace, so don't create a new one.
7880206084Srdivacky      // FIXME: At some point, we'll want to create the (redundant)
7881206084Srdivacky      // declaration to maintain better source information.
7882198092Srdivacky      if (!R.isAmbiguous() && !R.empty() &&
7883206084Srdivacky          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7884212904Sdim        return 0;
7885193326Sed    }
7886198092Srdivacky
7887193326Sed    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7888193326Sed      diag::err_redefinition_different_kind;
7889193326Sed    Diag(AliasLoc, DiagID) << Alias;
7890193326Sed    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7891212904Sdim    return 0;
7892193326Sed  }
7893193326Sed
7894199482Srdivacky  if (R.isAmbiguous())
7895212904Sdim    return 0;
7896198092Srdivacky
7897198092Srdivacky  if (R.empty()) {
7898224145Sdim    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7899234353Sdim      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7900212904Sdim      return 0;
7901210299Sed    }
7902193326Sed  }
7903198092Srdivacky
7904194613Sed  NamespaceAliasDecl *AliasDecl =
7905198092Srdivacky    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7906219077Sdim                               Alias, SS.getWithLocInContext(Context),
7907198092Srdivacky                               IdentLoc, R.getFoundDecl());
7908198092Srdivacky
7909203955Srdivacky  PushOnScopeChains(AliasDecl, S);
7910212904Sdim  return AliasDecl;
7911193326Sed}
7912193326Sed
7913223017SdimSema::ImplicitExceptionSpecification
7914239462SdimSema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7915239462Sdim                                               CXXMethodDecl *MD) {
7916239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
7917239462Sdim
7918210299Sed  // C++ [except.spec]p14:
7919210299Sed  //   An implicitly declared special member function (Clause 12) shall have an
7920210299Sed  //   exception-specification. [...]
7921234982Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
7922224145Sdim  if (ClassDecl->isInvalidDecl())
7923224145Sdim    return ExceptSpec;
7924210299Sed
7925221345Sdim  // Direct base-class constructors.
7926210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7927210299Sed                                       BEnd = ClassDecl->bases_end();
7928210299Sed       B != BEnd; ++B) {
7929210299Sed    if (B->isVirtual()) // Handled below.
7930210299Sed      continue;
7931210299Sed
7932210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7933210299Sed      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7934223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7935223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
7936223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
7937223017Sdim      if (Constructor)
7938234982Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7939210299Sed    }
7940210299Sed  }
7941221345Sdim
7942221345Sdim  // Virtual base-class constructors.
7943210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7944210299Sed                                       BEnd = ClassDecl->vbases_end();
7945210299Sed       B != BEnd; ++B) {
7946210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7947210299Sed      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7948223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7949223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
7950223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
7951223017Sdim      if (Constructor)
7952234982Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7953210299Sed    }
7954210299Sed  }
7955221345Sdim
7956221345Sdim  // Field constructors.
7957210299Sed  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7958210299Sed                               FEnd = ClassDecl->field_end();
7959210299Sed       F != FEnd; ++F) {
7960223017Sdim    if (F->hasInClassInitializer()) {
7961223017Sdim      if (Expr *E = F->getInClassInitializer())
7962223017Sdim        ExceptSpec.CalledExpr(E);
7963223017Sdim      else if (!F->isInvalidDecl())
7964239462Sdim        // DR1351:
7965239462Sdim        //   If the brace-or-equal-initializer of a non-static data member
7966239462Sdim        //   invokes a defaulted default constructor of its class or of an
7967239462Sdim        //   enclosing class in a potentially evaluated subexpression, the
7968239462Sdim        //   program is ill-formed.
7969239462Sdim        //
7970239462Sdim        // This resolution is unworkable: the exception specification of the
7971239462Sdim        // default constructor can be needed in an unevaluated context, in
7972239462Sdim        // particular, in the operand of a noexcept-expression, and we can be
7973239462Sdim        // unable to compute an exception specification for an enclosed class.
7974239462Sdim        //
7975239462Sdim        // We do not allow an in-class initializer to require the evaluation
7976239462Sdim        // of the exception specification for any in-class initializer whose
7977239462Sdim        // definition is not lexically complete.
7978239462Sdim        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7979223017Sdim    } else if (const RecordType *RecordTy
7980210299Sed              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7981223017Sdim      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7982223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7983223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
7984223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
7985223017Sdim      // In particular, the problem is that this function never gets called. It
7986223017Sdim      // might just be ill-formed because this function attempts to refer to
7987223017Sdim      // a deleted function here.
7988223017Sdim      if (Constructor)
7989234982Sdim        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7990210299Sed    }
7991210299Sed  }
7992218893Sdim
7993223017Sdim  return ExceptSpec;
7994223017Sdim}
7995221345Sdim
7996249423SdimSema::ImplicitExceptionSpecification
7997251662SdimSema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7998251662Sdim  CXXRecordDecl *ClassDecl = CD->getParent();
7999251662Sdim
8000251662Sdim  // C++ [except.spec]p14:
8001251662Sdim  //   An inheriting constructor [...] shall have an exception-specification. [...]
8002249423Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
8003251662Sdim  if (ClassDecl->isInvalidDecl())
8004251662Sdim    return ExceptSpec;
8005251662Sdim
8006251662Sdim  // Inherited constructor.
8007251662Sdim  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8008251662Sdim  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8009251662Sdim  // FIXME: Copying or moving the parameters could add extra exceptions to the
8010251662Sdim  // set, as could the default arguments for the inherited constructor. This
8011251662Sdim  // will be addressed when we implement the resolution of core issue 1351.
8012251662Sdim  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8013251662Sdim
8014251662Sdim  // Direct base-class constructors.
8015251662Sdim  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8016251662Sdim                                       BEnd = ClassDecl->bases_end();
8017251662Sdim       B != BEnd; ++B) {
8018251662Sdim    if (B->isVirtual()) // Handled below.
8019251662Sdim      continue;
8020251662Sdim
8021251662Sdim    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8022251662Sdim      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8023251662Sdim      if (BaseClassDecl == InheritedDecl)
8024251662Sdim        continue;
8025251662Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8026251662Sdim      if (Constructor)
8027251662Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8028251662Sdim    }
8029251662Sdim  }
8030251662Sdim
8031251662Sdim  // Virtual base-class constructors.
8032251662Sdim  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8033251662Sdim                                       BEnd = ClassDecl->vbases_end();
8034251662Sdim       B != BEnd; ++B) {
8035251662Sdim    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8036251662Sdim      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8037251662Sdim      if (BaseClassDecl == InheritedDecl)
8038251662Sdim        continue;
8039251662Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8040251662Sdim      if (Constructor)
8041251662Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8042251662Sdim    }
8043251662Sdim  }
8044251662Sdim
8045251662Sdim  // Field constructors.
8046251662Sdim  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8047251662Sdim                               FEnd = ClassDecl->field_end();
8048251662Sdim       F != FEnd; ++F) {
8049251662Sdim    if (F->hasInClassInitializer()) {
8050251662Sdim      if (Expr *E = F->getInClassInitializer())
8051251662Sdim        ExceptSpec.CalledExpr(E);
8052251662Sdim      else if (!F->isInvalidDecl())
8053251662Sdim        Diag(CD->getLocation(),
8054251662Sdim             diag::err_in_class_initializer_references_def_ctor) << CD;
8055251662Sdim    } else if (const RecordType *RecordTy
8056251662Sdim              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8057251662Sdim      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8058251662Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8059251662Sdim      if (Constructor)
8060251662Sdim        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8061251662Sdim    }
8062251662Sdim  }
8063251662Sdim
8064249423Sdim  return ExceptSpec;
8065249423Sdim}
8066249423Sdim
8067249423Sdimnamespace {
8068249423Sdim/// RAII object to register a special member as being currently declared.
8069249423Sdimstruct DeclaringSpecialMember {
8070249423Sdim  Sema &S;
8071249423Sdim  Sema::SpecialMemberDecl D;
8072249423Sdim  bool WasAlreadyBeingDeclared;
8073249423Sdim
8074249423Sdim  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8075249423Sdim    : S(S), D(RD, CSM) {
8076249423Sdim    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8077249423Sdim    if (WasAlreadyBeingDeclared)
8078249423Sdim      // This almost never happens, but if it does, ensure that our cache
8079249423Sdim      // doesn't contain a stale result.
8080249423Sdim      S.SpecialMemberCache.clear();
8081249423Sdim
8082249423Sdim    // FIXME: Register a note to be produced if we encounter an error while
8083249423Sdim    // declaring the special member.
8084249423Sdim  }
8085249423Sdim  ~DeclaringSpecialMember() {
8086249423Sdim    if (!WasAlreadyBeingDeclared)
8087249423Sdim      S.SpecialMembersBeingDeclared.erase(D);
8088249423Sdim  }
8089249423Sdim
8090249423Sdim  /// \brief Are we already trying to declare this special member?
8091249423Sdim  bool isAlreadyBeingDeclared() const {
8092249423Sdim    return WasAlreadyBeingDeclared;
8093249423Sdim  }
8094249423Sdim};
8095249423Sdim}
8096249423Sdim
8097223017SdimCXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8098223017Sdim                                                     CXXRecordDecl *ClassDecl) {
8099223017Sdim  // C++ [class.ctor]p5:
8100223017Sdim  //   A default constructor for a class X is a constructor of class X
8101223017Sdim  //   that can be called without an argument. If there is no
8102223017Sdim  //   user-declared constructor for class X, a default constructor is
8103223017Sdim  //   implicitly declared. An implicitly-declared default constructor
8104223017Sdim  //   is an inline public member of its class.
8105249423Sdim  assert(ClassDecl->needsImplicitDefaultConstructor() &&
8106223017Sdim         "Should not build implicit default constructor!");
8107223017Sdim
8108249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8109249423Sdim  if (DSM.isAlreadyBeingDeclared())
8110249423Sdim    return 0;
8111249423Sdim
8112239462Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8113239462Sdim                                                     CXXDefaultConstructor,
8114239462Sdim                                                     false);
8115223017Sdim
8116210299Sed  // Create the actual constructor declaration.
8117210299Sed  CanQualType ClassType
8118210299Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8119221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
8120210299Sed  DeclarationName Name
8121210299Sed    = Context.DeclarationNames.getCXXConstructorName(ClassType);
8122221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
8123234353Sdim  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8124239462Sdim      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8125234353Sdim      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8126239462Sdim      Constexpr);
8127210299Sed  DefaultCon->setAccess(AS_public);
8128223017Sdim  DefaultCon->setDefaulted();
8129210299Sed  DefaultCon->setImplicit();
8130239462Sdim
8131239462Sdim  // Build an exception specification pointing back at this constructor.
8132263508Sdim  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8133251662Sdim  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8134239462Sdim
8135249423Sdim  // We don't need to use SpecialMemberIsTrivial here; triviality for default
8136249423Sdim  // constructors is easy to compute.
8137249423Sdim  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8138249423Sdim
8139249423Sdim  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8140249423Sdim    SetDeclDeleted(DefaultCon, ClassLoc);
8141249423Sdim
8142210299Sed  // Note that we have declared this constructor.
8143210299Sed  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8144249423Sdim
8145210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
8146210299Sed    PushOnScopeChains(DefaultCon, S, false);
8147210299Sed  ClassDecl->addDecl(DefaultCon);
8148223017Sdim
8149210299Sed  return DefaultCon;
8150210299Sed}
8151210299Sed
8152194613Sedvoid Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8153194613Sed                                            CXXConstructorDecl *Constructor) {
8154223017Sdim  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8155223017Sdim          !Constructor->doesThisDeclarationHaveABody() &&
8156223017Sdim          !Constructor->isDeleted()) &&
8157194711Sed    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8158198092Srdivacky
8159207619Srdivacky  CXXRecordDecl *ClassDecl = Constructor->getParent();
8160194711Sed  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8161199482Srdivacky
8162243830Sdim  SynthesizedFunctionScope Scope(*this, Constructor);
8163218893Sdim  DiagnosticErrorTrap Trap(Diags);
8164249423Sdim  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8165208600Srdivacky      Trap.hasErrorOccurred()) {
8166199990Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
8167223017Sdim      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8168199482Srdivacky    Constructor->setInvalidDecl();
8169218893Sdim    return;
8170194613Sed  }
8171218893Sdim
8172218893Sdim  SourceLocation Loc = Constructor->getLocation();
8173239462Sdim  Constructor->setBody(new (Context) CompoundStmt(Loc));
8174218893Sdim
8175263508Sdim  Constructor->markUsed(Context);
8176218893Sdim  MarkVTableUsed(CurrentLocation, ClassDecl);
8177221345Sdim
8178221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
8179221345Sdim    L->CompletedImplicitDefinition(Constructor);
8180221345Sdim  }
8181263508Sdim
8182263508Sdim  DiagnoseUninitializedFields(*this, Constructor);
8183194613Sed}
8184194613Sed
8185223017Sdimvoid Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8186263508Sdim  // Perform any delayed checks on exception specifications.
8187263508Sdim  CheckDelayedMemberExceptionSpecs();
8188223017Sdim}
8189223017Sdim
8190251662Sdimnamespace {
8191251662Sdim/// Information on inheriting constructors to declare.
8192251662Sdimclass InheritingConstructorInfo {
8193251662Sdimpublic:
8194251662Sdim  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8195251662Sdim      : SemaRef(SemaRef), Derived(Derived) {
8196251662Sdim    // Mark the constructors that we already have in the derived class.
8197251662Sdim    //
8198251662Sdim    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8199251662Sdim    //   unless there is a user-declared constructor with the same signature in
8200251662Sdim    //   the class where the using-declaration appears.
8201251662Sdim    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8202251662Sdim  }
8203251662Sdim
8204251662Sdim  void inheritAll(CXXRecordDecl *RD) {
8205251662Sdim    visitAll(RD, &InheritingConstructorInfo::inherit);
8206251662Sdim  }
8207251662Sdim
8208251662Sdimprivate:
8209251662Sdim  /// Information about an inheriting constructor.
8210251662Sdim  struct InheritingConstructor {
8211251662Sdim    InheritingConstructor()
8212251662Sdim      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8213251662Sdim
8214251662Sdim    /// If \c true, a constructor with this signature is already declared
8215251662Sdim    /// in the derived class.
8216251662Sdim    bool DeclaredInDerived;
8217251662Sdim
8218251662Sdim    /// The constructor which is inherited.
8219251662Sdim    const CXXConstructorDecl *BaseCtor;
8220251662Sdim
8221251662Sdim    /// The derived constructor we declared.
8222251662Sdim    CXXConstructorDecl *DerivedCtor;
8223251662Sdim  };
8224251662Sdim
8225251662Sdim  /// Inheriting constructors with a given canonical type. There can be at
8226251662Sdim  /// most one such non-template constructor, and any number of templated
8227251662Sdim  /// constructors.
8228251662Sdim  struct InheritingConstructorsForType {
8229251662Sdim    InheritingConstructor NonTemplate;
8230263508Sdim    SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8231263508Sdim        Templates;
8232251662Sdim
8233251662Sdim    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8234251662Sdim      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8235251662Sdim        TemplateParameterList *ParamList = FTD->getTemplateParameters();
8236251662Sdim        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8237251662Sdim          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8238251662Sdim                                               false, S.TPL_TemplateMatch))
8239251662Sdim            return Templates[I].second;
8240251662Sdim        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8241251662Sdim        return Templates.back().second;
8242218893Sdim      }
8243251662Sdim
8244251662Sdim      return NonTemplate;
8245218893Sdim    }
8246251662Sdim  };
8247251662Sdim
8248251662Sdim  /// Get or create the inheriting constructor record for a constructor.
8249251662Sdim  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8250251662Sdim                                  QualType CtorType) {
8251251662Sdim    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8252251662Sdim        .getEntry(SemaRef, Ctor);
8253218893Sdim  }
8254218893Sdim
8255251662Sdim  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8256249423Sdim
8257251662Sdim  /// Process all constructors for a class.
8258251662Sdim  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8259251662Sdim    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8260251662Sdim                                      CtorE = RD->ctor_end();
8261251662Sdim         CtorIt != CtorE; ++CtorIt)
8262251662Sdim      (this->*Callback)(*CtorIt);
8263251662Sdim    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8264251662Sdim             I(RD->decls_begin()), E(RD->decls_end());
8265251662Sdim         I != E; ++I) {
8266251662Sdim      const FunctionDecl *FD = (*I)->getTemplatedDecl();
8267251662Sdim      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8268251662Sdim        (this->*Callback)(CD);
8269251662Sdim    }
8270251662Sdim  }
8271218893Sdim
8272251662Sdim  /// Note that a constructor (or constructor template) was declared in Derived.
8273251662Sdim  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8274251662Sdim    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8275251662Sdim  }
8276218893Sdim
8277251662Sdim  /// Inherit a single constructor.
8278251662Sdim  void inherit(const CXXConstructorDecl *Ctor) {
8279251662Sdim    const FunctionProtoType *CtorType =
8280251662Sdim        Ctor->getType()->castAs<FunctionProtoType>();
8281251662Sdim    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8282251662Sdim    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8283218893Sdim
8284251662Sdim    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8285218893Sdim
8286251662Sdim    // Core issue (no number yet): the ellipsis is always discarded.
8287251662Sdim    if (EPI.Variadic) {
8288251662Sdim      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8289251662Sdim      SemaRef.Diag(Ctor->getLocation(),
8290251662Sdim                   diag::note_using_decl_constructor_ellipsis);
8291251662Sdim      EPI.Variadic = false;
8292251662Sdim    }
8293249423Sdim
8294251662Sdim    // Declare a constructor for each number of parameters.
8295251662Sdim    //
8296251662Sdim    // C++11 [class.inhctor]p1:
8297251662Sdim    //   The candidate set of inherited constructors from the class X named in
8298251662Sdim    //   the using-declaration consists of [... modulo defects ...] for each
8299251662Sdim    //   constructor or constructor template of X, the set of constructors or
8300251662Sdim    //   constructor templates that results from omitting any ellipsis parameter
8301251662Sdim    //   specification and successively omitting parameters with a default
8302251662Sdim    //   argument from the end of the parameter-type-list
8303251662Sdim    unsigned MinParams = minParamsToInherit(Ctor);
8304251662Sdim    unsigned Params = Ctor->getNumParams();
8305251662Sdim    if (Params >= MinParams) {
8306251662Sdim      do
8307251662Sdim        declareCtor(UsingLoc, Ctor,
8308251662Sdim                    SemaRef.Context.getFunctionType(
8309251662Sdim                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8310251662Sdim      while (Params > MinParams &&
8311251662Sdim             Ctor->getParamDecl(--Params)->hasDefaultArg());
8312251662Sdim    }
8313251662Sdim  }
8314251662Sdim
8315251662Sdim  /// Find the using-declaration which specified that we should inherit the
8316251662Sdim  /// constructors of \p Base.
8317251662Sdim  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8318251662Sdim    // No fancy lookup required; just look for the base constructor name
8319251662Sdim    // directly within the derived class.
8320251662Sdim    ASTContext &Context = SemaRef.Context;
8321251662Sdim    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8322251662Sdim        Context.getCanonicalType(Context.getRecordType(Base)));
8323251662Sdim    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8324251662Sdim    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8325251662Sdim  }
8326251662Sdim
8327251662Sdim  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8328251662Sdim    // C++11 [class.inhctor]p3:
8329251662Sdim    //   [F]or each constructor template in the candidate set of inherited
8330251662Sdim    //   constructors, a constructor template is implicitly declared
8331251662Sdim    if (Ctor->getDescribedFunctionTemplate())
8332251662Sdim      return 0;
8333251662Sdim
8334251662Sdim    //   For each non-template constructor in the candidate set of inherited
8335251662Sdim    //   constructors other than a constructor having no parameters or a
8336251662Sdim    //   copy/move constructor having a single parameter, a constructor is
8337251662Sdim    //   implicitly declared [...]
8338251662Sdim    if (Ctor->getNumParams() == 0)
8339251662Sdim      return 1;
8340251662Sdim    if (Ctor->isCopyOrMoveConstructor())
8341251662Sdim      return 2;
8342251662Sdim
8343251662Sdim    // Per discussion on core reflector, never inherit a constructor which
8344251662Sdim    // would become a default, copy, or move constructor of Derived either.
8345251662Sdim    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8346251662Sdim    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8347251662Sdim    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8348251662Sdim  }
8349251662Sdim
8350251662Sdim  /// Declare a single inheriting constructor, inheriting the specified
8351251662Sdim  /// constructor, with the given type.
8352251662Sdim  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8353251662Sdim                   QualType DerivedType) {
8354251662Sdim    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8355251662Sdim
8356251662Sdim    // C++11 [class.inhctor]p3:
8357251662Sdim    //   ... a constructor is implicitly declared with the same constructor
8358251662Sdim    //   characteristics unless there is a user-declared constructor with
8359251662Sdim    //   the same signature in the class where the using-declaration appears
8360251662Sdim    if (Entry.DeclaredInDerived)
8361251662Sdim      return;
8362251662Sdim
8363251662Sdim    // C++11 [class.inhctor]p7:
8364251662Sdim    //   If two using-declarations declare inheriting constructors with the
8365251662Sdim    //   same signature, the program is ill-formed
8366251662Sdim    if (Entry.DerivedCtor) {
8367251662Sdim      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8368251662Sdim        // Only diagnose this once per constructor.
8369251662Sdim        if (Entry.DerivedCtor->isInvalidDecl())
8370251662Sdim          return;
8371251662Sdim        Entry.DerivedCtor->setInvalidDecl();
8372251662Sdim
8373251662Sdim        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8374251662Sdim        SemaRef.Diag(BaseCtor->getLocation(),
8375251662Sdim                     diag::note_using_decl_constructor_conflict_current_ctor);
8376251662Sdim        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8377251662Sdim                     diag::note_using_decl_constructor_conflict_previous_ctor);
8378251662Sdim        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8379251662Sdim                     diag::note_using_decl_constructor_conflict_previous_using);
8380251662Sdim      } else {
8381251662Sdim        // Core issue (no number): if the same inheriting constructor is
8382251662Sdim        // produced by multiple base class constructors from the same base
8383251662Sdim        // class, the inheriting constructor is defined as deleted.
8384251662Sdim        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8385249423Sdim      }
8386249423Sdim
8387251662Sdim      return;
8388251662Sdim    }
8389249423Sdim
8390251662Sdim    ASTContext &Context = SemaRef.Context;
8391251662Sdim    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8392251662Sdim        Context.getCanonicalType(Context.getRecordType(Derived)));
8393251662Sdim    DeclarationNameInfo NameInfo(Name, UsingLoc);
8394218893Sdim
8395251662Sdim    TemplateParameterList *TemplateParams = 0;
8396251662Sdim    if (const FunctionTemplateDecl *FTD =
8397251662Sdim            BaseCtor->getDescribedFunctionTemplate()) {
8398251662Sdim      TemplateParams = FTD->getTemplateParameters();
8399251662Sdim      // We're reusing template parameters from a different DeclContext. This
8400251662Sdim      // is questionable at best, but works out because the template depth in
8401251662Sdim      // both places is guaranteed to be 0.
8402251662Sdim      // FIXME: Rebuild the template parameters in the new context, and
8403251662Sdim      // transform the function type to refer to them.
8404251662Sdim    }
8405218893Sdim
8406251662Sdim    // Build type source info pointing at the using-declaration. This is
8407251662Sdim    // required by template instantiation.
8408251662Sdim    TypeSourceInfo *TInfo =
8409251662Sdim        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8410251662Sdim    FunctionProtoTypeLoc ProtoLoc =
8411251662Sdim        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8412218893Sdim
8413251662Sdim    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8414251662Sdim        Context, Derived, UsingLoc, NameInfo, DerivedType,
8415251662Sdim        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8416251662Sdim        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8417218893Sdim
8418251662Sdim    // Build an unevaluated exception specification for this constructor.
8419251662Sdim    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8420251662Sdim    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8421251662Sdim    EPI.ExceptionSpecType = EST_Unevaluated;
8422251662Sdim    EPI.ExceptionSpecDecl = DerivedCtor;
8423251662Sdim    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8424251662Sdim                                                 FPT->getArgTypes(), EPI));
8425218893Sdim
8426251662Sdim    // Build the parameter declarations.
8427251662Sdim    SmallVector<ParmVarDecl *, 16> ParamDecls;
8428251662Sdim    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8429251662Sdim      TypeSourceInfo *TInfo =
8430251662Sdim          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8431251662Sdim      ParmVarDecl *PD = ParmVarDecl::Create(
8432251662Sdim          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8433251662Sdim          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8434251662Sdim      PD->setScopeInfo(0, I);
8435251662Sdim      PD->setImplicit();
8436251662Sdim      ParamDecls.push_back(PD);
8437251662Sdim      ProtoLoc.setArg(I, PD);
8438251662Sdim    }
8439218893Sdim
8440251662Sdim    // Set up the new constructor.
8441251662Sdim    DerivedCtor->setAccess(BaseCtor->getAccess());
8442251662Sdim    DerivedCtor->setParams(ParamDecls);
8443251662Sdim    DerivedCtor->setInheritedConstructor(BaseCtor);
8444251662Sdim    if (BaseCtor->isDeleted())
8445251662Sdim      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8446249423Sdim
8447251662Sdim    // If this is a constructor template, build the template declaration.
8448251662Sdim    if (TemplateParams) {
8449251662Sdim      FunctionTemplateDecl *DerivedTemplate =
8450251662Sdim          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8451251662Sdim                                       TemplateParams, DerivedCtor);
8452251662Sdim      DerivedTemplate->setAccess(BaseCtor->getAccess());
8453251662Sdim      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8454251662Sdim      Derived->addDecl(DerivedTemplate);
8455251662Sdim    } else {
8456251662Sdim      Derived->addDecl(DerivedCtor);
8457251662Sdim    }
8458218893Sdim
8459251662Sdim    Entry.BaseCtor = BaseCtor;
8460251662Sdim    Entry.DerivedCtor = DerivedCtor;
8461218893Sdim  }
8462251662Sdim
8463251662Sdim  Sema &SemaRef;
8464251662Sdim  CXXRecordDecl *Derived;
8465251662Sdim  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8466251662Sdim  MapType Map;
8467251662Sdim};
8468218893Sdim}
8469218893Sdim
8470251662Sdimvoid Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8471251662Sdim  // Defer declaring the inheriting constructors until the class is
8472251662Sdim  // instantiated.
8473251662Sdim  if (ClassDecl->isDependentContext())
8474251662Sdim    return;
8475251662Sdim
8476251662Sdim  // Find base classes from which we might inherit constructors.
8477251662Sdim  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8478251662Sdim  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8479251662Sdim                                          BaseE = ClassDecl->bases_end();
8480251662Sdim       BaseIt != BaseE; ++BaseIt)
8481251662Sdim    if (BaseIt->getInheritConstructors())
8482251662Sdim      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8483251662Sdim
8484251662Sdim  // Go no further if we're not inheriting any constructors.
8485251662Sdim  if (InheritedBases.empty())
8486251662Sdim    return;
8487251662Sdim
8488251662Sdim  // Declare the inherited constructors.
8489251662Sdim  InheritingConstructorInfo ICI(*this, ClassDecl);
8490251662Sdim  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8491251662Sdim    ICI.inheritAll(InheritedBases[I]);
8492251662Sdim}
8493251662Sdim
8494249423Sdimvoid Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8495249423Sdim                                       CXXConstructorDecl *Constructor) {
8496249423Sdim  CXXRecordDecl *ClassDecl = Constructor->getParent();
8497249423Sdim  assert(Constructor->getInheritedConstructor() &&
8498249423Sdim         !Constructor->doesThisDeclarationHaveABody() &&
8499249423Sdim         !Constructor->isDeleted());
8500249423Sdim
8501249423Sdim  SynthesizedFunctionScope Scope(*this, Constructor);
8502249423Sdim  DiagnosticErrorTrap Trap(Diags);
8503249423Sdim  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8504249423Sdim      Trap.hasErrorOccurred()) {
8505249423Sdim    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8506249423Sdim      << Context.getTagDeclType(ClassDecl);
8507249423Sdim    Constructor->setInvalidDecl();
8508249423Sdim    return;
8509249423Sdim  }
8510249423Sdim
8511249423Sdim  SourceLocation Loc = Constructor->getLocation();
8512249423Sdim  Constructor->setBody(new (Context) CompoundStmt(Loc));
8513249423Sdim
8514263508Sdim  Constructor->markUsed(Context);
8515249423Sdim  MarkVTableUsed(CurrentLocation, ClassDecl);
8516249423Sdim
8517249423Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
8518249423Sdim    L->CompletedImplicitDefinition(Constructor);
8519249423Sdim  }
8520249423Sdim}
8521249423Sdim
8522249423Sdim
8523223017SdimSema::ImplicitExceptionSpecification
8524239462SdimSema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8525239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
8526239462Sdim
8527210299Sed  // C++ [except.spec]p14:
8528210299Sed  //   An implicitly declared special member function (Clause 12) shall have
8529210299Sed  //   an exception-specification.
8530234982Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
8531224145Sdim  if (ClassDecl->isInvalidDecl())
8532224145Sdim    return ExceptSpec;
8533224145Sdim
8534210299Sed  // Direct base-class destructors.
8535210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8536210299Sed                                       BEnd = ClassDecl->bases_end();
8537210299Sed       B != BEnd; ++B) {
8538210299Sed    if (B->isVirtual()) // Handled below.
8539210299Sed      continue;
8540210299Sed
8541210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8542234982Sdim      ExceptSpec.CalledDecl(B->getLocStart(),
8543223017Sdim                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8544210299Sed  }
8545223017Sdim
8546210299Sed  // Virtual base-class destructors.
8547210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8548210299Sed                                       BEnd = ClassDecl->vbases_end();
8549210299Sed       B != BEnd; ++B) {
8550210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8551234982Sdim      ExceptSpec.CalledDecl(B->getLocStart(),
8552223017Sdim                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8553210299Sed  }
8554223017Sdim
8555210299Sed  // Field destructors.
8556210299Sed  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8557210299Sed                               FEnd = ClassDecl->field_end();
8558210299Sed       F != FEnd; ++F) {
8559210299Sed    if (const RecordType *RecordTy
8560210299Sed        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8561234982Sdim      ExceptSpec.CalledDecl(F->getLocation(),
8562223017Sdim                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8563210299Sed  }
8564221345Sdim
8565223017Sdim  return ExceptSpec;
8566223017Sdim}
8567223017Sdim
8568223017SdimCXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8569223017Sdim  // C++ [class.dtor]p2:
8570223017Sdim  //   If a class has no user-declared destructor, a destructor is
8571223017Sdim  //   declared implicitly. An implicitly-declared destructor is an
8572223017Sdim  //   inline public member of its class.
8573249423Sdim  assert(ClassDecl->needsImplicitDestructor());
8574223017Sdim
8575249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8576249423Sdim  if (DSM.isAlreadyBeingDeclared())
8577249423Sdim    return 0;
8578249423Sdim
8579210299Sed  // Create the actual destructor declaration.
8580210299Sed  CanQualType ClassType
8581210299Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8582221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
8583210299Sed  DeclarationName Name
8584210299Sed    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8585221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
8586210299Sed  CXXDestructorDecl *Destructor
8587239462Sdim      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8588239462Sdim                                  QualType(), 0, /*isInline=*/true,
8589221345Sdim                                  /*isImplicitlyDeclared=*/true);
8590210299Sed  Destructor->setAccess(AS_public);
8591223017Sdim  Destructor->setDefaulted();
8592210299Sed  Destructor->setImplicit();
8593239462Sdim
8594239462Sdim  // Build an exception specification pointing back at this destructor.
8595263508Sdim  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8596251662Sdim  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8597239462Sdim
8598249423Sdim  AddOverriddenMethods(ClassDecl, Destructor);
8599249423Sdim
8600249423Sdim  // We don't need to use SpecialMemberIsTrivial here; triviality for
8601249423Sdim  // destructors is easy to compute.
8602249423Sdim  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8603249423Sdim
8604249423Sdim  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8605249423Sdim    SetDeclDeleted(Destructor, ClassLoc);
8606249423Sdim
8607210299Sed  // Note that we have declared this destructor.
8608210299Sed  ++ASTContext::NumImplicitDestructorsDeclared;
8609239462Sdim
8610210299Sed  // Introduce this destructor into its scope.
8611210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
8612210299Sed    PushOnScopeChains(Destructor, S, false);
8613210299Sed  ClassDecl->addDecl(Destructor);
8614223017Sdim
8615210299Sed  return Destructor;
8616210299Sed}
8617210299Sed
8618195099Sedvoid Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8619198092Srdivacky                                    CXXDestructorDecl *Destructor) {
8620223017Sdim  assert((Destructor->isDefaulted() &&
8621234353Sdim          !Destructor->doesThisDeclarationHaveABody() &&
8622234353Sdim          !Destructor->isDeleted()) &&
8623195099Sed         "DefineImplicitDestructor - call it for implicit default dtor");
8624199482Srdivacky  CXXRecordDecl *ClassDecl = Destructor->getParent();
8625195099Sed  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8626203955Srdivacky
8627208600Srdivacky  if (Destructor->isInvalidDecl())
8628208600Srdivacky    return;
8629208600Srdivacky
8630243830Sdim  SynthesizedFunctionScope Scope(*this, Destructor);
8631203955Srdivacky
8632218893Sdim  DiagnosticErrorTrap Trap(Diags);
8633205408Srdivacky  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8634205408Srdivacky                                         Destructor->getParent());
8635198092Srdivacky
8636208600Srdivacky  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8637199990Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
8638199990Srdivacky      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8639199990Srdivacky
8640199990Srdivacky    Destructor->setInvalidDecl();
8641199990Srdivacky    return;
8642199990Srdivacky  }
8643199990Srdivacky
8644218893Sdim  SourceLocation Loc = Destructor->getLocation();
8645239462Sdim  Destructor->setBody(new (Context) CompoundStmt(Loc));
8646263508Sdim  Destructor->markUsed(Context);
8647208600Srdivacky  MarkVTableUsed(CurrentLocation, ClassDecl);
8648221345Sdim
8649221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
8650221345Sdim    L->CompletedImplicitDefinition(Destructor);
8651221345Sdim  }
8652195099Sed}
8653195099Sed
8654235864Sdim/// \brief Perform any semantic analysis which needs to be delayed until all
8655235864Sdim/// pending class member declarations have been parsed.
8656235864Sdimvoid Sema::ActOnFinishCXXMemberDecls() {
8657249423Sdim  // If the context is an invalid C++ class, just suppress these checks.
8658249423Sdim  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8659249423Sdim    if (Record->isInvalidDecl()) {
8660263508Sdim      DelayedDefaultedMemberExceptionSpecs.clear();
8661249423Sdim      DelayedDestructorExceptionSpecChecks.clear();
8662249423Sdim      return;
8663249423Sdim    }
8664249423Sdim  }
8665235864Sdim}
8666235864Sdim
8667239462Sdimvoid Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8668239462Sdim                                         CXXDestructorDecl *Destructor) {
8669249423Sdim  assert(getLangOpts().CPlusPlus11 &&
8670239462Sdim         "adjusting dtor exception specs was introduced in c++11");
8671239462Sdim
8672223017Sdim  // C++11 [class.dtor]p3:
8673223017Sdim  //   A declaration of a destructor that does not have an exception-
8674223017Sdim  //   specification is implicitly considered to have the same exception-
8675223017Sdim  //   specification as an implicit declaration.
8676239462Sdim  const FunctionProtoType *DtorType = Destructor->getType()->
8677223017Sdim                                        getAs<FunctionProtoType>();
8678239462Sdim  if (DtorType->hasExceptionSpec())
8679223017Sdim    return;
8680223017Sdim
8681226633Sdim  // Replace the destructor's type, building off the existing one. Fortunately,
8682226633Sdim  // the only thing of interest in the destructor type is its extended info.
8683226633Sdim  // The return and arguments are fixed.
8684239462Sdim  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8685239462Sdim  EPI.ExceptionSpecType = EST_Unevaluated;
8686239462Sdim  EPI.ExceptionSpecDecl = Destructor;
8687251662Sdim  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8688223017Sdim
8689223017Sdim  // FIXME: If the destructor has a body that could throw, and the newly created
8690223017Sdim  // spec doesn't allow exceptions, we should emit a warning, because this
8691223017Sdim  // change in behavior can break conforming C++03 programs at runtime.
8692239462Sdim  // However, we don't have a body or an exception specification yet, so it
8693239462Sdim  // needs to be done somewhere else.
8694223017Sdim}
8695223017Sdim
8696263508Sdimnamespace {
8697263508Sdim/// \brief An abstract base class for all helper classes used in building the
8698263508Sdim//  copy/move operators. These classes serve as factory functions and help us
8699263508Sdim//  avoid using the same Expr* in the AST twice.
8700263508Sdimclass ExprBuilder {
8701263508Sdim  ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8702263508Sdim  ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8703263508Sdim
8704263508Sdimprotected:
8705263508Sdim  static Expr *assertNotNull(Expr *E) {
8706263508Sdim    assert(E && "Expression construction must not fail.");
8707263508Sdim    return E;
8708263508Sdim  }
8709263508Sdim
8710263508Sdimpublic:
8711263508Sdim  ExprBuilder() {}
8712263508Sdim  virtual ~ExprBuilder() {}
8713263508Sdim
8714263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8715263508Sdim};
8716263508Sdim
8717263508Sdimclass RefBuilder: public ExprBuilder {
8718263508Sdim  VarDecl *Var;
8719263508Sdim  QualType VarType;
8720263508Sdim
8721263508Sdimpublic:
8722263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8723263508Sdim    return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8724263508Sdim  }
8725263508Sdim
8726263508Sdim  RefBuilder(VarDecl *Var, QualType VarType)
8727263508Sdim      : Var(Var), VarType(VarType) {}
8728263508Sdim};
8729263508Sdim
8730263508Sdimclass ThisBuilder: public ExprBuilder {
8731263508Sdimpublic:
8732263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8733263508Sdim    return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8734263508Sdim  }
8735263508Sdim};
8736263508Sdim
8737263508Sdimclass CastBuilder: public ExprBuilder {
8738263508Sdim  const ExprBuilder &Builder;
8739263508Sdim  QualType Type;
8740263508Sdim  ExprValueKind Kind;
8741263508Sdim  const CXXCastPath &Path;
8742263508Sdim
8743263508Sdimpublic:
8744263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8745263508Sdim    return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8746263508Sdim                                             CK_UncheckedDerivedToBase, Kind,
8747263508Sdim                                             &Path).take());
8748263508Sdim  }
8749263508Sdim
8750263508Sdim  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8751263508Sdim              const CXXCastPath &Path)
8752263508Sdim      : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8753263508Sdim};
8754263508Sdim
8755263508Sdimclass DerefBuilder: public ExprBuilder {
8756263508Sdim  const ExprBuilder &Builder;
8757263508Sdim
8758263508Sdimpublic:
8759263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8760263508Sdim    return assertNotNull(
8761263508Sdim        S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8762263508Sdim  }
8763263508Sdim
8764263508Sdim  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8765263508Sdim};
8766263508Sdim
8767263508Sdimclass MemberBuilder: public ExprBuilder {
8768263508Sdim  const ExprBuilder &Builder;
8769263508Sdim  QualType Type;
8770263508Sdim  CXXScopeSpec SS;
8771263508Sdim  bool IsArrow;
8772263508Sdim  LookupResult &MemberLookup;
8773263508Sdim
8774263508Sdimpublic:
8775263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8776263508Sdim    return assertNotNull(S.BuildMemberReferenceExpr(
8777263508Sdim        Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8778263508Sdim        MemberLookup, 0).take());
8779263508Sdim  }
8780263508Sdim
8781263508Sdim  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8782263508Sdim                LookupResult &MemberLookup)
8783263508Sdim      : Builder(Builder), Type(Type), IsArrow(IsArrow),
8784263508Sdim        MemberLookup(MemberLookup) {}
8785263508Sdim};
8786263508Sdim
8787263508Sdimclass MoveCastBuilder: public ExprBuilder {
8788263508Sdim  const ExprBuilder &Builder;
8789263508Sdim
8790263508Sdimpublic:
8791263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8792263508Sdim    return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8793263508Sdim  }
8794263508Sdim
8795263508Sdim  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8796263508Sdim};
8797263508Sdim
8798263508Sdimclass LvalueConvBuilder: public ExprBuilder {
8799263508Sdim  const ExprBuilder &Builder;
8800263508Sdim
8801263508Sdimpublic:
8802263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8803263508Sdim    return assertNotNull(
8804263508Sdim        S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8805263508Sdim  }
8806263508Sdim
8807263508Sdim  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8808263508Sdim};
8809263508Sdim
8810263508Sdimclass SubscriptBuilder: public ExprBuilder {
8811263508Sdim  const ExprBuilder &Base;
8812263508Sdim  const ExprBuilder &Index;
8813263508Sdim
8814263508Sdimpublic:
8815263508Sdim  virtual Expr *build(Sema &S, SourceLocation Loc) const
8816263508Sdim      LLVM_OVERRIDE {
8817263508Sdim    return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8818263508Sdim        Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8819263508Sdim  }
8820263508Sdim
8821263508Sdim  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8822263508Sdim      : Base(Base), Index(Index) {}
8823263508Sdim};
8824263508Sdim
8825263508Sdim} // end anonymous namespace
8826263508Sdim
8827249423Sdim/// When generating a defaulted copy or move assignment operator, if a field
8828249423Sdim/// should be copied with __builtin_memcpy rather than via explicit assignments,
8829249423Sdim/// do so. This optimization only applies for arrays of scalars, and for arrays
8830249423Sdim/// of class type where the selected copy/move-assignment operator is trivial.
8831249423Sdimstatic StmtResult
8832249423SdimbuildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8833263508Sdim                           const ExprBuilder &ToB, const ExprBuilder &FromB) {
8834249423Sdim  // Compute the size of the memory buffer to be copied.
8835249423Sdim  QualType SizeType = S.Context.getSizeType();
8836249423Sdim  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8837249423Sdim                   S.Context.getTypeSizeInChars(T).getQuantity());
8838249423Sdim
8839249423Sdim  // Take the address of the field references for "from" and "to". We
8840249423Sdim  // directly construct UnaryOperators here because semantic analysis
8841249423Sdim  // does not permit us to take the address of an xvalue.
8842263508Sdim  Expr *From = FromB.build(S, Loc);
8843249423Sdim  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8844249423Sdim                         S.Context.getPointerType(From->getType()),
8845249423Sdim                         VK_RValue, OK_Ordinary, Loc);
8846263508Sdim  Expr *To = ToB.build(S, Loc);
8847249423Sdim  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8848249423Sdim                       S.Context.getPointerType(To->getType()),
8849249423Sdim                       VK_RValue, OK_Ordinary, Loc);
8850249423Sdim
8851249423Sdim  const Type *E = T->getBaseElementTypeUnsafe();
8852249423Sdim  bool NeedsCollectableMemCpy =
8853249423Sdim    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8854249423Sdim
8855249423Sdim  // Create a reference to the __builtin_objc_memmove_collectable function
8856249423Sdim  StringRef MemCpyName = NeedsCollectableMemCpy ?
8857249423Sdim    "__builtin_objc_memmove_collectable" :
8858249423Sdim    "__builtin_memcpy";
8859249423Sdim  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8860249423Sdim                 Sema::LookupOrdinaryName);
8861249423Sdim  S.LookupName(R, S.TUScope, true);
8862249423Sdim
8863249423Sdim  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8864249423Sdim  if (!MemCpy)
8865249423Sdim    // Something went horribly wrong earlier, and we will have complained
8866249423Sdim    // about it.
8867249423Sdim    return StmtError();
8868249423Sdim
8869249423Sdim  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8870249423Sdim                                            VK_RValue, Loc, 0);
8871249423Sdim  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8872249423Sdim
8873249423Sdim  Expr *CallArgs[] = {
8874249423Sdim    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8875249423Sdim  };
8876249423Sdim  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8877249423Sdim                                    Loc, CallArgs, Loc);
8878249423Sdim
8879249423Sdim  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8880249423Sdim  return S.Owned(Call.takeAs<Stmt>());
8881249423Sdim}
8882249423Sdim
8883226633Sdim/// \brief Builds a statement that copies/moves the given entity from \p From to
8884207619Srdivacky/// \c To.
8885207619Srdivacky///
8886226633Sdim/// This routine is used to copy/move the members of a class with an
8887226633Sdim/// implicitly-declared copy/move assignment operator. When the entities being
8888207619Srdivacky/// copied are arrays, this routine builds for loops to copy them.
8889207619Srdivacky///
8890207619Srdivacky/// \param S The Sema object used for type-checking.
8891207619Srdivacky///
8892226633Sdim/// \param Loc The location where the implicit copy/move is being generated.
8893207619Srdivacky///
8894226633Sdim/// \param T The type of the expressions being copied/moved. Both expressions
8895226633Sdim/// must have this type.
8896207619Srdivacky///
8897226633Sdim/// \param To The expression we are copying/moving to.
8898207619Srdivacky///
8899226633Sdim/// \param From The expression we are copying/moving from.
8900207619Srdivacky///
8901226633Sdim/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8902207632Srdivacky/// Otherwise, it's a non-static member subobject.
8903207632Srdivacky///
8904226633Sdim/// \param Copying Whether we're copying or moving.
8905226633Sdim///
8906207619Srdivacky/// \param Depth Internal parameter recording the depth of the recursion.
8907207619Srdivacky///
8908249423Sdim/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8909249423Sdim/// if a memcpy should be used instead.
8910212904Sdimstatic StmtResult
8911249423SdimbuildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8912263508Sdim                                 const ExprBuilder &To, const ExprBuilder &From,
8913249423Sdim                                 bool CopyingBaseSubobject, bool Copying,
8914249423Sdim                                 unsigned Depth = 0) {
8915249423Sdim  // C++11 [class.copy]p28:
8916207619Srdivacky  //   Each subobject is assigned in the manner appropriate to its type:
8917207619Srdivacky  //
8918226633Sdim  //     - if the subobject is of class type, as if by a call to operator= with
8919226633Sdim  //       the subobject as the object expression and the corresponding
8920226633Sdim  //       subobject of x as a single function argument (as if by explicit
8921226633Sdim  //       qualification; that is, ignoring any possible virtual overriding
8922226633Sdim  //       functions in more derived classes);
8923249423Sdim  //
8924249423Sdim  // C++03 [class.copy]p13:
8925249423Sdim  //     - if the subobject is of class type, the copy assignment operator for
8926249423Sdim  //       the class is used (as if by explicit qualification; that is,
8927249423Sdim  //       ignoring any possible virtual overriding functions in more derived
8928249423Sdim  //       classes);
8929207619Srdivacky  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8930207619Srdivacky    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8931249423Sdim
8932207619Srdivacky    // Look for operator=.
8933207619Srdivacky    DeclarationName Name
8934207619Srdivacky      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8935207619Srdivacky    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8936207619Srdivacky    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8937226633Sdim
8938249423Sdim    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8939249423Sdim    // operator.
8940249423Sdim    if (!S.getLangOpts().CPlusPlus11) {
8941249423Sdim      LookupResult::Filter F = OpLookup.makeFilter();
8942249423Sdim      while (F.hasNext()) {
8943249423Sdim        NamedDecl *D = F.next();
8944249423Sdim        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8945249423Sdim          if (Method->isCopyAssignmentOperator() ||
8946249423Sdim              (!Copying && Method->isMoveAssignmentOperator()))
8947249423Sdim            continue;
8948249423Sdim
8949249423Sdim        F.erase();
8950249423Sdim      }
8951249423Sdim      F.done();
8952207619Srdivacky    }
8953249423Sdim
8954207632Srdivacky    // Suppress the protected check (C++ [class.protected]) for each of the
8955249423Sdim    // assignment operators we found. This strange dance is required when
8956207632Srdivacky    // we're assigning via a base classes's copy-assignment operator. To
8957249423Sdim    // ensure that we're getting the right base class subobject (without
8958207632Srdivacky    // ambiguities), we need to cast "this" to that subobject type; to
8959207632Srdivacky    // ensure that we don't go through the virtual call mechanism, we need
8960207632Srdivacky    // to qualify the operator= name with the base class (see below). However,
8961207632Srdivacky    // this means that if the base class has a protected copy assignment
8962207632Srdivacky    // operator, the protected member access check will fail. So, we
8963207632Srdivacky    // rewrite "protected" access to "public" access in this case, since we
8964207632Srdivacky    // know by construction that we're calling from a derived class.
8965207632Srdivacky    if (CopyingBaseSubobject) {
8966207632Srdivacky      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8967207632Srdivacky           L != LEnd; ++L) {
8968207632Srdivacky        if (L.getAccess() == AS_protected)
8969207632Srdivacky          L.setAccess(AS_public);
8970207632Srdivacky      }
8971207632Srdivacky    }
8972249423Sdim
8973207619Srdivacky    // Create the nested-name-specifier that will be used to qualify the
8974207619Srdivacky    // reference to operator=; this is required to suppress the virtual
8975207619Srdivacky    // call mechanism.
8976207619Srdivacky    CXXScopeSpec SS;
8977234353Sdim    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8978249423Sdim    SS.MakeTrivial(S.Context,
8979249423Sdim                   NestedNameSpecifier::Create(S.Context, 0, false,
8980234353Sdim                                               CanonicalT),
8981219077Sdim                   Loc);
8982249423Sdim
8983207619Srdivacky    // Create the reference to operator=.
8984212904Sdim    ExprResult OpEqualRef
8985263508Sdim      = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8986263508Sdim                                   SS, /*TemplateKWLoc=*/SourceLocation(),
8987234353Sdim                                   /*FirstQualifierInScope=*/0,
8988234353Sdim                                   OpLookup,
8989207619Srdivacky                                   /*TemplateArgs=*/0,
8990207619Srdivacky                                   /*SuppressQualifierCheck=*/true);
8991207619Srdivacky    if (OpEqualRef.isInvalid())
8992212904Sdim      return StmtError();
8993249423Sdim
8994207619Srdivacky    // Build the call to the assignment operator.
8995212904Sdim
8996263508Sdim    Expr *FromInst = From.build(S, Loc);
8997249423Sdim    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8998218893Sdim                                                  OpEqualRef.takeAs<Expr>(),
8999263508Sdim                                                  Loc, FromInst, Loc);
9000207619Srdivacky    if (Call.isInvalid())
9001212904Sdim      return StmtError();
9002249423Sdim
9003249423Sdim    // If we built a call to a trivial 'operator=' while copying an array,
9004249423Sdim    // bail out. We'll replace the whole shebang with a memcpy.
9005249423Sdim    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9006249423Sdim    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9007249423Sdim      return StmtResult((Stmt*)0);
9008249423Sdim
9009249423Sdim    // Convert to an expression-statement, and clean up any produced
9010249423Sdim    // temporaries.
9011249423Sdim    return S.ActOnExprStmt(Call);
9012207619Srdivacky  }
9013198092Srdivacky
9014249423Sdim  //     - if the subobject is of scalar type, the built-in assignment
9015207619Srdivacky  //       operator is used.
9016249423Sdim  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9017207619Srdivacky  if (!ArrayTy) {
9018263508Sdim    ExprResult Assignment = S.CreateBuiltinBinOp(
9019263508Sdim        Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9020207619Srdivacky    if (Assignment.isInvalid())
9021212904Sdim      return StmtError();
9022249423Sdim    return S.ActOnExprStmt(Assignment);
9023207619Srdivacky  }
9024249423Sdim
9025249423Sdim  //     - if the subobject is an array, each element is assigned, in the
9026207619Srdivacky  //       manner appropriate to the element type;
9027249423Sdim
9028207619Srdivacky  // Construct a loop over the array bounds, e.g.,
9029207619Srdivacky  //
9030207619Srdivacky  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9031207619Srdivacky  //
9032207619Srdivacky  // that will copy each of the array elements.
9033207619Srdivacky  QualType SizeType = S.Context.getSizeType();
9034249423Sdim
9035207619Srdivacky  // Create the iteration variable.
9036207619Srdivacky  IdentifierInfo *IterationVarName = 0;
9037207619Srdivacky  {
9038234353Sdim    SmallString<8> Str;
9039207619Srdivacky    llvm::raw_svector_ostream OS(Str);
9040207619Srdivacky    OS << "__i" << Depth;
9041207619Srdivacky    IterationVarName = &S.Context.Idents.get(OS.str());
9042207619Srdivacky  }
9043221345Sdim  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9044207619Srdivacky                                          IterationVarName, SizeType,
9045207619Srdivacky                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9046249423Sdim                                          SC_None);
9047249423Sdim
9048207619Srdivacky  // Initialize the iteration variable to zero.
9049207619Srdivacky  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9050212904Sdim  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9051198092Srdivacky
9052263508Sdim  // Creates a reference to the iteration variable.
9053263508Sdim  RefBuilder IterationVarRef(IterationVar, SizeType);
9054263508Sdim  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9055234353Sdim
9056207619Srdivacky  // Create the DeclStmt that holds the iteration variable.
9057207619Srdivacky  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9058249423Sdim
9059249423Sdim  // Subscript the "from" and "to" expressions with the iteration variable.
9060263508Sdim  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9061263508Sdim  MoveCastBuilder FromIndexMove(FromIndexCopy);
9062263508Sdim  const ExprBuilder *FromIndex;
9063263508Sdim  if (Copying)
9064263508Sdim    FromIndex = &FromIndexCopy;
9065263508Sdim  else
9066263508Sdim    FromIndex = &FromIndexMove;
9067249423Sdim
9068263508Sdim  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9069263508Sdim
9070249423Sdim  // Build the copy/move for an individual element of the array.
9071249423Sdim  StmtResult Copy =
9072249423Sdim    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9073263508Sdim                                     ToIndex, *FromIndex, CopyingBaseSubobject,
9074249423Sdim                                     Copying, Depth + 1);
9075249423Sdim  // Bail out if copying fails or if we determined that we should use memcpy.
9076249423Sdim  if (Copy.isInvalid() || !Copy.get())
9077249423Sdim    return Copy;
9078249423Sdim
9079207619Srdivacky  // Create the comparison against the array bound.
9080218893Sdim  llvm::APInt Upper
9081218893Sdim    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9082212904Sdim  Expr *Comparison
9083263508Sdim    = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9084218893Sdim                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9085218893Sdim                                     BO_NE, S.Context.BoolTy,
9086243830Sdim                                     VK_RValue, OK_Ordinary, Loc, false);
9087249423Sdim
9088207619Srdivacky  // Create the pre-increment of the iteration variable.
9089212904Sdim  Expr *Increment
9090263508Sdim    = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9091263508Sdim                                    SizeType, VK_LValue, OK_Ordinary, Loc);
9092226633Sdim
9093207619Srdivacky  // Construct the loop that copies all elements of this array.
9094212904Sdim  return S.ActOnForStmt(Loc, Loc, InitStmt,
9095207619Srdivacky                        S.MakeFullExpr(Comparison),
9096249423Sdim                        0, S.MakeFullDiscardedValueExpr(Increment),
9097212904Sdim                        Loc, Copy.take());
9098207619Srdivacky}
9099203955Srdivacky
9100249423Sdimstatic StmtResult
9101249423SdimbuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9102263508Sdim                      const ExprBuilder &To, const ExprBuilder &From,
9103249423Sdim                      bool CopyingBaseSubobject, bool Copying) {
9104249423Sdim  // Maybe we should use a memcpy?
9105249423Sdim  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9106249423Sdim      T.isTriviallyCopyableType(S.Context))
9107249423Sdim    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9108224145Sdim
9109249423Sdim  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9110249423Sdim                                                     CopyingBaseSubobject,
9111249423Sdim                                                     Copying, 0));
9112224145Sdim
9113249423Sdim  // If we ended up picking a trivial assignment operator for an array of a
9114249423Sdim  // non-trivially-copyable class type, just emit a memcpy.
9115249423Sdim  if (!Result.isInvalid() && !Result.get())
9116249423Sdim    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9117224145Sdim
9118249423Sdim  return Result;
9119239462Sdim}
9120239462Sdim
9121239462SdimSema::ImplicitExceptionSpecification
9122239462SdimSema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9123239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
9124239462Sdim
9125239462Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
9126239462Sdim  if (ClassDecl->isInvalidDecl())
9127239462Sdim    return ExceptSpec;
9128239462Sdim
9129239462Sdim  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9130239462Sdim  assert(T->getNumArgs() == 1 && "not a copy assignment op");
9131239462Sdim  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9132239462Sdim
9133210299Sed  // C++ [except.spec]p14:
9134239462Sdim  //   An implicitly declared special member function (Clause 12) shall have an
9135210299Sed  //   exception-specification. [...]
9136224145Sdim
9137224145Sdim  // It is unspecified whether or not an implicit copy assignment operator
9138224145Sdim  // attempts to deduplicate calls to assignment operators of virtual bases are
9139224145Sdim  // made. As such, this exception specification is effectively unspecified.
9140224145Sdim  // Based on a similar decision made for constness in C++0x, we're erring on
9141224145Sdim  // the side of assuming such calls to be made regardless of whether they
9142224145Sdim  // actually happen.
9143210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9144210299Sed                                       BaseEnd = ClassDecl->bases_end();
9145210299Sed       Base != BaseEnd; ++Base) {
9146224145Sdim    if (Base->isVirtual())
9147224145Sdim      continue;
9148224145Sdim
9149210299Sed    CXXRecordDecl *BaseClassDecl
9150210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9151224145Sdim    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9152224145Sdim                                                            ArgQuals, false, 0))
9153234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9154224145Sdim  }
9155210299Sed
9156224145Sdim  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9157224145Sdim                                       BaseEnd = ClassDecl->vbases_end();
9158224145Sdim       Base != BaseEnd; ++Base) {
9159224145Sdim    CXXRecordDecl *BaseClassDecl
9160224145Sdim      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9161224145Sdim    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9162224145Sdim                                                            ArgQuals, false, 0))
9163234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9164210299Sed  }
9165224145Sdim
9166210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9167210299Sed                                  FieldEnd = ClassDecl->field_end();
9168210299Sed       Field != FieldEnd;
9169210299Sed       ++Field) {
9170239462Sdim    QualType FieldType = Context.getBaseElementType(Field->getType());
9171224145Sdim    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9172224145Sdim      if (CXXMethodDecl *CopyAssign =
9173239462Sdim          LookupCopyingAssignment(FieldClassDecl,
9174239462Sdim                                  ArgQuals | FieldType.getCVRQualifiers(),
9175239462Sdim                                  false, 0))
9176234982Sdim        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9177224145Sdim    }
9178210299Sed  }
9179221345Sdim
9180239462Sdim  return ExceptSpec;
9181223017Sdim}
9182223017Sdim
9183223017SdimCXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9184223017Sdim  // Note: The following rules are largely analoguous to the copy
9185223017Sdim  // constructor rules. Note that virtual bases are not taken into account
9186223017Sdim  // for determining the argument type of the operator. Note also that
9187223017Sdim  // operators taking an object instead of a reference are allowed.
9188249423Sdim  assert(ClassDecl->needsImplicitCopyAssignment());
9189223017Sdim
9190249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9191249423Sdim  if (DSM.isAlreadyBeingDeclared())
9192249423Sdim    return 0;
9193249423Sdim
9194223017Sdim  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9195223017Sdim  QualType RetType = Context.getLValueReferenceType(ArgType);
9196263508Sdim  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9197263508Sdim  if (Const)
9198223017Sdim    ArgType = ArgType.withConst();
9199223017Sdim  ArgType = Context.getLValueReferenceType(ArgType);
9200223017Sdim
9201263508Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9202263508Sdim                                                     CXXCopyAssignment,
9203263508Sdim                                                     Const);
9204263508Sdim
9205210299Sed  //   An implicitly-declared copy assignment operator is an inline public
9206210299Sed  //   member of its class.
9207210299Sed  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9208221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
9209221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
9210263508Sdim  CXXMethodDecl *CopyAssignment =
9211263508Sdim      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9212263508Sdim                            /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9213263508Sdim                            /*isInline=*/ true, Constexpr, SourceLocation());
9214210299Sed  CopyAssignment->setAccess(AS_public);
9215223017Sdim  CopyAssignment->setDefaulted();
9216210299Sed  CopyAssignment->setImplicit();
9217239462Sdim
9218239462Sdim  // Build an exception specification pointing back at this member.
9219263508Sdim  FunctionProtoType::ExtProtoInfo EPI =
9220263508Sdim      getImplicitMethodEPI(*this, CopyAssignment);
9221249423Sdim  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9222239462Sdim
9223210299Sed  // Add the parameter to the operator.
9224210299Sed  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9225221345Sdim                                               ClassLoc, ClassLoc, /*Id=*/0,
9226210299Sed                                               ArgType, /*TInfo=*/0,
9227212904Sdim                                               SC_None, 0);
9228226633Sdim  CopyAssignment->setParams(FromParam);
9229223017Sdim
9230249423Sdim  AddOverriddenMethods(ClassDecl, CopyAssignment);
9231249423Sdim
9232249423Sdim  CopyAssignment->setTrivial(
9233249423Sdim    ClassDecl->needsOverloadResolutionForCopyAssignment()
9234249423Sdim      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9235249423Sdim      : ClassDecl->hasTrivialCopyAssignment());
9236249423Sdim
9237234353Sdim  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9238249423Sdim    SetDeclDeleted(CopyAssignment, ClassLoc);
9239234353Sdim
9240249423Sdim  // Note that we have added this copy-assignment operator.
9241249423Sdim  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9242249423Sdim
9243249423Sdim  if (Scope *S = getScopeForContext(ClassDecl))
9244249423Sdim    PushOnScopeChains(CopyAssignment, S, false);
9245249423Sdim  ClassDecl->addDecl(CopyAssignment);
9246249423Sdim
9247210299Sed  return CopyAssignment;
9248210299Sed}
9249210299Sed
9250263508Sdim/// Diagnose an implicit copy operation for a class which is odr-used, but
9251263508Sdim/// which is deprecated because the class has a user-declared copy constructor,
9252263508Sdim/// copy assignment operator, or destructor.
9253263508Sdimstatic void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9254263508Sdim                                            SourceLocation UseLoc) {
9255263508Sdim  assert(CopyOp->isImplicit());
9256263508Sdim
9257263508Sdim  CXXRecordDecl *RD = CopyOp->getParent();
9258263508Sdim  CXXMethodDecl *UserDeclaredOperation = 0;
9259263508Sdim
9260263508Sdim  // In Microsoft mode, assignment operations don't affect constructors and
9261263508Sdim  // vice versa.
9262263508Sdim  if (RD->hasUserDeclaredDestructor()) {
9263263508Sdim    UserDeclaredOperation = RD->getDestructor();
9264263508Sdim  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9265263508Sdim             RD->hasUserDeclaredCopyConstructor() &&
9266263508Sdim             !S.getLangOpts().MicrosoftMode) {
9267263508Sdim    // Find any user-declared copy constructor.
9268263508Sdim    for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9269263508Sdim                                      E = RD->ctor_end(); I != E; ++I) {
9270263508Sdim      if (I->isCopyConstructor()) {
9271263508Sdim        UserDeclaredOperation = *I;
9272263508Sdim        break;
9273263508Sdim      }
9274263508Sdim    }
9275263508Sdim    assert(UserDeclaredOperation);
9276263508Sdim  } else if (isa<CXXConstructorDecl>(CopyOp) &&
9277263508Sdim             RD->hasUserDeclaredCopyAssignment() &&
9278263508Sdim             !S.getLangOpts().MicrosoftMode) {
9279263508Sdim    // Find any user-declared move assignment operator.
9280263508Sdim    for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9281263508Sdim                                        E = RD->method_end(); I != E; ++I) {
9282263508Sdim      if (I->isCopyAssignmentOperator()) {
9283263508Sdim        UserDeclaredOperation = *I;
9284263508Sdim        break;
9285263508Sdim      }
9286263508Sdim    }
9287263508Sdim    assert(UserDeclaredOperation);
9288263508Sdim  }
9289263508Sdim
9290263508Sdim  if (UserDeclaredOperation) {
9291263508Sdim    S.Diag(UserDeclaredOperation->getLocation(),
9292263508Sdim         diag::warn_deprecated_copy_operation)
9293263508Sdim      << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9294263508Sdim      << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9295263508Sdim    S.Diag(UseLoc, diag::note_member_synthesized_at)
9296263508Sdim      << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9297263508Sdim                                          : Sema::CXXCopyAssignment)
9298263508Sdim      << RD;
9299263508Sdim  }
9300263508Sdim}
9301263508Sdim
9302207619Srdivackyvoid Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9303207619Srdivacky                                        CXXMethodDecl *CopyAssignOperator) {
9304223017Sdim  assert((CopyAssignOperator->isDefaulted() &&
9305207619Srdivacky          CopyAssignOperator->isOverloadedOperator() &&
9306207619Srdivacky          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9307234353Sdim          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9308234353Sdim          !CopyAssignOperator->isDeleted()) &&
9309207619Srdivacky         "DefineImplicitCopyAssignment called for wrong function");
9310207619Srdivacky
9311207619Srdivacky  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9312207619Srdivacky
9313207619Srdivacky  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9314207619Srdivacky    CopyAssignOperator->setInvalidDecl();
9315207619Srdivacky    return;
9316207619Srdivacky  }
9317207619Srdivacky
9318263508Sdim  // C++11 [class.copy]p18:
9319263508Sdim  //   The [definition of an implicitly declared copy assignment operator] is
9320263508Sdim  //   deprecated if the class has a user-declared copy constructor or a
9321263508Sdim  //   user-declared destructor.
9322263508Sdim  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9323263508Sdim    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9324263508Sdim
9325263508Sdim  CopyAssignOperator->markUsed(Context);
9326263508Sdim
9327243830Sdim  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9328218893Sdim  DiagnosticErrorTrap Trap(Diags);
9329207619Srdivacky
9330207619Srdivacky  // C++0x [class.copy]p30:
9331207619Srdivacky  //   The implicitly-defined or explicitly-defaulted copy assignment operator
9332207619Srdivacky  //   for a non-union class X performs memberwise copy assignment of its
9333207619Srdivacky  //   subobjects. The direct base classes of X are assigned first, in the
9334207619Srdivacky  //   order of their declaration in the base-specifier-list, and then the
9335207619Srdivacky  //   immediate non-static data members of X are assigned, in the order in
9336207619Srdivacky  //   which they were declared in the class definition.
9337207619Srdivacky
9338207619Srdivacky  // The statements that form the synthesized function body.
9339243830Sdim  SmallVector<Stmt*, 8> Statements;
9340207619Srdivacky
9341207619Srdivacky  // The parameter for the "other" object, which we are copying from.
9342207619Srdivacky  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9343207619Srdivacky  Qualifiers OtherQuals = Other->getType().getQualifiers();
9344207619Srdivacky  QualType OtherRefType = Other->getType();
9345207619Srdivacky  if (const LValueReferenceType *OtherRef
9346207619Srdivacky                                = OtherRefType->getAs<LValueReferenceType>()) {
9347207619Srdivacky    OtherRefType = OtherRef->getPointeeType();
9348207619Srdivacky    OtherQuals = OtherRefType.getQualifiers();
9349207619Srdivacky  }
9350207619Srdivacky
9351207619Srdivacky  // Our location for everything implicitly-generated.
9352207619Srdivacky  SourceLocation Loc = CopyAssignOperator->getLocation();
9353207619Srdivacky
9354263508Sdim  // Builds a DeclRefExpr for the "other" object.
9355263508Sdim  RefBuilder OtherRef(Other, OtherRefType);
9356263508Sdim
9357263508Sdim  // Builds the "this" pointer.
9358263508Sdim  ThisBuilder This;
9359207619Srdivacky
9360207619Srdivacky  // Assign base classes.
9361207619Srdivacky  bool Invalid = false;
9362195341Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9363195341Sed       E = ClassDecl->bases_end(); Base != E; ++Base) {
9364207619Srdivacky    // Form the assignment:
9365207619Srdivacky    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9366207619Srdivacky    QualType BaseType = Base->getType().getUnqualifiedType();
9367218893Sdim    if (!BaseType->isRecordType()) {
9368207619Srdivacky      Invalid = true;
9369207619Srdivacky      continue;
9370207619Srdivacky    }
9371205219Srdivacky
9372212904Sdim    CXXCastPath BasePath;
9373212904Sdim    BasePath.push_back(Base);
9374212904Sdim
9375207619Srdivacky    // Construct the "from" expression, which is an implicit cast to the
9376207619Srdivacky    // appropriately-qualified base type.
9377263508Sdim    CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9378263508Sdim                     VK_LValue, BasePath);
9379207619Srdivacky
9380207619Srdivacky    // Dereference "this".
9381263508Sdim    DerefBuilder DerefThis(This);
9382263508Sdim    CastBuilder To(DerefThis,
9383263508Sdim                   Context.getCVRQualifiedType(
9384263508Sdim                       BaseType, CopyAssignOperator->getTypeQualifiers()),
9385263508Sdim                   VK_LValue, BasePath);
9386207619Srdivacky
9387207619Srdivacky    // Build the copy.
9388249423Sdim    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9389263508Sdim                                            To, From,
9390226633Sdim                                            /*CopyingBaseSubobject=*/true,
9391226633Sdim                                            /*Copying=*/true);
9392207619Srdivacky    if (Copy.isInvalid()) {
9393208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
9394208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9395208600Srdivacky      CopyAssignOperator->setInvalidDecl();
9396208600Srdivacky      return;
9397205219Srdivacky    }
9398207619Srdivacky
9399207619Srdivacky    // Success! Record the copy.
9400207619Srdivacky    Statements.push_back(Copy.takeAs<Expr>());
9401195099Sed  }
9402207619Srdivacky
9403207619Srdivacky  // Assign non-static members.
9404195341Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9405207619Srdivacky                                  FieldEnd = ClassDecl->field_end();
9406207619Srdivacky       Field != FieldEnd; ++Field) {
9407226633Sdim    if (Field->isUnnamedBitfield())
9408226633Sdim      continue;
9409263508Sdim
9410263508Sdim    if (Field->isInvalidDecl()) {
9411263508Sdim      Invalid = true;
9412263508Sdim      continue;
9413263508Sdim    }
9414263508Sdim
9415207619Srdivacky    // Check for members of reference type; we can't copy those.
9416207619Srdivacky    if (Field->getType()->isReferenceType()) {
9417198092Srdivacky      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9418207619Srdivacky        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9419198092Srdivacky      Diag(Field->getLocation(), diag::note_declared_at);
9420208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
9421208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9422207619Srdivacky      Invalid = true;
9423207619Srdivacky      continue;
9424207619Srdivacky    }
9425207619Srdivacky
9426207619Srdivacky    // Check for members of const-qualified, non-class type.
9427207619Srdivacky    QualType BaseType = Context.getBaseElementType(Field->getType());
9428207619Srdivacky    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9429198092Srdivacky      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9430207619Srdivacky        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9431198092Srdivacky      Diag(Field->getLocation(), diag::note_declared_at);
9432208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
9433208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9434207619Srdivacky      Invalid = true;
9435207619Srdivacky      continue;
9436195099Sed    }
9437224145Sdim
9438224145Sdim    // Suppress assigning zero-width bitfields.
9439226633Sdim    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9440226633Sdim      continue;
9441207619Srdivacky
9442207619Srdivacky    QualType FieldType = Field->getType().getNonReferenceType();
9443208600Srdivacky    if (FieldType->isIncompleteArrayType()) {
9444208600Srdivacky      assert(ClassDecl->hasFlexibleArrayMember() &&
9445208600Srdivacky             "Incomplete array type is not valid");
9446208600Srdivacky      continue;
9447208600Srdivacky    }
9448207619Srdivacky
9449207619Srdivacky    // Build references to the field in the object we're copying from and to.
9450207619Srdivacky    CXXScopeSpec SS; // Intentionally empty
9451207619Srdivacky    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9452207619Srdivacky                              LookupMemberName);
9453207619Srdivacky    MemberLookup.addDecl(*Field);
9454207619Srdivacky    MemberLookup.resolveKind();
9455207619Srdivacky
9456263508Sdim    MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9457263508Sdim
9458263508Sdim    MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9459263508Sdim
9460207619Srdivacky    // Build the copy of this field.
9461249423Sdim    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9462263508Sdim                                            To, From,
9463226633Sdim                                            /*CopyingBaseSubobject=*/false,
9464226633Sdim                                            /*Copying=*/true);
9465207619Srdivacky    if (Copy.isInvalid()) {
9466208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
9467208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9468208600Srdivacky      CopyAssignOperator->setInvalidDecl();
9469208600Srdivacky      return;
9470207619Srdivacky    }
9471207619Srdivacky
9472207619Srdivacky    // Success! Record the copy.
9473207619Srdivacky    Statements.push_back(Copy.takeAs<Stmt>());
9474195099Sed  }
9475203955Srdivacky
9476207619Srdivacky  if (!Invalid) {
9477207619Srdivacky    // Add a "return *this;"
9478263508Sdim    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9479207619Srdivacky
9480212904Sdim    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9481207619Srdivacky    if (Return.isInvalid())
9482207619Srdivacky      Invalid = true;
9483207619Srdivacky    else {
9484207619Srdivacky      Statements.push_back(Return.takeAs<Stmt>());
9485208600Srdivacky
9486208600Srdivacky      if (Trap.hasErrorOccurred()) {
9487208600Srdivacky        Diag(CurrentLocation, diag::note_member_synthesized_at)
9488208600Srdivacky          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9489208600Srdivacky        Invalid = true;
9490208600Srdivacky      }
9491207619Srdivacky    }
9492207619Srdivacky  }
9493195099Sed
9494207619Srdivacky  if (Invalid) {
9495207619Srdivacky    CopyAssignOperator->setInvalidDecl();
9496207619Srdivacky    return;
9497207619Srdivacky  }
9498234353Sdim
9499234353Sdim  StmtResult Body;
9500234353Sdim  {
9501234353Sdim    CompoundScopeRAII CompoundScope(*this);
9502243830Sdim    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9503234353Sdim                             /*isStmtExpr=*/false);
9504234353Sdim    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9505234353Sdim  }
9506207619Srdivacky  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9507221345Sdim
9508221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
9509221345Sdim    L->CompletedImplicitDefinition(CopyAssignOperator);
9510221345Sdim  }
9511195099Sed}
9512195099Sed
9513226633SdimSema::ImplicitExceptionSpecification
9514239462SdimSema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9515239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
9516239462Sdim
9517234982Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
9518226633Sdim  if (ClassDecl->isInvalidDecl())
9519226633Sdim    return ExceptSpec;
9520226633Sdim
9521226633Sdim  // C++0x [except.spec]p14:
9522226633Sdim  //   An implicitly declared special member function (Clause 12) shall have an
9523226633Sdim  //   exception-specification. [...]
9524226633Sdim
9525226633Sdim  // It is unspecified whether or not an implicit move assignment operator
9526226633Sdim  // attempts to deduplicate calls to assignment operators of virtual bases are
9527226633Sdim  // made. As such, this exception specification is effectively unspecified.
9528226633Sdim  // Based on a similar decision made for constness in C++0x, we're erring on
9529226633Sdim  // the side of assuming such calls to be made regardless of whether they
9530226633Sdim  // actually happen.
9531226633Sdim  // Note that a move constructor is not implicitly declared when there are
9532226633Sdim  // virtual bases, but it can still be user-declared and explicitly defaulted.
9533226633Sdim  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9534226633Sdim                                       BaseEnd = ClassDecl->bases_end();
9535226633Sdim       Base != BaseEnd; ++Base) {
9536226633Sdim    if (Base->isVirtual())
9537226633Sdim      continue;
9538226633Sdim
9539226633Sdim    CXXRecordDecl *BaseClassDecl
9540226633Sdim      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9541226633Sdim    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9542239462Sdim                                                           0, false, 0))
9543234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9544226633Sdim  }
9545226633Sdim
9546226633Sdim  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9547226633Sdim                                       BaseEnd = ClassDecl->vbases_end();
9548226633Sdim       Base != BaseEnd; ++Base) {
9549226633Sdim    CXXRecordDecl *BaseClassDecl
9550226633Sdim      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9551226633Sdim    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9552239462Sdim                                                           0, false, 0))
9553234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9554226633Sdim  }
9555226633Sdim
9556226633Sdim  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9557226633Sdim                                  FieldEnd = ClassDecl->field_end();
9558226633Sdim       Field != FieldEnd;
9559226633Sdim       ++Field) {
9560239462Sdim    QualType FieldType = Context.getBaseElementType(Field->getType());
9561226633Sdim    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9562239462Sdim      if (CXXMethodDecl *MoveAssign =
9563239462Sdim              LookupMovingAssignment(FieldClassDecl,
9564239462Sdim                                     FieldType.getCVRQualifiers(),
9565239462Sdim                                     false, 0))
9566234982Sdim        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9567226633Sdim    }
9568226633Sdim  }
9569226633Sdim
9570226633Sdim  return ExceptSpec;
9571226633Sdim}
9572226633Sdim
9573226633SdimCXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9574234353Sdim  assert(ClassDecl->needsImplicitMoveAssignment());
9575234353Sdim
9576249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9577249423Sdim  if (DSM.isAlreadyBeingDeclared())
9578249423Sdim    return 0;
9579249423Sdim
9580226633Sdim  // Note: The following rules are largely analoguous to the move
9581226633Sdim  // constructor rules.
9582226633Sdim
9583226633Sdim  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9584226633Sdim  QualType RetType = Context.getLValueReferenceType(ArgType);
9585226633Sdim  ArgType = Context.getRValueReferenceType(ArgType);
9586226633Sdim
9587263508Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9588263508Sdim                                                     CXXMoveAssignment,
9589263508Sdim                                                     false);
9590263508Sdim
9591226633Sdim  //   An implicitly-declared move assignment operator is an inline public
9592226633Sdim  //   member of its class.
9593226633Sdim  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9594226633Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
9595226633Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
9596263508Sdim  CXXMethodDecl *MoveAssignment =
9597263508Sdim      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9598263508Sdim                            /*TInfo=*/0, /*StorageClass=*/SC_None,
9599263508Sdim                            /*isInline=*/true, Constexpr, SourceLocation());
9600226633Sdim  MoveAssignment->setAccess(AS_public);
9601226633Sdim  MoveAssignment->setDefaulted();
9602226633Sdim  MoveAssignment->setImplicit();
9603226633Sdim
9604239462Sdim  // Build an exception specification pointing back at this member.
9605263508Sdim  FunctionProtoType::ExtProtoInfo EPI =
9606263508Sdim      getImplicitMethodEPI(*this, MoveAssignment);
9607249423Sdim  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9608239462Sdim
9609226633Sdim  // Add the parameter to the operator.
9610226633Sdim  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9611226633Sdim                                               ClassLoc, ClassLoc, /*Id=*/0,
9612226633Sdim                                               ArgType, /*TInfo=*/0,
9613226633Sdim                                               SC_None, 0);
9614226633Sdim  MoveAssignment->setParams(FromParam);
9615226633Sdim
9616249423Sdim  AddOverriddenMethods(ClassDecl, MoveAssignment);
9617226633Sdim
9618249423Sdim  MoveAssignment->setTrivial(
9619249423Sdim    ClassDecl->needsOverloadResolutionForMoveAssignment()
9620249423Sdim      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9621249423Sdim      : ClassDecl->hasTrivialMoveAssignment());
9622249423Sdim
9623234353Sdim  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9624263508Sdim    ClassDecl->setImplicitMoveAssignmentIsDeleted();
9625263508Sdim    SetDeclDeleted(MoveAssignment, ClassLoc);
9626226633Sdim  }
9627226633Sdim
9628249423Sdim  // Note that we have added this copy-assignment operator.
9629249423Sdim  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9630249423Sdim
9631226633Sdim  if (Scope *S = getScopeForContext(ClassDecl))
9632226633Sdim    PushOnScopeChains(MoveAssignment, S, false);
9633226633Sdim  ClassDecl->addDecl(MoveAssignment);
9634226633Sdim
9635226633Sdim  return MoveAssignment;
9636226633Sdim}
9637226633Sdim
9638263508Sdim/// Check if we're implicitly defining a move assignment operator for a class
9639263508Sdim/// with virtual bases. Such a move assignment might move-assign the virtual
9640263508Sdim/// base multiple times.
9641263508Sdimstatic void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9642263508Sdim                                               SourceLocation CurrentLocation) {
9643263508Sdim  assert(!Class->isDependentContext() && "should not define dependent move");
9644263508Sdim
9645263508Sdim  // Only a virtual base could get implicitly move-assigned multiple times.
9646263508Sdim  // Only a non-trivial move assignment can observe this. We only want to
9647263508Sdim  // diagnose if we implicitly define an assignment operator that assigns
9648263508Sdim  // two base classes, both of which move-assign the same virtual base.
9649263508Sdim  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9650263508Sdim      Class->getNumBases() < 2)
9651263508Sdim    return;
9652263508Sdim
9653263508Sdim  llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9654263508Sdim  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9655263508Sdim  VBaseMap VBases;
9656263508Sdim
9657263508Sdim  for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9658263508Sdim                                          BE = Class->bases_end();
9659263508Sdim       BI != BE; ++BI) {
9660263508Sdim    Worklist.push_back(&*BI);
9661263508Sdim    while (!Worklist.empty()) {
9662263508Sdim      CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9663263508Sdim      CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9664263508Sdim
9665263508Sdim      // If the base has no non-trivial move assignment operators,
9666263508Sdim      // we don't care about moves from it.
9667263508Sdim      if (!Base->hasNonTrivialMoveAssignment())
9668263508Sdim        continue;
9669263508Sdim
9670263508Sdim      // If there's nothing virtual here, skip it.
9671263508Sdim      if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9672263508Sdim        continue;
9673263508Sdim
9674263508Sdim      // If we're not actually going to call a move assignment for this base,
9675263508Sdim      // or the selected move assignment is trivial, skip it.
9676263508Sdim      Sema::SpecialMemberOverloadResult *SMOR =
9677263508Sdim        S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9678263508Sdim                              /*ConstArg*/false, /*VolatileArg*/false,
9679263508Sdim                              /*RValueThis*/true, /*ConstThis*/false,
9680263508Sdim                              /*VolatileThis*/false);
9681263508Sdim      if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9682263508Sdim          !SMOR->getMethod()->isMoveAssignmentOperator())
9683263508Sdim        continue;
9684263508Sdim
9685263508Sdim      if (BaseSpec->isVirtual()) {
9686263508Sdim        // We're going to move-assign this virtual base, and its move
9687263508Sdim        // assignment operator is not trivial. If this can happen for
9688263508Sdim        // multiple distinct direct bases of Class, diagnose it. (If it
9689263508Sdim        // only happens in one base, we'll diagnose it when synthesizing
9690263508Sdim        // that base class's move assignment operator.)
9691263508Sdim        CXXBaseSpecifier *&Existing =
9692263508Sdim            VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9693263508Sdim                .first->second;
9694263508Sdim        if (Existing && Existing != BI) {
9695263508Sdim          S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9696263508Sdim            << Class << Base;
9697263508Sdim          S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9698263508Sdim            << (Base->getCanonicalDecl() ==
9699263508Sdim                Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9700263508Sdim            << Base << Existing->getType() << Existing->getSourceRange();
9701263508Sdim          S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9702263508Sdim            << (Base->getCanonicalDecl() ==
9703263508Sdim                BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9704263508Sdim            << Base << BI->getType() << BaseSpec->getSourceRange();
9705263508Sdim
9706263508Sdim          // Only diagnose each vbase once.
9707263508Sdim          Existing = 0;
9708263508Sdim        }
9709263508Sdim      } else {
9710263508Sdim        // Only walk over bases that have defaulted move assignment operators.
9711263508Sdim        // We assume that any user-provided move assignment operator handles
9712263508Sdim        // the multiple-moves-of-vbase case itself somehow.
9713263508Sdim        if (!SMOR->getMethod()->isDefaulted())
9714263508Sdim          continue;
9715263508Sdim
9716263508Sdim        // We're going to move the base classes of Base. Add them to the list.
9717263508Sdim        for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9718263508Sdim                                                BE = Base->bases_end();
9719263508Sdim             BI != BE; ++BI)
9720263508Sdim          Worklist.push_back(&*BI);
9721263508Sdim      }
9722263508Sdim    }
9723263508Sdim  }
9724263508Sdim}
9725263508Sdim
9726226633Sdimvoid Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9727226633Sdim                                        CXXMethodDecl *MoveAssignOperator) {
9728226633Sdim  assert((MoveAssignOperator->isDefaulted() &&
9729226633Sdim          MoveAssignOperator->isOverloadedOperator() &&
9730226633Sdim          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9731234353Sdim          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9732234353Sdim          !MoveAssignOperator->isDeleted()) &&
9733226633Sdim         "DefineImplicitMoveAssignment called for wrong function");
9734226633Sdim
9735226633Sdim  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9736226633Sdim
9737226633Sdim  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9738226633Sdim    MoveAssignOperator->setInvalidDecl();
9739226633Sdim    return;
9740226633Sdim  }
9741226633Sdim
9742263508Sdim  MoveAssignOperator->markUsed(Context);
9743226633Sdim
9744243830Sdim  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9745226633Sdim  DiagnosticErrorTrap Trap(Diags);
9746226633Sdim
9747226633Sdim  // C++0x [class.copy]p28:
9748226633Sdim  //   The implicitly-defined or move assignment operator for a non-union class
9749226633Sdim  //   X performs memberwise move assignment of its subobjects. The direct base
9750226633Sdim  //   classes of X are assigned first, in the order of their declaration in the
9751226633Sdim  //   base-specifier-list, and then the immediate non-static data members of X
9752226633Sdim  //   are assigned, in the order in which they were declared in the class
9753226633Sdim  //   definition.
9754226633Sdim
9755263508Sdim  // Issue a warning if our implicit move assignment operator will move
9756263508Sdim  // from a virtual base more than once.
9757263508Sdim  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9758263508Sdim
9759226633Sdim  // The statements that form the synthesized function body.
9760243830Sdim  SmallVector<Stmt*, 8> Statements;
9761226633Sdim
9762226633Sdim  // The parameter for the "other" object, which we are move from.
9763226633Sdim  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9764226633Sdim  QualType OtherRefType = Other->getType()->
9765226633Sdim      getAs<RValueReferenceType>()->getPointeeType();
9766263508Sdim  assert(!OtherRefType.getQualifiers() &&
9767226633Sdim         "Bad argument type of defaulted move assignment");
9768226633Sdim
9769226633Sdim  // Our location for everything implicitly-generated.
9770226633Sdim  SourceLocation Loc = MoveAssignOperator->getLocation();
9771226633Sdim
9772263508Sdim  // Builds a reference to the "other" object.
9773263508Sdim  RefBuilder OtherRef(Other, OtherRefType);
9774226633Sdim  // Cast to rvalue.
9775263508Sdim  MoveCastBuilder MoveOther(OtherRef);
9776226633Sdim
9777263508Sdim  // Builds the "this" pointer.
9778263508Sdim  ThisBuilder This;
9779234353Sdim
9780226633Sdim  // Assign base classes.
9781226633Sdim  bool Invalid = false;
9782226633Sdim  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9783226633Sdim       E = ClassDecl->bases_end(); Base != E; ++Base) {
9784263508Sdim    // C++11 [class.copy]p28:
9785263508Sdim    //   It is unspecified whether subobjects representing virtual base classes
9786263508Sdim    //   are assigned more than once by the implicitly-defined copy assignment
9787263508Sdim    //   operator.
9788263508Sdim    // FIXME: Do not assign to a vbase that will be assigned by some other base
9789263508Sdim    // class. For a move-assignment, this can result in the vbase being moved
9790263508Sdim    // multiple times.
9791263508Sdim
9792226633Sdim    // Form the assignment:
9793226633Sdim    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9794226633Sdim    QualType BaseType = Base->getType().getUnqualifiedType();
9795226633Sdim    if (!BaseType->isRecordType()) {
9796226633Sdim      Invalid = true;
9797226633Sdim      continue;
9798226633Sdim    }
9799226633Sdim
9800226633Sdim    CXXCastPath BasePath;
9801226633Sdim    BasePath.push_back(Base);
9802226633Sdim
9803226633Sdim    // Construct the "from" expression, which is an implicit cast to the
9804226633Sdim    // appropriately-qualified base type.
9805263508Sdim    CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9806226633Sdim
9807226633Sdim    // Dereference "this".
9808263508Sdim    DerefBuilder DerefThis(This);
9809226633Sdim
9810226633Sdim    // Implicitly cast "this" to the appropriately-qualified base type.
9811263508Sdim    CastBuilder To(DerefThis,
9812263508Sdim                   Context.getCVRQualifiedType(
9813263508Sdim                       BaseType, MoveAssignOperator->getTypeQualifiers()),
9814263508Sdim                   VK_LValue, BasePath);
9815226633Sdim
9816226633Sdim    // Build the move.
9817249423Sdim    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9818263508Sdim                                            To, From,
9819226633Sdim                                            /*CopyingBaseSubobject=*/true,
9820226633Sdim                                            /*Copying=*/false);
9821226633Sdim    if (Move.isInvalid()) {
9822226633Sdim      Diag(CurrentLocation, diag::note_member_synthesized_at)
9823226633Sdim        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9824226633Sdim      MoveAssignOperator->setInvalidDecl();
9825226633Sdim      return;
9826226633Sdim    }
9827226633Sdim
9828226633Sdim    // Success! Record the move.
9829226633Sdim    Statements.push_back(Move.takeAs<Expr>());
9830226633Sdim  }
9831226633Sdim
9832226633Sdim  // Assign non-static members.
9833226633Sdim  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9834226633Sdim                                  FieldEnd = ClassDecl->field_end();
9835226633Sdim       Field != FieldEnd; ++Field) {
9836226633Sdim    if (Field->isUnnamedBitfield())
9837226633Sdim      continue;
9838226633Sdim
9839263508Sdim    if (Field->isInvalidDecl()) {
9840263508Sdim      Invalid = true;
9841263508Sdim      continue;
9842263508Sdim    }
9843263508Sdim
9844226633Sdim    // Check for members of reference type; we can't move those.
9845226633Sdim    if (Field->getType()->isReferenceType()) {
9846226633Sdim      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9847226633Sdim        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9848226633Sdim      Diag(Field->getLocation(), diag::note_declared_at);
9849226633Sdim      Diag(CurrentLocation, diag::note_member_synthesized_at)
9850226633Sdim        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9851226633Sdim      Invalid = true;
9852226633Sdim      continue;
9853226633Sdim    }
9854226633Sdim
9855226633Sdim    // Check for members of const-qualified, non-class type.
9856226633Sdim    QualType BaseType = Context.getBaseElementType(Field->getType());
9857226633Sdim    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9858226633Sdim      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9859226633Sdim        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9860226633Sdim      Diag(Field->getLocation(), diag::note_declared_at);
9861226633Sdim      Diag(CurrentLocation, diag::note_member_synthesized_at)
9862226633Sdim        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9863226633Sdim      Invalid = true;
9864226633Sdim      continue;
9865226633Sdim    }
9866226633Sdim
9867226633Sdim    // Suppress assigning zero-width bitfields.
9868226633Sdim    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9869226633Sdim      continue;
9870226633Sdim
9871226633Sdim    QualType FieldType = Field->getType().getNonReferenceType();
9872226633Sdim    if (FieldType->isIncompleteArrayType()) {
9873226633Sdim      assert(ClassDecl->hasFlexibleArrayMember() &&
9874226633Sdim             "Incomplete array type is not valid");
9875226633Sdim      continue;
9876226633Sdim    }
9877226633Sdim
9878226633Sdim    // Build references to the field in the object we're copying from and to.
9879226633Sdim    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9880226633Sdim                              LookupMemberName);
9881226633Sdim    MemberLookup.addDecl(*Field);
9882226633Sdim    MemberLookup.resolveKind();
9883263508Sdim    MemberBuilder From(MoveOther, OtherRefType,
9884263508Sdim                       /*IsArrow=*/false, MemberLookup);
9885263508Sdim    MemberBuilder To(This, getCurrentThisType(),
9886263508Sdim                     /*IsArrow=*/true, MemberLookup);
9887226633Sdim
9888263508Sdim    assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9889226633Sdim        "Member reference with rvalue base must be rvalue except for reference "
9890226633Sdim        "members, which aren't allowed for move assignment.");
9891226633Sdim
9892226633Sdim    // Build the move of this field.
9893249423Sdim    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9894263508Sdim                                            To, From,
9895226633Sdim                                            /*CopyingBaseSubobject=*/false,
9896226633Sdim                                            /*Copying=*/false);
9897226633Sdim    if (Move.isInvalid()) {
9898226633Sdim      Diag(CurrentLocation, diag::note_member_synthesized_at)
9899226633Sdim        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9900226633Sdim      MoveAssignOperator->setInvalidDecl();
9901226633Sdim      return;
9902226633Sdim    }
9903249423Sdim
9904226633Sdim    // Success! Record the copy.
9905226633Sdim    Statements.push_back(Move.takeAs<Stmt>());
9906226633Sdim  }
9907226633Sdim
9908226633Sdim  if (!Invalid) {
9909226633Sdim    // Add a "return *this;"
9910263508Sdim    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9911226633Sdim
9912226633Sdim    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9913226633Sdim    if (Return.isInvalid())
9914226633Sdim      Invalid = true;
9915226633Sdim    else {
9916226633Sdim      Statements.push_back(Return.takeAs<Stmt>());
9917226633Sdim
9918226633Sdim      if (Trap.hasErrorOccurred()) {
9919226633Sdim        Diag(CurrentLocation, diag::note_member_synthesized_at)
9920226633Sdim          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9921226633Sdim        Invalid = true;
9922226633Sdim      }
9923226633Sdim    }
9924226633Sdim  }
9925226633Sdim
9926226633Sdim  if (Invalid) {
9927226633Sdim    MoveAssignOperator->setInvalidDecl();
9928226633Sdim    return;
9929226633Sdim  }
9930234353Sdim
9931234353Sdim  StmtResult Body;
9932234353Sdim  {
9933234353Sdim    CompoundScopeRAII CompoundScope(*this);
9934243830Sdim    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9935234353Sdim                             /*isStmtExpr=*/false);
9936234353Sdim    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9937234353Sdim  }
9938226633Sdim  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9939226633Sdim
9940226633Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
9941226633Sdim    L->CompletedImplicitDefinition(MoveAssignOperator);
9942226633Sdim  }
9943226633Sdim}
9944226633Sdim
9945239462SdimSema::ImplicitExceptionSpecification
9946239462SdimSema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9947239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
9948239462Sdim
9949239462Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
9950239462Sdim  if (ClassDecl->isInvalidDecl())
9951239462Sdim    return ExceptSpec;
9952239462Sdim
9953239462Sdim  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9954239462Sdim  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9955239462Sdim  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9956239462Sdim
9957210299Sed  // C++ [except.spec]p14:
9958210299Sed  //   An implicitly declared special member function (Clause 12) shall have an
9959210299Sed  //   exception-specification. [...]
9960210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9961210299Sed                                       BaseEnd = ClassDecl->bases_end();
9962210299Sed       Base != BaseEnd;
9963210299Sed       ++Base) {
9964210299Sed    // Virtual bases are handled below.
9965210299Sed    if (Base->isVirtual())
9966210299Sed      continue;
9967210299Sed
9968210299Sed    CXXRecordDecl *BaseClassDecl
9969210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9970223017Sdim    if (CXXConstructorDecl *CopyConstructor =
9971224145Sdim          LookupCopyingConstructor(BaseClassDecl, Quals))
9972234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9973210299Sed  }
9974210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9975210299Sed                                       BaseEnd = ClassDecl->vbases_end();
9976210299Sed       Base != BaseEnd;
9977210299Sed       ++Base) {
9978210299Sed    CXXRecordDecl *BaseClassDecl
9979210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9980223017Sdim    if (CXXConstructorDecl *CopyConstructor =
9981224145Sdim          LookupCopyingConstructor(BaseClassDecl, Quals))
9982234982Sdim      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9983210299Sed  }
9984210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9985210299Sed                                  FieldEnd = ClassDecl->field_end();
9986210299Sed       Field != FieldEnd;
9987210299Sed       ++Field) {
9988239462Sdim    QualType FieldType = Context.getBaseElementType(Field->getType());
9989223017Sdim    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9990223017Sdim      if (CXXConstructorDecl *CopyConstructor =
9991239462Sdim              LookupCopyingConstructor(FieldClassDecl,
9992239462Sdim                                       Quals | FieldType.getCVRQualifiers()))
9993234982Sdim      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9994210299Sed    }
9995210299Sed  }
9996221345Sdim
9997239462Sdim  return ExceptSpec;
9998223017Sdim}
9999223017Sdim
10000223017SdimCXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10001223017Sdim                                                    CXXRecordDecl *ClassDecl) {
10002223017Sdim  // C++ [class.copy]p4:
10003223017Sdim  //   If the class definition does not explicitly declare a copy
10004223017Sdim  //   constructor, one is declared implicitly.
10005249423Sdim  assert(ClassDecl->needsImplicitCopyConstructor());
10006223017Sdim
10007249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10008249423Sdim  if (DSM.isAlreadyBeingDeclared())
10009249423Sdim    return 0;
10010249423Sdim
10011223017Sdim  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10012223017Sdim  QualType ArgType = ClassType;
10013249423Sdim  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10014223017Sdim  if (Const)
10015223017Sdim    ArgType = ArgType.withConst();
10016223017Sdim  ArgType = Context.getLValueReferenceType(ArgType);
10017223017Sdim
10018239462Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10019239462Sdim                                                     CXXCopyConstructor,
10020239462Sdim                                                     Const);
10021239462Sdim
10022210299Sed  DeclarationName Name
10023210299Sed    = Context.DeclarationNames.getCXXConstructorName(
10024210299Sed                                           Context.getCanonicalType(ClassType));
10025221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
10026221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
10027223017Sdim
10028223017Sdim  //   An implicitly-declared copy constructor is an inline public
10029234353Sdim  //   member of its class.
10030234353Sdim  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10031239462Sdim      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10032234353Sdim      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10033239462Sdim      Constexpr);
10034210299Sed  CopyConstructor->setAccess(AS_public);
10035223017Sdim  CopyConstructor->setDefaulted();
10036234353Sdim
10037239462Sdim  // Build an exception specification pointing back at this member.
10038263508Sdim  FunctionProtoType::ExtProtoInfo EPI =
10039263508Sdim      getImplicitMethodEPI(*this, CopyConstructor);
10040239462Sdim  CopyConstructor->setType(
10041249423Sdim      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10042239462Sdim
10043210299Sed  // Add the parameter to the constructor.
10044210299Sed  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10045221345Sdim                                               ClassLoc, ClassLoc,
10046210299Sed                                               /*IdentifierInfo=*/0,
10047210299Sed                                               ArgType, /*TInfo=*/0,
10048212904Sdim                                               SC_None, 0);
10049226633Sdim  CopyConstructor->setParams(FromParam);
10050223017Sdim
10051249423Sdim  CopyConstructor->setTrivial(
10052249423Sdim    ClassDecl->needsOverloadResolutionForCopyConstructor()
10053249423Sdim      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10054249423Sdim      : ClassDecl->hasTrivialCopyConstructor());
10055223017Sdim
10056234353Sdim  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10057249423Sdim    SetDeclDeleted(CopyConstructor, ClassLoc);
10058234353Sdim
10059249423Sdim  // Note that we have declared this constructor.
10060249423Sdim  ++ASTContext::NumImplicitCopyConstructorsDeclared;
10061249423Sdim
10062249423Sdim  if (Scope *S = getScopeForContext(ClassDecl))
10063249423Sdim    PushOnScopeChains(CopyConstructor, S, false);
10064249423Sdim  ClassDecl->addDecl(CopyConstructor);
10065249423Sdim
10066210299Sed  return CopyConstructor;
10067210299Sed}
10068210299Sed
10069194711Sedvoid Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10070223017Sdim                                   CXXConstructorDecl *CopyConstructor) {
10071223017Sdim  assert((CopyConstructor->isDefaulted() &&
10072223017Sdim          CopyConstructor->isCopyConstructor() &&
10073234353Sdim          !CopyConstructor->doesThisDeclarationHaveABody() &&
10074234353Sdim          !CopyConstructor->isDeleted()) &&
10075194711Sed         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10076198092Srdivacky
10077207619Srdivacky  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10078194711Sed  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10079203955Srdivacky
10080263508Sdim  // C++11 [class.copy]p7:
10081263508Sdim  //   The [definition of an implicitly declared copy constructor] is
10082263508Sdim  //   deprecated if the class has a user-declared copy assignment operator
10083263508Sdim  //   or a user-declared destructor.
10084263508Sdim  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10085263508Sdim    diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10086263508Sdim
10087243830Sdim  SynthesizedFunctionScope Scope(*this, CopyConstructor);
10088218893Sdim  DiagnosticErrorTrap Trap(Diags);
10089203955Srdivacky
10090249423Sdim  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10091208600Srdivacky      Trap.hasErrorOccurred()) {
10092207619Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
10093208600Srdivacky      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10094207619Srdivacky    CopyConstructor->setInvalidDecl();
10095208600Srdivacky  }  else {
10096234353Sdim    Sema::CompoundScopeRAII CompoundScope(*this);
10097263508Sdim    CopyConstructor->setBody(ActOnCompoundStmt(
10098263508Sdim        CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10099263508Sdim        /*isStmtExpr=*/ false).takeAs<Stmt>());
10100207619Srdivacky  }
10101263508Sdim
10102263508Sdim  CopyConstructor->markUsed(Context);
10103221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
10104221345Sdim    L->CompletedImplicitDefinition(CopyConstructor);
10105221345Sdim  }
10106194711Sed}
10107194711Sed
10108226633SdimSema::ImplicitExceptionSpecification
10109239462SdimSema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10110239462Sdim  CXXRecordDecl *ClassDecl = MD->getParent();
10111239462Sdim
10112226633Sdim  // C++ [except.spec]p14:
10113226633Sdim  //   An implicitly declared special member function (Clause 12) shall have an
10114226633Sdim  //   exception-specification. [...]
10115234982Sdim  ImplicitExceptionSpecification ExceptSpec(*this);
10116226633Sdim  if (ClassDecl->isInvalidDecl())
10117226633Sdim    return ExceptSpec;
10118226633Sdim
10119226633Sdim  // Direct base-class constructors.
10120226633Sdim  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10121226633Sdim                                       BEnd = ClassDecl->bases_end();
10122226633Sdim       B != BEnd; ++B) {
10123226633Sdim    if (B->isVirtual()) // Handled below.
10124226633Sdim      continue;
10125226633Sdim
10126226633Sdim    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10127226633Sdim      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10128239462Sdim      CXXConstructorDecl *Constructor =
10129239462Sdim          LookupMovingConstructor(BaseClassDecl, 0);
10130226633Sdim      // If this is a deleted function, add it anyway. This might be conformant
10131226633Sdim      // with the standard. This might not. I'm not sure. It might not matter.
10132226633Sdim      if (Constructor)
10133234982Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10134226633Sdim    }
10135226633Sdim  }
10136226633Sdim
10137226633Sdim  // Virtual base-class constructors.
10138226633Sdim  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10139226633Sdim                                       BEnd = ClassDecl->vbases_end();
10140226633Sdim       B != BEnd; ++B) {
10141226633Sdim    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10142226633Sdim      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10143239462Sdim      CXXConstructorDecl *Constructor =
10144239462Sdim          LookupMovingConstructor(BaseClassDecl, 0);
10145226633Sdim      // If this is a deleted function, add it anyway. This might be conformant
10146226633Sdim      // with the standard. This might not. I'm not sure. It might not matter.
10147226633Sdim      if (Constructor)
10148234982Sdim        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10149226633Sdim    }
10150226633Sdim  }
10151226633Sdim
10152226633Sdim  // Field constructors.
10153226633Sdim  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10154226633Sdim                               FEnd = ClassDecl->field_end();
10155226633Sdim       F != FEnd; ++F) {
10156239462Sdim    QualType FieldType = Context.getBaseElementType(F->getType());
10157239462Sdim    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10158239462Sdim      CXXConstructorDecl *Constructor =
10159239462Sdim          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10160226633Sdim      // If this is a deleted function, add it anyway. This might be conformant
10161226633Sdim      // with the standard. This might not. I'm not sure. It might not matter.
10162226633Sdim      // In particular, the problem is that this function never gets called. It
10163226633Sdim      // might just be ill-formed because this function attempts to refer to
10164226633Sdim      // a deleted function here.
10165226633Sdim      if (Constructor)
10166234982Sdim        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10167226633Sdim    }
10168226633Sdim  }
10169226633Sdim
10170226633Sdim  return ExceptSpec;
10171226633Sdim}
10172226633Sdim
10173226633SdimCXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10174226633Sdim                                                    CXXRecordDecl *ClassDecl) {
10175234353Sdim  assert(ClassDecl->needsImplicitMoveConstructor());
10176234353Sdim
10177249423Sdim  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10178249423Sdim  if (DSM.isAlreadyBeingDeclared())
10179249423Sdim    return 0;
10180249423Sdim
10181226633Sdim  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10182226633Sdim  QualType ArgType = Context.getRValueReferenceType(ClassType);
10183226633Sdim
10184239462Sdim  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10185239462Sdim                                                     CXXMoveConstructor,
10186239462Sdim                                                     false);
10187239462Sdim
10188226633Sdim  DeclarationName Name
10189226633Sdim    = Context.DeclarationNames.getCXXConstructorName(
10190226633Sdim                                           Context.getCanonicalType(ClassType));
10191226633Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
10192226633Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
10193226633Sdim
10194263508Sdim  // C++11 [class.copy]p11:
10195226633Sdim  //   An implicitly-declared copy/move constructor is an inline public
10196234353Sdim  //   member of its class.
10197234353Sdim  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10198239462Sdim      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10199234353Sdim      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10200239462Sdim      Constexpr);
10201226633Sdim  MoveConstructor->setAccess(AS_public);
10202226633Sdim  MoveConstructor->setDefaulted();
10203234353Sdim
10204239462Sdim  // Build an exception specification pointing back at this member.
10205263508Sdim  FunctionProtoType::ExtProtoInfo EPI =
10206263508Sdim      getImplicitMethodEPI(*this, MoveConstructor);
10207239462Sdim  MoveConstructor->setType(
10208249423Sdim      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10209239462Sdim
10210226633Sdim  // Add the parameter to the constructor.
10211226633Sdim  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10212226633Sdim                                               ClassLoc, ClassLoc,
10213226633Sdim                                               /*IdentifierInfo=*/0,
10214226633Sdim                                               ArgType, /*TInfo=*/0,
10215226633Sdim                                               SC_None, 0);
10216226633Sdim  MoveConstructor->setParams(FromParam);
10217226633Sdim
10218249423Sdim  MoveConstructor->setTrivial(
10219249423Sdim    ClassDecl->needsOverloadResolutionForMoveConstructor()
10220249423Sdim      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10221249423Sdim      : ClassDecl->hasTrivialMoveConstructor());
10222249423Sdim
10223226633Sdim  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10224263508Sdim    ClassDecl->setImplicitMoveConstructorIsDeleted();
10225263508Sdim    SetDeclDeleted(MoveConstructor, ClassLoc);
10226226633Sdim  }
10227226633Sdim
10228226633Sdim  // Note that we have declared this constructor.
10229226633Sdim  ++ASTContext::NumImplicitMoveConstructorsDeclared;
10230226633Sdim
10231226633Sdim  if (Scope *S = getScopeForContext(ClassDecl))
10232226633Sdim    PushOnScopeChains(MoveConstructor, S, false);
10233226633Sdim  ClassDecl->addDecl(MoveConstructor);
10234226633Sdim
10235226633Sdim  return MoveConstructor;
10236226633Sdim}
10237226633Sdim
10238226633Sdimvoid Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10239226633Sdim                                   CXXConstructorDecl *MoveConstructor) {
10240226633Sdim  assert((MoveConstructor->isDefaulted() &&
10241226633Sdim          MoveConstructor->isMoveConstructor() &&
10242234353Sdim          !MoveConstructor->doesThisDeclarationHaveABody() &&
10243234353Sdim          !MoveConstructor->isDeleted()) &&
10244226633Sdim         "DefineImplicitMoveConstructor - call it for implicit move ctor");
10245226633Sdim
10246226633Sdim  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10247226633Sdim  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10248226633Sdim
10249243830Sdim  SynthesizedFunctionScope Scope(*this, MoveConstructor);
10250226633Sdim  DiagnosticErrorTrap Trap(Diags);
10251226633Sdim
10252249423Sdim  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10253226633Sdim      Trap.hasErrorOccurred()) {
10254226633Sdim    Diag(CurrentLocation, diag::note_member_synthesized_at)
10255226633Sdim      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10256226633Sdim    MoveConstructor->setInvalidDecl();
10257226633Sdim  }  else {
10258234353Sdim    Sema::CompoundScopeRAII CompoundScope(*this);
10259263508Sdim    MoveConstructor->setBody(ActOnCompoundStmt(
10260263508Sdim        MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10261263508Sdim        /*isStmtExpr=*/ false).takeAs<Stmt>());
10262226633Sdim  }
10263226633Sdim
10264263508Sdim  MoveConstructor->markUsed(Context);
10265226633Sdim
10266226633Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
10267226633Sdim    L->CompletedImplicitDefinition(MoveConstructor);
10268226633Sdim  }
10269226633Sdim}
10270226633Sdim
10271234353Sdimbool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10272263508Sdim  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10273234353Sdim}
10274234353Sdim
10275234353Sdimvoid Sema::DefineImplicitLambdaToFunctionPointerConversion(
10276263508Sdim                            SourceLocation CurrentLocation,
10277263508Sdim                            CXXConversionDecl *Conv) {
10278234353Sdim  CXXRecordDecl *Lambda = Conv->getParent();
10279263508Sdim  CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10280263508Sdim  // If we are defining a specialization of a conversion to function-ptr
10281263508Sdim  // cache the deduced template arguments for this specialization
10282263508Sdim  // so that we can use them to retrieve the corresponding call-operator
10283263508Sdim  // and static-invoker.
10284263508Sdim  const TemplateArgumentList *DeducedTemplateArgs = 0;
10285263508Sdim
10286234353Sdim
10287263508Sdim  // Retrieve the corresponding call-operator specialization.
10288263508Sdim  if (Lambda->isGenericLambda()) {
10289263508Sdim    assert(Conv->isFunctionTemplateSpecialization());
10290263508Sdim    FunctionTemplateDecl *CallOpTemplate =
10291263508Sdim        CallOp->getDescribedFunctionTemplate();
10292263508Sdim    DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10293263508Sdim    void *InsertPos = 0;
10294263508Sdim    FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10295263508Sdim                                                DeducedTemplateArgs->data(),
10296263508Sdim                                                DeducedTemplateArgs->size(),
10297263508Sdim                                                InsertPos);
10298263508Sdim    assert(CallOpSpec &&
10299263508Sdim          "Conversion operator must have a corresponding call operator");
10300263508Sdim    CallOp = cast<CXXMethodDecl>(CallOpSpec);
10301263508Sdim  }
10302263508Sdim  // Mark the call operator referenced (and add to pending instantiations
10303263508Sdim  // if necessary).
10304263508Sdim  // For both the conversion and static-invoker template specializations
10305263508Sdim  // we construct their body's in this function, so no need to add them
10306263508Sdim  // to the PendingInstantiations.
10307263508Sdim  MarkFunctionReferenced(CurrentLocation, CallOp);
10308263508Sdim
10309243830Sdim  SynthesizedFunctionScope Scope(*this, Conv);
10310234353Sdim  DiagnosticErrorTrap Trap(Diags);
10311263508Sdim
10312263508Sdim  // Retreive the static invoker...
10313263508Sdim  CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10314263508Sdim  // ... and get the corresponding specialization for a generic lambda.
10315263508Sdim  if (Lambda->isGenericLambda()) {
10316263508Sdim    assert(DeducedTemplateArgs &&
10317263508Sdim      "Must have deduced template arguments from Conversion Operator");
10318263508Sdim    FunctionTemplateDecl *InvokeTemplate =
10319263508Sdim                          Invoker->getDescribedFunctionTemplate();
10320263508Sdim    void *InsertPos = 0;
10321263508Sdim    FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10322263508Sdim                                                DeducedTemplateArgs->data(),
10323263508Sdim                                                DeducedTemplateArgs->size(),
10324263508Sdim                                                InsertPos);
10325263508Sdim    assert(InvokeSpec &&
10326263508Sdim      "Must have a corresponding static invoker specialization");
10327263508Sdim    Invoker = cast<CXXMethodDecl>(InvokeSpec);
10328263508Sdim  }
10329263508Sdim  // Construct the body of the conversion function { return __invoke; }.
10330263508Sdim  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10331263508Sdim                                        VK_LValue, Conv->getLocation()).take();
10332263508Sdim   assert(FunctionRef && "Can't refer to __invoke function?");
10333263508Sdim   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10334263508Sdim   Conv->setBody(new (Context) CompoundStmt(Context, Return,
10335263508Sdim                                            Conv->getLocation(),
10336263508Sdim                                            Conv->getLocation()));
10337263508Sdim
10338263508Sdim  Conv->markUsed(Context);
10339263508Sdim  Conv->setReferenced();
10340234353Sdim
10341234353Sdim  // Fill in the __invoke function with a dummy implementation. IR generation
10342234353Sdim  // will fill in the actual details.
10343263508Sdim  Invoker->markUsed(Context);
10344263508Sdim  Invoker->setReferenced();
10345263508Sdim  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10346263508Sdim
10347234353Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
10348234353Sdim    L->CompletedImplicitDefinition(Conv);
10349263508Sdim    L->CompletedImplicitDefinition(Invoker);
10350263508Sdim   }
10351234353Sdim}
10352234353Sdim
10353263508Sdim
10354263508Sdim
10355234353Sdimvoid Sema::DefineImplicitLambdaToBlockPointerConversion(
10356234353Sdim       SourceLocation CurrentLocation,
10357234353Sdim       CXXConversionDecl *Conv)
10358234353Sdim{
10359263508Sdim  assert(!Conv->getParent()->isGenericLambda());
10360263508Sdim
10361263508Sdim  Conv->markUsed(Context);
10362234353Sdim
10363243830Sdim  SynthesizedFunctionScope Scope(*this, Conv);
10364234353Sdim  DiagnosticErrorTrap Trap(Diags);
10365234353Sdim
10366234353Sdim  // Copy-initialize the lambda object as needed to capture it.
10367234353Sdim  Expr *This = ActOnCXXThis(CurrentLocation).take();
10368234353Sdim  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10369234353Sdim
10370234353Sdim  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10371234353Sdim                                                        Conv->getLocation(),
10372234353Sdim                                                        Conv, DerefThis);
10373234353Sdim
10374234353Sdim  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10375234353Sdim  // behavior.  Note that only the general conversion function does this
10376234353Sdim  // (since it's unusable otherwise); in the case where we inline the
10377234353Sdim  // block literal, it has block literal lifetime semantics.
10378234353Sdim  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10379234353Sdim    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10380234353Sdim                                          CK_CopyAndAutoreleaseBlockObject,
10381234353Sdim                                          BuildBlock.get(), 0, VK_RValue);
10382234353Sdim
10383234353Sdim  if (BuildBlock.isInvalid()) {
10384234353Sdim    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10385234353Sdim    Conv->setInvalidDecl();
10386234353Sdim    return;
10387234353Sdim  }
10388234353Sdim
10389234353Sdim  // Create the return statement that returns the block from the conversion
10390234353Sdim  // function.
10391234353Sdim  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10392234353Sdim  if (Return.isInvalid()) {
10393234353Sdim    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10394234353Sdim    Conv->setInvalidDecl();
10395234353Sdim    return;
10396234353Sdim  }
10397234353Sdim
10398234353Sdim  // Set the body of the conversion function.
10399234353Sdim  Stmt *ReturnS = Return.take();
10400249423Sdim  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10401234353Sdim                                           Conv->getLocation(),
10402234353Sdim                                           Conv->getLocation()));
10403234353Sdim
10404234353Sdim  // We're done; notify the mutation listener, if any.
10405234353Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
10406234353Sdim    L->CompletedImplicitDefinition(Conv);
10407234353Sdim  }
10408234353Sdim}
10409234353Sdim
10410234353Sdim/// \brief Determine whether the given list arguments contains exactly one
10411234353Sdim/// "real" (non-default) argument.
10412234353Sdimstatic bool hasOneRealArgument(MultiExprArg Args) {
10413234353Sdim  switch (Args.size()) {
10414234353Sdim  case 0:
10415234353Sdim    return false;
10416234353Sdim
10417234353Sdim  default:
10418243830Sdim    if (!Args[1]->isDefaultArgument())
10419234353Sdim      return false;
10420234353Sdim
10421234353Sdim    // fall through
10422234353Sdim  case 1:
10423243830Sdim    return !Args[0]->isDefaultArgument();
10424234353Sdim  }
10425234353Sdim
10426234353Sdim  return false;
10427234353Sdim}
10428234353Sdim
10429212904SdimExprResult
10430198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10431198092Srdivacky                            CXXConstructorDecl *Constructor,
10432201361Srdivacky                            MultiExprArg ExprArgs,
10433226633Sdim                            bool HadMultipleCandidates,
10434249423Sdim                            bool IsListInitialization,
10435203955Srdivacky                            bool RequiresZeroInit,
10436218893Sdim                            unsigned ConstructKind,
10437218893Sdim                            SourceRange ParenRange) {
10438198092Srdivacky  bool Elidable = false;
10439198092Srdivacky
10440206125Srdivacky  // C++0x [class.copy]p34:
10441206125Srdivacky  //   When certain criteria are met, an implementation is allowed to
10442206125Srdivacky  //   omit the copy/move construction of a class object, even if the
10443206125Srdivacky  //   copy/move constructor and/or destructor for the object have
10444206125Srdivacky  //   side effects. [...]
10445206125Srdivacky  //     - when a temporary class object that has not been bound to a
10446206125Srdivacky  //       reference (12.2) would be copied/moved to a class object
10447206125Srdivacky  //       with the same cv-unqualified type, the copy/move operation
10448206125Srdivacky  //       can be omitted by constructing the temporary object
10449206125Srdivacky  //       directly into the target of the omitted copy/move
10450218893Sdim  if (ConstructKind == CXXConstructExpr::CK_Complete &&
10451234353Sdim      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10452243830Sdim    Expr *SubExpr = ExprArgs[0];
10453218893Sdim    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10454198092Srdivacky  }
10455198092Srdivacky
10456198092Srdivacky  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10457243830Sdim                               Elidable, ExprArgs, HadMultipleCandidates,
10458249423Sdim                               IsListInitialization, RequiresZeroInit,
10459249423Sdim                               ConstructKind, ParenRange);
10460198092Srdivacky}
10461198092Srdivacky
10462198092Srdivacky/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10463198092Srdivacky/// including handling of its default argument expressions.
10464212904SdimExprResult
10465198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10466198092Srdivacky                            CXXConstructorDecl *Constructor, bool Elidable,
10467201361Srdivacky                            MultiExprArg ExprArgs,
10468226633Sdim                            bool HadMultipleCandidates,
10469249423Sdim                            bool IsListInitialization,
10470203955Srdivacky                            bool RequiresZeroInit,
10471218893Sdim                            unsigned ConstructKind,
10472218893Sdim                            SourceRange ParenRange) {
10473234353Sdim  MarkFunctionReferenced(ConstructLoc, Constructor);
10474201361Srdivacky  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10475243830Sdim                                        Constructor, Elidable, ExprArgs,
10476249423Sdim                                        HadMultipleCandidates,
10477249423Sdim                                        IsListInitialization, RequiresZeroInit,
10478218893Sdim              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10479218893Sdim                                        ParenRange));
10480198092Srdivacky}
10481198092Srdivacky
10482203955Srdivackyvoid Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10483221345Sdim  if (VD->isInvalidDecl()) return;
10484221345Sdim
10485203955Srdivacky  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10486221345Sdim  if (ClassDecl->isInvalidDecl()) return;
10487234353Sdim  if (ClassDecl->hasIrrelevantDestructor()) return;
10488221345Sdim  if (ClassDecl->isDependentContext()) return;
10489212904Sdim
10490221345Sdim  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10491234353Sdim  MarkFunctionReferenced(VD->getLocation(), Destructor);
10492221345Sdim  CheckDestructorAccess(VD->getLocation(), Destructor,
10493221345Sdim                        PDiag(diag::err_access_dtor_var)
10494221345Sdim                        << VD->getDeclName()
10495221345Sdim                        << VD->getType());
10496234353Sdim  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10497221345Sdim
10498221345Sdim  if (!VD->hasGlobalStorage()) return;
10499221345Sdim
10500221345Sdim  // Emit warning for non-trivial dtor in global scope (a real global,
10501221345Sdim  // class-static, function-static).
10502221345Sdim  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10503221345Sdim
10504221345Sdim  // TODO: this should be re-enabled for static locals by !CXAAtExit
10505221345Sdim  if (!VD->isStaticLocal())
10506221345Sdim    Diag(VD->getLocation(), diag::warn_global_destructor);
10507195099Sed}
10508195099Sed
10509198092Srdivacky/// \brief Given a constructor and the set of arguments provided for the
10510198092Srdivacky/// constructor, convert the arguments and add any required default arguments
10511198092Srdivacky/// to form a proper call to this constructor.
10512198092Srdivacky///
10513198092Srdivacky/// \returns true if an error occurred, false otherwise.
10514198092Srdivackybool
10515198092SrdivackySema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10516198092Srdivacky                              MultiExprArg ArgsPtr,
10517239462Sdim                              SourceLocation Loc,
10518243830Sdim                              SmallVectorImpl<Expr*> &ConvertedArgs,
10519249423Sdim                              bool AllowExplicit,
10520249423Sdim                              bool IsListInitialization) {
10521198092Srdivacky  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10522198092Srdivacky  unsigned NumArgs = ArgsPtr.size();
10523243830Sdim  Expr **Args = ArgsPtr.data();
10524198092Srdivacky
10525198092Srdivacky  const FunctionProtoType *Proto
10526198092Srdivacky    = Constructor->getType()->getAs<FunctionProtoType>();
10527198092Srdivacky  assert(Proto && "Constructor without a prototype?");
10528198092Srdivacky  unsigned NumArgsInProto = Proto->getNumArgs();
10529198092Srdivacky
10530198092Srdivacky  // If too few arguments are available, we'll fill in the rest with defaults.
10531199990Srdivacky  if (NumArgs < NumArgsInProto)
10532198092Srdivacky    ConvertedArgs.reserve(NumArgsInProto);
10533199990Srdivacky  else
10534198092Srdivacky    ConvertedArgs.reserve(NumArgs);
10535199990Srdivacky
10536199990Srdivacky  VariadicCallType CallType =
10537199990Srdivacky    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10538226633Sdim  SmallVector<Expr *, 8> AllArgs;
10539199990Srdivacky  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10540263508Sdim                                        Proto, 0,
10541263508Sdim                                        llvm::makeArrayRef(Args, NumArgs),
10542263508Sdim                                        AllArgs,
10543249423Sdim                                        CallType, AllowExplicit,
10544249423Sdim                                        IsListInitialization);
10545234353Sdim  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10546234353Sdim
10547263508Sdim  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10548234353Sdim
10549249423Sdim  CheckConstructorCall(Constructor,
10550249423Sdim                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10551249423Sdim                                                        AllArgs.size()),
10552239462Sdim                       Proto, Loc);
10553234353Sdim
10554199990Srdivacky  return Invalid;
10555198092Srdivacky}
10556198092Srdivacky
10557200583Srdivackystatic inline bool
10558200583SrdivackyCheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10559200583Srdivacky                                       const FunctionDecl *FnDecl) {
10560212904Sdim  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10561200583Srdivacky  if (isa<NamespaceDecl>(DC)) {
10562200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10563200583Srdivacky                        diag::err_operator_new_delete_declared_in_namespace)
10564200583Srdivacky      << FnDecl->getDeclName();
10565200583Srdivacky  }
10566200583Srdivacky
10567200583Srdivacky  if (isa<TranslationUnitDecl>(DC) &&
10568212904Sdim      FnDecl->getStorageClass() == SC_Static) {
10569200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10570200583Srdivacky                        diag::err_operator_new_delete_declared_static)
10571200583Srdivacky      << FnDecl->getDeclName();
10572200583Srdivacky  }
10573200583Srdivacky
10574200583Srdivacky  return false;
10575200583Srdivacky}
10576200583Srdivacky
10577200583Srdivackystatic inline bool
10578200583SrdivackyCheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10579200583Srdivacky                            CanQualType ExpectedResultType,
10580200583Srdivacky                            CanQualType ExpectedFirstParamType,
10581200583Srdivacky                            unsigned DependentParamTypeDiag,
10582200583Srdivacky                            unsigned InvalidParamTypeDiag) {
10583200583Srdivacky  QualType ResultType =
10584200583Srdivacky    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10585200583Srdivacky
10586200583Srdivacky  // Check that the result type is not dependent.
10587200583Srdivacky  if (ResultType->isDependentType())
10588200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10589200583Srdivacky                        diag::err_operator_new_delete_dependent_result_type)
10590200583Srdivacky    << FnDecl->getDeclName() << ExpectedResultType;
10591200583Srdivacky
10592200583Srdivacky  // Check that the result type is what we expect.
10593200583Srdivacky  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10594200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10595200583Srdivacky                        diag::err_operator_new_delete_invalid_result_type)
10596200583Srdivacky    << FnDecl->getDeclName() << ExpectedResultType;
10597200583Srdivacky
10598200583Srdivacky  // A function template must have at least 2 parameters.
10599200583Srdivacky  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10600200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10601200583Srdivacky                      diag::err_operator_new_delete_template_too_few_parameters)
10602200583Srdivacky        << FnDecl->getDeclName();
10603200583Srdivacky
10604200583Srdivacky  // The function decl must have at least 1 parameter.
10605200583Srdivacky  if (FnDecl->getNumParams() == 0)
10606200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10607200583Srdivacky                        diag::err_operator_new_delete_too_few_parameters)
10608200583Srdivacky      << FnDecl->getDeclName();
10609200583Srdivacky
10610239462Sdim  // Check the first parameter type is not dependent.
10611200583Srdivacky  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10612200583Srdivacky  if (FirstParamType->isDependentType())
10613200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10614200583Srdivacky      << FnDecl->getDeclName() << ExpectedFirstParamType;
10615200583Srdivacky
10616200583Srdivacky  // Check that the first parameter type is what we expect.
10617201361Srdivacky  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10618200583Srdivacky      ExpectedFirstParamType)
10619200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10620200583Srdivacky    << FnDecl->getDeclName() << ExpectedFirstParamType;
10621200583Srdivacky
10622200583Srdivacky  return false;
10623200583Srdivacky}
10624200583Srdivacky
10625200583Srdivackystatic bool
10626200583SrdivackyCheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10627200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
10628200583Srdivacky  //   A program is ill-formed if an allocation function is declared in a
10629200583Srdivacky  //   namespace scope other than global scope or declared static in global
10630200583Srdivacky  //   scope.
10631200583Srdivacky  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10632200583Srdivacky    return true;
10633200583Srdivacky
10634200583Srdivacky  CanQualType SizeTy =
10635200583Srdivacky    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10636200583Srdivacky
10637200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
10638200583Srdivacky  //  The return type shall be void*. The first parameter shall have type
10639200583Srdivacky  //  std::size_t.
10640200583Srdivacky  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10641200583Srdivacky                                  SizeTy,
10642200583Srdivacky                                  diag::err_operator_new_dependent_param_type,
10643200583Srdivacky                                  diag::err_operator_new_param_type))
10644200583Srdivacky    return true;
10645200583Srdivacky
10646200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
10647200583Srdivacky  //  The first parameter shall not have an associated default argument.
10648200583Srdivacky  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10649200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
10650200583Srdivacky                        diag::err_operator_new_default_arg)
10651200583Srdivacky      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10652200583Srdivacky
10653200583Srdivacky  return false;
10654200583Srdivacky}
10655200583Srdivacky
10656200583Srdivackystatic bool
10657243830SdimCheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10658200583Srdivacky  // C++ [basic.stc.dynamic.deallocation]p1:
10659200583Srdivacky  //   A program is ill-formed if deallocation functions are declared in a
10660200583Srdivacky  //   namespace scope other than global scope or declared static in global
10661200583Srdivacky  //   scope.
10662200583Srdivacky  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10663200583Srdivacky    return true;
10664200583Srdivacky
10665200583Srdivacky  // C++ [basic.stc.dynamic.deallocation]p2:
10666200583Srdivacky  //   Each deallocation function shall return void and its first parameter
10667200583Srdivacky  //   shall be void*.
10668200583Srdivacky  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10669200583Srdivacky                                  SemaRef.Context.VoidPtrTy,
10670200583Srdivacky                                 diag::err_operator_delete_dependent_param_type,
10671200583Srdivacky                                 diag::err_operator_delete_param_type))
10672200583Srdivacky    return true;
10673200583Srdivacky
10674200583Srdivacky  return false;
10675200583Srdivacky}
10676200583Srdivacky
10677193326Sed/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10678193326Sed/// of this overloaded operator is well-formed. If so, returns false;
10679193326Sed/// otherwise, emits appropriate diagnostics and returns true.
10680193326Sedbool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10681193326Sed  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10682193326Sed         "Expected an overloaded operator declaration");
10683193326Sed
10684193326Sed  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10685193326Sed
10686198092Srdivacky  // C++ [over.oper]p5:
10687193326Sed  //   The allocation and deallocation functions, operator new,
10688193326Sed  //   operator new[], operator delete and operator delete[], are
10689193326Sed  //   described completely in 3.7.3. The attributes and restrictions
10690193326Sed  //   found in the rest of this subclause do not apply to them unless
10691193326Sed  //   explicitly stated in 3.7.3.
10692199482Srdivacky  if (Op == OO_Delete || Op == OO_Array_Delete)
10693200583Srdivacky    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10694199482Srdivacky
10695200583Srdivacky  if (Op == OO_New || Op == OO_Array_New)
10696200583Srdivacky    return CheckOperatorNewDeclaration(*this, FnDecl);
10697193326Sed
10698193326Sed  // C++ [over.oper]p6:
10699193326Sed  //   An operator function shall either be a non-static member
10700193326Sed  //   function or be a non-member function and have at least one
10701193326Sed  //   parameter whose type is a class, a reference to a class, an
10702193326Sed  //   enumeration, or a reference to an enumeration.
10703193326Sed  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10704193326Sed    if (MethodDecl->isStatic())
10705193326Sed      return Diag(FnDecl->getLocation(),
10706193326Sed                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10707193326Sed  } else {
10708193326Sed    bool ClassOrEnumParam = false;
10709193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10710193326Sed                                   ParamEnd = FnDecl->param_end();
10711193326Sed         Param != ParamEnd; ++Param) {
10712193326Sed      QualType ParamType = (*Param)->getType().getNonReferenceType();
10713195099Sed      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10714195099Sed          ParamType->isEnumeralType()) {
10715193326Sed        ClassOrEnumParam = true;
10716193326Sed        break;
10717193326Sed      }
10718193326Sed    }
10719193326Sed
10720193326Sed    if (!ClassOrEnumParam)
10721193326Sed      return Diag(FnDecl->getLocation(),
10722193326Sed                  diag::err_operator_overload_needs_class_or_enum)
10723193326Sed        << FnDecl->getDeclName();
10724193326Sed  }
10725193326Sed
10726193326Sed  // C++ [over.oper]p8:
10727193326Sed  //   An operator function cannot have default arguments (8.3.6),
10728193326Sed  //   except where explicitly stated below.
10729193326Sed  //
10730198092Srdivacky  // Only the function-call operator allows default arguments
10731193326Sed  // (C++ [over.call]p1).
10732193326Sed  if (Op != OO_Call) {
10733193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10734193326Sed         Param != FnDecl->param_end(); ++Param) {
10735200583Srdivacky      if ((*Param)->hasDefaultArg())
10736198092Srdivacky        return Diag((*Param)->getLocation(),
10737193326Sed                    diag::err_operator_overload_default_arg)
10738200583Srdivacky          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10739193326Sed    }
10740193326Sed  }
10741193326Sed
10742193326Sed  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10743193326Sed    { false, false, false }
10744193326Sed#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10745193326Sed    , { Unary, Binary, MemberOnly }
10746193326Sed#include "clang/Basic/OperatorKinds.def"
10747193326Sed  };
10748193326Sed
10749193326Sed  bool CanBeUnaryOperator = OperatorUses[Op][0];
10750193326Sed  bool CanBeBinaryOperator = OperatorUses[Op][1];
10751193326Sed  bool MustBeMemberOperator = OperatorUses[Op][2];
10752193326Sed
10753193326Sed  // C++ [over.oper]p8:
10754193326Sed  //   [...] Operator functions cannot have more or fewer parameters
10755193326Sed  //   than the number required for the corresponding operator, as
10756193326Sed  //   described in the rest of this subclause.
10757198092Srdivacky  unsigned NumParams = FnDecl->getNumParams()
10758193326Sed                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10759193326Sed  if (Op != OO_Call &&
10760193326Sed      ((NumParams == 1 && !CanBeUnaryOperator) ||
10761193326Sed       (NumParams == 2 && !CanBeBinaryOperator) ||
10762193326Sed       (NumParams < 1) || (NumParams > 2))) {
10763193326Sed    // We have the wrong number of parameters.
10764193326Sed    unsigned ErrorKind;
10765193326Sed    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10766193326Sed      ErrorKind = 2;  // 2 -> unary or binary.
10767193326Sed    } else if (CanBeUnaryOperator) {
10768193326Sed      ErrorKind = 0;  // 0 -> unary
10769193326Sed    } else {
10770193326Sed      assert(CanBeBinaryOperator &&
10771193326Sed             "All non-call overloaded operators are unary or binary!");
10772193326Sed      ErrorKind = 1;  // 1 -> binary
10773193326Sed    }
10774193326Sed
10775193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10776193326Sed      << FnDecl->getDeclName() << NumParams << ErrorKind;
10777193326Sed  }
10778193326Sed
10779193326Sed  // Overloaded operators other than operator() cannot be variadic.
10780193326Sed  if (Op != OO_Call &&
10781198092Srdivacky      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10782193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10783193326Sed      << FnDecl->getDeclName();
10784193326Sed  }
10785193326Sed
10786193326Sed  // Some operators must be non-static member functions.
10787193326Sed  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10788193326Sed    return Diag(FnDecl->getLocation(),
10789193326Sed                diag::err_operator_overload_must_be_member)
10790193326Sed      << FnDecl->getDeclName();
10791193326Sed  }
10792193326Sed
10793193326Sed  // C++ [over.inc]p1:
10794193326Sed  //   The user-defined function called operator++ implements the
10795193326Sed  //   prefix and postfix ++ operator. If this function is a member
10796193326Sed  //   function with no parameters, or a non-member function with one
10797193326Sed  //   parameter of class or enumeration type, it defines the prefix
10798193326Sed  //   increment operator ++ for objects of that type. If the function
10799193326Sed  //   is a member function with one parameter (which shall be of type
10800193326Sed  //   int) or a non-member function with two parameters (the second
10801193326Sed  //   of which shall be of type int), it defines the postfix
10802193326Sed  //   increment operator ++ for objects of that type.
10803193326Sed  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10804193326Sed    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10805193326Sed    bool ParamIsInt = false;
10806198092Srdivacky    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10807193326Sed      ParamIsInt = BT->getKind() == BuiltinType::Int;
10808193326Sed
10809193326Sed    if (!ParamIsInt)
10810193326Sed      return Diag(LastParam->getLocation(),
10811198092Srdivacky                  diag::err_operator_overload_post_incdec_must_be_int)
10812193326Sed        << LastParam->getType() << (Op == OO_MinusMinus);
10813193326Sed  }
10814193326Sed
10815193326Sed  return false;
10816193326Sed}
10817193326Sed
10818202379Srdivacky/// CheckLiteralOperatorDeclaration - Check whether the declaration
10819202379Srdivacky/// of this literal operator function is well-formed. If so, returns
10820202379Srdivacky/// false; otherwise, emits appropriate diagnostics and returns true.
10821202379Srdivackybool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10822234353Sdim  if (isa<CXXMethodDecl>(FnDecl)) {
10823202379Srdivacky    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10824202379Srdivacky      << FnDecl->getDeclName();
10825202379Srdivacky    return true;
10826202379Srdivacky  }
10827202379Srdivacky
10828234353Sdim  if (FnDecl->isExternC()) {
10829234353Sdim    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10830234353Sdim    return true;
10831234353Sdim  }
10832234353Sdim
10833202379Srdivacky  bool Valid = false;
10834202379Srdivacky
10835234353Sdim  // This might be the definition of a literal operator template.
10836234353Sdim  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10837234353Sdim  // This might be a specialization of a literal operator template.
10838234353Sdim  if (!TpDecl)
10839234353Sdim    TpDecl = FnDecl->getPrimaryTemplate();
10840234353Sdim
10841263508Sdim  // template <char...> type operator "" name() and
10842263508Sdim  // template <class T, T...> type operator "" name() are the only valid
10843263508Sdim  // template signatures, and the only valid signatures with no parameters.
10844234353Sdim  if (TpDecl) {
10845234353Sdim    if (FnDecl->param_size() == 0) {
10846263508Sdim      // Must have one or two template parameters
10847207619Srdivacky      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10848207619Srdivacky      if (Params->size() == 1) {
10849207619Srdivacky        NonTypeTemplateParmDecl *PmDecl =
10850239462Sdim          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10851202379Srdivacky
10852207619Srdivacky        // The template parameter must be a char parameter pack.
10853207619Srdivacky        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10854207619Srdivacky            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10855207619Srdivacky          Valid = true;
10856263508Sdim      } else if (Params->size() == 2) {
10857263508Sdim        TemplateTypeParmDecl *PmType =
10858263508Sdim          dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10859263508Sdim        NonTypeTemplateParmDecl *PmArgs =
10860263508Sdim          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10861263508Sdim
10862263508Sdim        // The second template parameter must be a parameter pack with the
10863263508Sdim        // first template parameter as its type.
10864263508Sdim        if (PmType && PmArgs &&
10865263508Sdim            !PmType->isTemplateParameterPack() &&
10866263508Sdim            PmArgs->isTemplateParameterPack()) {
10867263508Sdim          const TemplateTypeParmType *TArgs =
10868263508Sdim            PmArgs->getType()->getAs<TemplateTypeParmType>();
10869263508Sdim          if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10870263508Sdim              TArgs->getIndex() == PmType->getIndex()) {
10871263508Sdim            Valid = true;
10872263508Sdim            if (ActiveTemplateInstantiations.empty())
10873263508Sdim              Diag(FnDecl->getLocation(),
10874263508Sdim                   diag::ext_string_literal_operator_template);
10875263508Sdim          }
10876263508Sdim        }
10877207619Srdivacky      }
10878207619Srdivacky    }
10879234353Sdim  } else if (FnDecl->param_size()) {
10880202379Srdivacky    // Check the first parameter
10881207619Srdivacky    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10882207619Srdivacky
10883234353Sdim    QualType T = (*Param)->getType().getUnqualifiedType();
10884202379Srdivacky
10885207619Srdivacky    // unsigned long long int, long double, and any character type are allowed
10886207619Srdivacky    // as the only parameters.
10887202379Srdivacky    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10888202379Srdivacky        Context.hasSameType(T, Context.LongDoubleTy) ||
10889202379Srdivacky        Context.hasSameType(T, Context.CharTy) ||
10890263508Sdim        Context.hasSameType(T, Context.WideCharTy) ||
10891202379Srdivacky        Context.hasSameType(T, Context.Char16Ty) ||
10892202379Srdivacky        Context.hasSameType(T, Context.Char32Ty)) {
10893202379Srdivacky      if (++Param == FnDecl->param_end())
10894202379Srdivacky        Valid = true;
10895202379Srdivacky      goto FinishedParams;
10896202379Srdivacky    }
10897202379Srdivacky
10898207619Srdivacky    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10899202379Srdivacky    const PointerType *PT = T->getAs<PointerType>();
10900202379Srdivacky    if (!PT)
10901202379Srdivacky      goto FinishedParams;
10902202379Srdivacky    T = PT->getPointeeType();
10903234353Sdim    if (!T.isConstQualified() || T.isVolatileQualified())
10904202379Srdivacky      goto FinishedParams;
10905202379Srdivacky    T = T.getUnqualifiedType();
10906202379Srdivacky
10907202379Srdivacky    // Move on to the second parameter;
10908202379Srdivacky    ++Param;
10909202379Srdivacky
10910202379Srdivacky    // If there is no second parameter, the first must be a const char *
10911202379Srdivacky    if (Param == FnDecl->param_end()) {
10912202379Srdivacky      if (Context.hasSameType(T, Context.CharTy))
10913202379Srdivacky        Valid = true;
10914202379Srdivacky      goto FinishedParams;
10915202379Srdivacky    }
10916202379Srdivacky
10917202379Srdivacky    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10918202379Srdivacky    // are allowed as the first parameter to a two-parameter function
10919202379Srdivacky    if (!(Context.hasSameType(T, Context.CharTy) ||
10920263508Sdim          Context.hasSameType(T, Context.WideCharTy) ||
10921202379Srdivacky          Context.hasSameType(T, Context.Char16Ty) ||
10922202379Srdivacky          Context.hasSameType(T, Context.Char32Ty)))
10923202379Srdivacky      goto FinishedParams;
10924202379Srdivacky
10925202379Srdivacky    // The second and final parameter must be an std::size_t
10926202379Srdivacky    T = (*Param)->getType().getUnqualifiedType();
10927202379Srdivacky    if (Context.hasSameType(T, Context.getSizeType()) &&
10928202379Srdivacky        ++Param == FnDecl->param_end())
10929202379Srdivacky      Valid = true;
10930202379Srdivacky  }
10931202379Srdivacky
10932202379Srdivacky  // FIXME: This diagnostic is absolutely terrible.
10933202379SrdivackyFinishedParams:
10934202379Srdivacky  if (!Valid) {
10935202379Srdivacky    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10936202379Srdivacky      << FnDecl->getDeclName();
10937202379Srdivacky    return true;
10938202379Srdivacky  }
10939202379Srdivacky
10940234353Sdim  // A parameter-declaration-clause containing a default argument is not
10941234353Sdim  // equivalent to any of the permitted forms.
10942234353Sdim  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10943234353Sdim                                    ParamEnd = FnDecl->param_end();
10944234353Sdim       Param != ParamEnd; ++Param) {
10945234353Sdim    if ((*Param)->hasDefaultArg()) {
10946234353Sdim      Diag((*Param)->getDefaultArgRange().getBegin(),
10947234353Sdim           diag::err_literal_operator_default_argument)
10948234353Sdim        << (*Param)->getDefaultArgRange();
10949234353Sdim      break;
10950234353Sdim    }
10951234353Sdim  }
10952234353Sdim
10953234353Sdim  StringRef LiteralName
10954226633Sdim    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10955226633Sdim  if (LiteralName[0] != '_') {
10956234353Sdim    // C++11 [usrlit.suffix]p1:
10957234353Sdim    //   Literal suffix identifiers that do not start with an underscore
10958234353Sdim    //   are reserved for future standardization.
10959263508Sdim    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10960263508Sdim      << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10961226633Sdim  }
10962234353Sdim
10963202379Srdivacky  return false;
10964202379Srdivacky}
10965202379Srdivacky
10966193326Sed/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10967193326Sed/// linkage specification, including the language and (if present)
10968193326Sed/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10969193326Sed/// the location of the language string literal, which is provided
10970193326Sed/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10971193326Sed/// the '{' brace. Otherwise, this linkage specification does not
10972193326Sed/// have any braces.
10973218893SdimDecl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10974218893Sdim                                           SourceLocation LangLoc,
10975226633Sdim                                           StringRef Lang,
10976218893Sdim                                           SourceLocation LBraceLoc) {
10977193326Sed  LinkageSpecDecl::LanguageIDs Language;
10978207619Srdivacky  if (Lang == "\"C\"")
10979193326Sed    Language = LinkageSpecDecl::lang_c;
10980207619Srdivacky  else if (Lang == "\"C++\"")
10981193326Sed    Language = LinkageSpecDecl::lang_cxx;
10982193326Sed  else {
10983193326Sed    Diag(LangLoc, diag::err_bad_language);
10984212904Sdim    return 0;
10985193326Sed  }
10986198092Srdivacky
10987193326Sed  // FIXME: Add all the various semantics of linkage specifications
10988198092Srdivacky
10989193326Sed  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10990251662Sdim                                               ExternLoc, LangLoc, Language,
10991251662Sdim                                               LBraceLoc.isValid());
10992195341Sed  CurContext->addDecl(D);
10993193326Sed  PushDeclContext(S, D);
10994212904Sdim  return D;
10995193326Sed}
10996193326Sed
10997212904Sdim/// ActOnFinishLinkageSpecification - Complete the definition of
10998193326Sed/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10999193326Sed/// valid, it's the position of the closing '}' brace in a linkage
11000193326Sed/// specification that uses braces.
11001212904SdimDecl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11002221345Sdim                                            Decl *LinkageSpec,
11003221345Sdim                                            SourceLocation RBraceLoc) {
11004221345Sdim  if (LinkageSpec) {
11005221345Sdim    if (RBraceLoc.isValid()) {
11006221345Sdim      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11007221345Sdim      LSDecl->setRBraceLoc(RBraceLoc);
11008221345Sdim    }
11009193326Sed    PopDeclContext();
11010221345Sdim  }
11011193326Sed  return LinkageSpec;
11012193326Sed}
11013193326Sed
11014249423SdimDecl *Sema::ActOnEmptyDeclaration(Scope *S,
11015249423Sdim                                  AttributeList *AttrList,
11016249423Sdim                                  SourceLocation SemiLoc) {
11017249423Sdim  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11018249423Sdim  // Attribute declarations appertain to empty declaration so we handle
11019249423Sdim  // them here.
11020249423Sdim  if (AttrList)
11021249423Sdim    ProcessDeclAttributeList(S, ED, AttrList);
11022249423Sdim
11023249423Sdim  CurContext->addDecl(ED);
11024249423Sdim  return ED;
11025249423Sdim}
11026249423Sdim
11027193326Sed/// \brief Perform semantic analysis for the variable declaration that
11028193326Sed/// occurs within a C++ catch clause, returning the newly-created
11029193326Sed/// variable.
11030221345SdimVarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11031200583Srdivacky                                         TypeSourceInfo *TInfo,
11032221345Sdim                                         SourceLocation StartLoc,
11033221345Sdim                                         SourceLocation Loc,
11034221345Sdim                                         IdentifierInfo *Name) {
11035193326Sed  bool Invalid = false;
11036218893Sdim  QualType ExDeclType = TInfo->getType();
11037218893Sdim
11038193326Sed  // Arrays and functions decay.
11039193326Sed  if (ExDeclType->isArrayType())
11040193326Sed    ExDeclType = Context.getArrayDecayedType(ExDeclType);
11041193326Sed  else if (ExDeclType->isFunctionType())
11042193326Sed    ExDeclType = Context.getPointerType(ExDeclType);
11043193326Sed
11044193326Sed  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11045193326Sed  // The exception-declaration shall not denote a pointer or reference to an
11046193326Sed  // incomplete type, other than [cv] void*.
11047193326Sed  // N2844 forbids rvalue references.
11048198092Srdivacky  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11049218893Sdim    Diag(Loc, diag::err_catch_rvalue_ref);
11050193326Sed    Invalid = true;
11051193326Sed  }
11052193326Sed
11053193326Sed  QualType BaseType = ExDeclType;
11054193326Sed  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11055193326Sed  unsigned DK = diag::err_catch_incomplete;
11056198092Srdivacky  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11057193326Sed    BaseType = Ptr->getPointeeType();
11058193326Sed    Mode = 1;
11059234353Sdim    DK = diag::err_catch_incomplete_ptr;
11060198092Srdivacky  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11061193326Sed    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11062193326Sed    BaseType = Ref->getPointeeType();
11063193326Sed    Mode = 2;
11064234353Sdim    DK = diag::err_catch_incomplete_ref;
11065193326Sed  }
11066193326Sed  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11067234353Sdim      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11068193326Sed    Invalid = true;
11069193326Sed
11070198092Srdivacky  if (!Invalid && !ExDeclType->isDependentType() &&
11071193326Sed      RequireNonAbstractType(Loc, ExDeclType,
11072193326Sed                             diag::err_abstract_type_in_decl,
11073193326Sed                             AbstractVariableType))
11074193326Sed    Invalid = true;
11075193326Sed
11076212904Sdim  // Only the non-fragile NeXT runtime currently supports C++ catches
11077212904Sdim  // of ObjC types, and no runtime supports catching ObjC types by value.
11078234353Sdim  if (!Invalid && getLangOpts().ObjC1) {
11079212904Sdim    QualType T = ExDeclType;
11080212904Sdim    if (const ReferenceType *RT = T->getAs<ReferenceType>())
11081212904Sdim      T = RT->getPointeeType();
11082212904Sdim
11083212904Sdim    if (T->isObjCObjectType()) {
11084212904Sdim      Diag(Loc, diag::err_objc_object_catch);
11085212904Sdim      Invalid = true;
11086212904Sdim    } else if (T->isObjCObjectPointerType()) {
11087239462Sdim      // FIXME: should this be a test for macosx-fragile specifically?
11088239462Sdim      if (getLangOpts().ObjCRuntime.isFragile())
11089224145Sdim        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11090212904Sdim    }
11091212904Sdim  }
11092212904Sdim
11093221345Sdim  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11094249423Sdim                                    ExDeclType, TInfo, SC_None);
11095207619Srdivacky  ExDecl->setExceptionVariable(true);
11096207619Srdivacky
11097234353Sdim  // In ARC, infer 'retaining' for variables of retainable type.
11098234353Sdim  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11099234353Sdim    Invalid = true;
11100234353Sdim
11101224145Sdim  if (!Invalid && !ExDeclType->isDependentType()) {
11102218893Sdim    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11103249423Sdim      // Insulate this from anything else we might currently be parsing.
11104249423Sdim      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11105249423Sdim
11106204793Srdivacky      // C++ [except.handle]p16:
11107263508Sdim      //   The object declared in an exception-declaration or, if the
11108263508Sdim      //   exception-declaration does not specify a name, a temporary (12.2) is
11109204793Srdivacky      //   copy-initialized (8.5) from the exception object. [...]
11110204793Srdivacky      //   The object is destroyed when the handler exits, after the destruction
11111204793Srdivacky      //   of any automatic objects initialized within the handler.
11112204793Srdivacky      //
11113263508Sdim      // We just pretend to initialize the object with itself, then make sure
11114204793Srdivacky      // it can be destroyed later.
11115218893Sdim      QualType initType = ExDeclType;
11116218893Sdim
11117218893Sdim      InitializedEntity entity =
11118218893Sdim        InitializedEntity::InitializeVariable(ExDecl);
11119218893Sdim      InitializationKind initKind =
11120218893Sdim        InitializationKind::CreateCopy(Loc, SourceLocation());
11121218893Sdim
11122218893Sdim      Expr *opaqueValue =
11123218893Sdim        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11124251662Sdim      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11125251662Sdim      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11126218893Sdim      if (result.isInvalid())
11127204793Srdivacky        Invalid = true;
11128218893Sdim      else {
11129218893Sdim        // If the constructor used was non-trivial, set this as the
11130218893Sdim        // "initializer".
11131263508Sdim        CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11132218893Sdim        if (!construct->getConstructor()->isTrivial()) {
11133218893Sdim          Expr *init = MaybeCreateExprWithCleanups(construct);
11134218893Sdim          ExDecl->setInit(init);
11135218893Sdim        }
11136218893Sdim
11137218893Sdim        // And make sure it's destructable.
11138218893Sdim        FinalizeVarWithDestructor(ExDecl, recordType);
11139218893Sdim      }
11140204793Srdivacky    }
11141204793Srdivacky  }
11142204793Srdivacky
11143193326Sed  if (Invalid)
11144193326Sed    ExDecl->setInvalidDecl();
11145193326Sed
11146193326Sed  return ExDecl;
11147193326Sed}
11148193326Sed
11149193326Sed/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11150193326Sed/// handler.
11151212904SdimDecl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11152210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11153218893Sdim  bool Invalid = D.isInvalidType();
11154193326Sed
11155218893Sdim  // Check for unexpanded parameter packs.
11156249423Sdim  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11157249423Sdim                                      UPPC_ExceptionType)) {
11158218893Sdim    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11159218893Sdim                                             D.getIdentifierLoc());
11160218893Sdim    Invalid = true;
11161218893Sdim  }
11162218893Sdim
11163193326Sed  IdentifierInfo *II = D.getIdentifier();
11164207619Srdivacky  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11165207619Srdivacky                                             LookupOrdinaryName,
11166207619Srdivacky                                             ForRedeclaration)) {
11167193326Sed    // The scope should be freshly made just for us. There is just no way
11168193326Sed    // it contains any previous declaration.
11169212904Sdim    assert(!S->isDeclScope(PrevDecl));
11170193326Sed    if (PrevDecl->isTemplateParameter()) {
11171193326Sed      // Maybe we will complain about the shadowed template parameter.
11172193326Sed      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11173234353Sdim      PrevDecl = 0;
11174193326Sed    }
11175193326Sed  }
11176193326Sed
11177193326Sed  if (D.getCXXScopeSpec().isSet() && !Invalid) {
11178193326Sed    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11179193326Sed      << D.getCXXScopeSpec().getRange();
11180193326Sed    Invalid = true;
11181193326Sed  }
11182193326Sed
11183218893Sdim  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11184234353Sdim                                              D.getLocStart(),
11185221345Sdim                                              D.getIdentifierLoc(),
11186221345Sdim                                              D.getIdentifier());
11187193326Sed  if (Invalid)
11188193326Sed    ExDecl->setInvalidDecl();
11189198092Srdivacky
11190193326Sed  // Add the exception declaration into this scope.
11191193326Sed  if (II)
11192193326Sed    PushOnScopeChains(ExDecl, S);
11193193326Sed  else
11194195341Sed    CurContext->addDecl(ExDecl);
11195193326Sed
11196194613Sed  ProcessDeclAttributes(S, ExDecl, D);
11197212904Sdim  return ExDecl;
11198193326Sed}
11199193326Sed
11200221345SdimDecl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11201212904Sdim                                         Expr *AssertExpr,
11202239462Sdim                                         Expr *AssertMessageExpr,
11203221345Sdim                                         SourceLocation RParenLoc) {
11204239462Sdim  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11205193326Sed
11206239462Sdim  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11207239462Sdim    return 0;
11208239462Sdim
11209239462Sdim  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11210239462Sdim                                      AssertMessage, RParenLoc, false);
11211239462Sdim}
11212239462Sdim
11213239462SdimDecl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11214239462Sdim                                         Expr *AssertExpr,
11215239462Sdim                                         StringLiteral *AssertMessage,
11216239462Sdim                                         SourceLocation RParenLoc,
11217239462Sdim                                         bool Failed) {
11218239462Sdim  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11219239462Sdim      !Failed) {
11220234353Sdim    // In a static_assert-declaration, the constant-expression shall be a
11221234353Sdim    // constant expression that can be contextually converted to bool.
11222234353Sdim    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11223234353Sdim    if (Converted.isInvalid())
11224239462Sdim      Failed = true;
11225193326Sed
11226234353Sdim    llvm::APSInt Cond;
11227239462Sdim    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11228239462Sdim          diag::err_static_assert_expression_is_not_constant,
11229234353Sdim          /*AllowFold=*/false).isInvalid())
11230239462Sdim      Failed = true;
11231234353Sdim
11232239462Sdim    if (!Failed && !Cond) {
11233249423Sdim      SmallString<256> MsgBuffer;
11234234353Sdim      llvm::raw_svector_ostream Msg(MsgBuffer);
11235239462Sdim      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11236221345Sdim      Diag(StaticAssertLoc, diag::err_static_assert_failed)
11237234353Sdim        << Msg.str() << AssertExpr->getSourceRange();
11238239462Sdim      Failed = true;
11239193326Sed    }
11240193326Sed  }
11241198092Srdivacky
11242221345Sdim  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11243239462Sdim                                        AssertExpr, AssertMessage, RParenLoc,
11244239462Sdim                                        Failed);
11245198092Srdivacky
11246195341Sed  CurContext->addDecl(Decl);
11247212904Sdim  return Decl;
11248193326Sed}
11249193326Sed
11250207619Srdivacky/// \brief Perform semantic analysis of the given friend type declaration.
11251207619Srdivacky///
11252207619Srdivacky/// \returns A friend declaration that.
11253243830SdimFriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11254234353Sdim                                      SourceLocation FriendLoc,
11255207619Srdivacky                                      TypeSourceInfo *TSInfo) {
11256207619Srdivacky  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11257207619Srdivacky
11258207619Srdivacky  QualType T = TSInfo->getType();
11259208600Srdivacky  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11260207619Srdivacky
11261234353Sdim  // C++03 [class.friend]p2:
11262234353Sdim  //   An elaborated-type-specifier shall be used in a friend declaration
11263234353Sdim  //   for a class.*
11264234353Sdim  //
11265234353Sdim  //   * The class-key of the elaborated-type-specifier is required.
11266234353Sdim  if (!ActiveTemplateInstantiations.empty()) {
11267234353Sdim    // Do not complain about the form of friend template types during
11268234353Sdim    // template instantiation; we will already have complained when the
11269234353Sdim    // template was declared.
11270249423Sdim  } else {
11271249423Sdim    if (!T->isElaboratedTypeSpecifier()) {
11272249423Sdim      // If we evaluated the type to a record type, suggest putting
11273249423Sdim      // a tag in front.
11274249423Sdim      if (const RecordType *RT = T->getAs<RecordType>()) {
11275249423Sdim        RecordDecl *RD = RT->getDecl();
11276234353Sdim
11277249423Sdim        std::string InsertionText = std::string(" ") + RD->getKindName();
11278234353Sdim
11279249423Sdim        Diag(TypeRange.getBegin(),
11280249423Sdim             getLangOpts().CPlusPlus11 ?
11281249423Sdim               diag::warn_cxx98_compat_unelaborated_friend_type :
11282249423Sdim               diag::ext_unelaborated_friend_type)
11283249423Sdim          << (unsigned) RD->getTagKind()
11284249423Sdim          << T
11285249423Sdim          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11286249423Sdim                                        InsertionText);
11287249423Sdim      } else {
11288249423Sdim        Diag(FriendLoc,
11289249423Sdim             getLangOpts().CPlusPlus11 ?
11290249423Sdim               diag::warn_cxx98_compat_nonclass_type_friend :
11291249423Sdim               diag::ext_nonclass_type_friend)
11292249423Sdim          << T
11293249423Sdim          << TypeRange;
11294249423Sdim      }
11295249423Sdim    } else if (T->getAs<EnumType>()) {
11296234353Sdim      Diag(FriendLoc,
11297249423Sdim           getLangOpts().CPlusPlus11 ?
11298249423Sdim             diag::warn_cxx98_compat_enum_friend :
11299249423Sdim             diag::ext_enum_friend)
11300234353Sdim        << T
11301243830Sdim        << TypeRange;
11302207619Srdivacky    }
11303249423Sdim
11304249423Sdim    // C++11 [class.friend]p3:
11305249423Sdim    //   A friend declaration that does not declare a function shall have one
11306249423Sdim    //   of the following forms:
11307249423Sdim    //     friend elaborated-type-specifier ;
11308249423Sdim    //     friend simple-type-specifier ;
11309249423Sdim    //     friend typename-specifier ;
11310249423Sdim    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11311249423Sdim      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11312207619Srdivacky  }
11313243830Sdim
11314207619Srdivacky  //   If the type specifier in a friend declaration designates a (possibly
11315243830Sdim  //   cv-qualified) class type, that class is declared as a friend; otherwise,
11316207619Srdivacky  //   the friend declaration is ignored.
11317243830Sdim  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11318207619Srdivacky}
11319207619Srdivacky
11320218893Sdim/// Handle a friend tag declaration where the scope specifier was
11321218893Sdim/// templated.
11322218893SdimDecl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11323218893Sdim                                    unsigned TagSpec, SourceLocation TagLoc,
11324218893Sdim                                    CXXScopeSpec &SS,
11325249423Sdim                                    IdentifierInfo *Name,
11326249423Sdim                                    SourceLocation NameLoc,
11327218893Sdim                                    AttributeList *Attr,
11328218893Sdim                                    MultiTemplateParamsArg TempParamLists) {
11329218893Sdim  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11330218893Sdim
11331218893Sdim  bool isExplicitSpecialization = false;
11332218893Sdim  bool Invalid = false;
11333218893Sdim
11334263508Sdim  if (TemplateParameterList *TemplateParams =
11335263508Sdim          MatchTemplateParametersToScopeSpecifier(
11336263508Sdim              TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11337263508Sdim              isExplicitSpecialization, Invalid)) {
11338218893Sdim    if (TemplateParams->size() > 0) {
11339218893Sdim      // This is a declaration of a class template.
11340218893Sdim      if (Invalid)
11341218893Sdim        return 0;
11342221345Sdim
11343218893Sdim      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11344218893Sdim                                SS, Name, NameLoc, Attr,
11345221345Sdim                                TemplateParams, AS_public,
11346226633Sdim                                /*ModulePrivateLoc=*/SourceLocation(),
11347221345Sdim                                TempParamLists.size() - 1,
11348243830Sdim                                TempParamLists.data()).take();
11349218893Sdim    } else {
11350218893Sdim      // The "template<>" header is extraneous.
11351218893Sdim      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11352218893Sdim        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11353218893Sdim      isExplicitSpecialization = true;
11354218893Sdim    }
11355218893Sdim  }
11356218893Sdim
11357218893Sdim  if (Invalid) return 0;
11358218893Sdim
11359218893Sdim  bool isAllExplicitSpecializations = true;
11360221345Sdim  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11361243830Sdim    if (TempParamLists[I]->size()) {
11362218893Sdim      isAllExplicitSpecializations = false;
11363218893Sdim      break;
11364218893Sdim    }
11365218893Sdim  }
11366218893Sdim
11367218893Sdim  // FIXME: don't ignore attributes.
11368218893Sdim
11369218893Sdim  // If it's explicit specializations all the way down, just forget
11370218893Sdim  // about the template header and build an appropriate non-templated
11371218893Sdim  // friend.  TODO: for source fidelity, remember the headers.
11372218893Sdim  if (isAllExplicitSpecializations) {
11373234353Sdim    if (SS.isEmpty()) {
11374234353Sdim      bool Owned = false;
11375234353Sdim      bool IsDependent = false;
11376234353Sdim      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11377234353Sdim                      Attr, AS_public,
11378234353Sdim                      /*ModulePrivateLoc=*/SourceLocation(),
11379234353Sdim                      MultiTemplateParamsArg(), Owned, IsDependent,
11380234353Sdim                      /*ScopedEnumKWLoc=*/SourceLocation(),
11381234353Sdim                      /*ScopedEnumUsesClassTag=*/false,
11382234353Sdim                      /*UnderlyingType=*/TypeResult());
11383234353Sdim    }
11384234353Sdim
11385221345Sdim    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11386218893Sdim    ElaboratedTypeKeyword Keyword
11387218893Sdim      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11388221345Sdim    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11389221345Sdim                                   *Name, NameLoc);
11390218893Sdim    if (T.isNull())
11391218893Sdim      return 0;
11392218893Sdim
11393218893Sdim    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11394218893Sdim    if (isa<DependentNameType>(T)) {
11395249423Sdim      DependentNameTypeLoc TL =
11396249423Sdim          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11397234353Sdim      TL.setElaboratedKeywordLoc(TagLoc);
11398221345Sdim      TL.setQualifierLoc(QualifierLoc);
11399218893Sdim      TL.setNameLoc(NameLoc);
11400218893Sdim    } else {
11401249423Sdim      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11402234353Sdim      TL.setElaboratedKeywordLoc(TagLoc);
11403221345Sdim      TL.setQualifierLoc(QualifierLoc);
11404249423Sdim      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11405218893Sdim    }
11406218893Sdim
11407218893Sdim    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11408249423Sdim                                            TSI, FriendLoc, TempParamLists);
11409218893Sdim    Friend->setAccess(AS_public);
11410218893Sdim    CurContext->addDecl(Friend);
11411218893Sdim    return Friend;
11412218893Sdim  }
11413234353Sdim
11414234353Sdim  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11415234353Sdim
11416218893Sdim
11417234353Sdim
11418218893Sdim  // Handle the case of a templated-scope friend class.  e.g.
11419218893Sdim  //   template <class T> class A<T>::B;
11420218893Sdim  // FIXME: we don't support these right now.
11421263508Sdim  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11422263508Sdim    << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11423218893Sdim  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11424218893Sdim  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11425218893Sdim  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11426249423Sdim  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11427234353Sdim  TL.setElaboratedKeywordLoc(TagLoc);
11428221345Sdim  TL.setQualifierLoc(SS.getWithLocInContext(Context));
11429218893Sdim  TL.setNameLoc(NameLoc);
11430218893Sdim
11431218893Sdim  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11432249423Sdim                                          TSI, FriendLoc, TempParamLists);
11433218893Sdim  Friend->setAccess(AS_public);
11434218893Sdim  Friend->setUnsupportedFriend(true);
11435218893Sdim  CurContext->addDecl(Friend);
11436218893Sdim  return Friend;
11437218893Sdim}
11438218893Sdim
11439218893Sdim
11440198092Srdivacky/// Handle a friend type declaration.  This works in tandem with
11441198092Srdivacky/// ActOnTag.
11442198092Srdivacky///
11443198092Srdivacky/// Notes on friend class templates:
11444198092Srdivacky///
11445198092Srdivacky/// We generally treat friend class declarations as if they were
11446198092Srdivacky/// declaring a class.  So, for example, the elaborated type specifier
11447198092Srdivacky/// in a friend declaration is required to obey the restrictions of a
11448198092Srdivacky/// class-head (i.e. no typedefs in the scope chain), template
11449198092Srdivacky/// parameters are required to match up with simple template-ids, &c.
11450198092Srdivacky/// However, unlike when declaring a template specialization, it's
11451198092Srdivacky/// okay to refer to a template specialization without an empty
11452198092Srdivacky/// template parameter declaration, e.g.
11453198092Srdivacky///   friend class A<T>::B<unsigned>;
11454198092Srdivacky/// We permit this as a special case; if there are any template
11455198092Srdivacky/// parameters present at all, require proper matching, i.e.
11456239462Sdim///   template <> template \<class T> friend class A<int>::B;
11457212904SdimDecl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11458218893Sdim                                MultiTemplateParamsArg TempParams) {
11459234353Sdim  SourceLocation Loc = DS.getLocStart();
11460198092Srdivacky
11461198092Srdivacky  assert(DS.isFriendSpecified());
11462198092Srdivacky  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11463198092Srdivacky
11464198092Srdivacky  // Try to convert the decl specifier to a type.  This works for
11465198092Srdivacky  // friend templates because ActOnTag never produces a ClassTemplateDecl
11466198092Srdivacky  // for a TUK_Friend.
11467198893Srdivacky  Declarator TheDeclarator(DS, Declarator::MemberContext);
11468210299Sed  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11469210299Sed  QualType T = TSI->getType();
11470198893Srdivacky  if (TheDeclarator.isInvalidType())
11471212904Sdim    return 0;
11472198092Srdivacky
11473218893Sdim  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11474218893Sdim    return 0;
11475218893Sdim
11476198092Srdivacky  // This is definitely an error in C++98.  It's probably meant to
11477198092Srdivacky  // be forbidden in C++0x, too, but the specification is just
11478198092Srdivacky  // poorly written.
11479198092Srdivacky  //
11480198092Srdivacky  // The problem is with declarations like the following:
11481198092Srdivacky  //   template <T> friend A<T>::foo;
11482198092Srdivacky  // where deciding whether a class C is a friend or not now hinges
11483198092Srdivacky  // on whether there exists an instantiation of A that causes
11484198092Srdivacky  // 'foo' to equal C.  There are restrictions on class-heads
11485198092Srdivacky  // (which we declare (by fiat) elaborated friend declarations to
11486198092Srdivacky  // be) that makes this tractable.
11487198092Srdivacky  //
11488198092Srdivacky  // FIXME: handle "template <> friend class A<T>;", which
11489198092Srdivacky  // is possibly well-formed?  Who even knows?
11490206084Srdivacky  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11491198092Srdivacky    Diag(Loc, diag::err_tagless_friend_type_template)
11492198092Srdivacky      << DS.getSourceRange();
11493212904Sdim    return 0;
11494193326Sed  }
11495207619Srdivacky
11496198092Srdivacky  // C++98 [class.friend]p1: A friend of a class is a function
11497198092Srdivacky  //   or class that is not a member of the class . . .
11498201361Srdivacky  // This is fixed in DR77, which just barely didn't make the C++03
11499201361Srdivacky  // deadline.  It's also a very silly restriction that seriously
11500201361Srdivacky  // affects inner classes and which nobody else seems to implement;
11501201361Srdivacky  // thus we never diagnose it, not even in -pedantic.
11502206084Srdivacky  //
11503206084Srdivacky  // But note that we could warn about it: it's always useless to
11504206084Srdivacky  // friend one of your own members (it's not, however, worthless to
11505206084Srdivacky  // friend a member of an arbitrary specialization of your template).
11506198092Srdivacky
11507198092Srdivacky  Decl *D;
11508207619Srdivacky  if (unsigned NumTempParamLists = TempParams.size())
11509198092Srdivacky    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11510207619Srdivacky                                   NumTempParamLists,
11511243830Sdim                                   TempParams.data(),
11512206084Srdivacky                                   TSI,
11513198092Srdivacky                                   DS.getFriendSpecLoc());
11514198092Srdivacky  else
11515234353Sdim    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11516207619Srdivacky
11517207619Srdivacky  if (!D)
11518212904Sdim    return 0;
11519207619Srdivacky
11520198092Srdivacky  D->setAccess(AS_public);
11521198092Srdivacky  CurContext->addDecl(D);
11522198092Srdivacky
11523212904Sdim  return D;
11524193326Sed}
11525193326Sed
11526249423SdimNamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11527249423Sdim                                        MultiTemplateParamsArg TemplateParams) {
11528198092Srdivacky  const DeclSpec &DS = D.getDeclSpec();
11529198092Srdivacky
11530198092Srdivacky  assert(DS.isFriendSpecified());
11531198092Srdivacky  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11532198092Srdivacky
11533198092Srdivacky  SourceLocation Loc = D.getIdentifierLoc();
11534210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11535198092Srdivacky
11536198092Srdivacky  // C++ [class.friend]p1
11537198092Srdivacky  //   A friend of a class is a function or class....
11538198092Srdivacky  // Note that this sees through typedefs, which is intended.
11539198092Srdivacky  // It *doesn't* see through dependent types, which is correct
11540198092Srdivacky  // according to [temp.arg.type]p3:
11541198092Srdivacky  //   If a declaration acquires a function type through a
11542198092Srdivacky  //   type dependent on a template-parameter and this causes
11543198092Srdivacky  //   a declaration that does not use the syntactic form of a
11544198092Srdivacky  //   function declarator to have a function type, the program
11545198092Srdivacky  //   is ill-formed.
11546226633Sdim  if (!TInfo->getType()->isFunctionType()) {
11547198092Srdivacky    Diag(Loc, diag::err_unexpected_friend);
11548198092Srdivacky
11549198092Srdivacky    // It might be worthwhile to try to recover by creating an
11550198092Srdivacky    // appropriate declaration.
11551212904Sdim    return 0;
11552198092Srdivacky  }
11553198092Srdivacky
11554198092Srdivacky  // C++ [namespace.memdef]p3
11555198092Srdivacky  //  - If a friend declaration in a non-local class first declares a
11556198092Srdivacky  //    class or function, the friend class or function is a member
11557198092Srdivacky  //    of the innermost enclosing namespace.
11558198092Srdivacky  //  - The name of the friend is not found by simple name lookup
11559198092Srdivacky  //    until a matching declaration is provided in that namespace
11560198092Srdivacky  //    scope (either before or after the class declaration granting
11561198092Srdivacky  //    friendship).
11562198092Srdivacky  //  - If a friend function is called, its name may be found by the
11563198092Srdivacky  //    name lookup that considers functions from namespaces and
11564198092Srdivacky  //    classes associated with the types of the function arguments.
11565198092Srdivacky  //  - When looking for a prior declaration of a class or a function
11566198092Srdivacky  //    declared as a friend, scopes outside the innermost enclosing
11567198092Srdivacky  //    namespace scope are not considered.
11568198092Srdivacky
11569218893Sdim  CXXScopeSpec &SS = D.getCXXScopeSpec();
11570212904Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11571212904Sdim  DeclarationName Name = NameInfo.getName();
11572198092Srdivacky  assert(Name);
11573198092Srdivacky
11574218893Sdim  // Check for unexpanded parameter packs.
11575218893Sdim  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11576218893Sdim      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11577218893Sdim      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11578218893Sdim    return 0;
11579218893Sdim
11580198092Srdivacky  // The context we found the declaration in, or in which we should
11581198092Srdivacky  // create the declaration.
11582198092Srdivacky  DeclContext *DC;
11583218893Sdim  Scope *DCScope = S;
11584218893Sdim  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11585218893Sdim                        ForRedeclaration);
11586198092Srdivacky
11587263508Sdim  // There are five cases here.
11588263508Sdim  //   - There's no scope specifier and we're in a local class. Only look
11589263508Sdim  //     for functions declared in the immediately-enclosing block scope.
11590263508Sdim  // We recover from invalid scope qualifiers as if they just weren't there.
11591263508Sdim  FunctionDecl *FunctionContainingLocalClass = 0;
11592263508Sdim  if ((SS.isInvalid() || !SS.isSet()) &&
11593263508Sdim      (FunctionContainingLocalClass =
11594263508Sdim           cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11595263508Sdim    // C++11 [class.friend]p11:
11596263508Sdim    //   If a friend declaration appears in a local class and the name
11597263508Sdim    //   specified is an unqualified name, a prior declaration is
11598263508Sdim    //   looked up without considering scopes that are outside the
11599263508Sdim    //   innermost enclosing non-class scope. For a friend function
11600263508Sdim    //   declaration, if there is no prior declaration, the program is
11601263508Sdim    //   ill-formed.
11602198092Srdivacky
11603263508Sdim    // Find the innermost enclosing non-class scope. This is the block
11604263508Sdim    // scope containing the local class definition (or for a nested class,
11605263508Sdim    // the outer local class).
11606263508Sdim    DCScope = S->getFnParent();
11607263508Sdim
11608263508Sdim    // Look up the function name in the scope.
11609263508Sdim    Previous.clear(LookupLocalFriendName);
11610263508Sdim    LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11611263508Sdim
11612263508Sdim    if (!Previous.empty()) {
11613263508Sdim      // All possible previous declarations must have the same context:
11614263508Sdim      // either they were declared at block scope or they are members of
11615263508Sdim      // one of the enclosing local classes.
11616263508Sdim      DC = Previous.getRepresentativeDecl()->getDeclContext();
11617263508Sdim    } else {
11618263508Sdim      // This is ill-formed, but provide the context that we would have
11619263508Sdim      // declared the function in, if we were permitted to, for error recovery.
11620263508Sdim      DC = FunctionContainingLocalClass;
11621263508Sdim    }
11622263508Sdim    adjustContextForLocalExternDecl(DC);
11623263508Sdim
11624263508Sdim    // C++ [class.friend]p6:
11625263508Sdim    //   A function can be defined in a friend declaration of a class if and
11626263508Sdim    //   only if the class is a non-local class (9.8), the function name is
11627263508Sdim    //   unqualified, and the function has namespace scope.
11628263508Sdim    if (D.isFunctionDefinition()) {
11629263508Sdim      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11630263508Sdim    }
11631263508Sdim
11632218893Sdim  //   - There's no scope specifier, in which case we just go to the
11633218893Sdim  //     appropriate scope and look for a function or function template
11634218893Sdim  //     there as appropriate.
11635263508Sdim  } else if (SS.isInvalid() || !SS.isSet()) {
11636263508Sdim    // C++11 [namespace.memdef]p3:
11637218893Sdim    //   If the name in a friend declaration is neither qualified nor
11638218893Sdim    //   a template-id and the declaration is a function or an
11639218893Sdim    //   elaborated-type-specifier, the lookup to determine whether
11640218893Sdim    //   the entity has been previously declared shall not consider
11641218893Sdim    //   any scopes outside the innermost enclosing namespace.
11642218893Sdim    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11643198092Srdivacky
11644218893Sdim    // Find the appropriate context according to the above.
11645218893Sdim    DC = CurContext;
11646251662Sdim
11647251662Sdim    // Skip class contexts.  If someone can cite chapter and verse
11648251662Sdim    // for this behavior, that would be nice --- it's what GCC and
11649251662Sdim    // EDG do, and it seems like a reasonable intent, but the spec
11650251662Sdim    // really only says that checks for unqualified existing
11651251662Sdim    // declarations should stop at the nearest enclosing namespace,
11652251662Sdim    // not that they should only consider the nearest enclosing
11653251662Sdim    // namespace.
11654251662Sdim    while (DC->isRecord())
11655251662Sdim      DC = DC->getParent();
11656251662Sdim
11657251662Sdim    DeclContext *LookupDC = DC;
11658251662Sdim    while (LookupDC->isTransparentContext())
11659251662Sdim      LookupDC = LookupDC->getParent();
11660251662Sdim
11661218893Sdim    while (true) {
11662251662Sdim      LookupQualifiedName(Previous, LookupDC);
11663218893Sdim
11664251662Sdim      if (!Previous.empty()) {
11665251662Sdim        DC = LookupDC;
11666251662Sdim        break;
11667251662Sdim      }
11668251662Sdim
11669218893Sdim      if (isTemplateId) {
11670251662Sdim        if (isa<TranslationUnitDecl>(LookupDC)) break;
11671218893Sdim      } else {
11672251662Sdim        if (LookupDC->isFileContext()) break;
11673218893Sdim      }
11674251662Sdim      LookupDC = LookupDC->getParent();
11675218893Sdim    }
11676218893Sdim
11677218893Sdim    DCScope = getScopeForDeclContext(S, DC);
11678263508Sdim
11679218893Sdim  //   - There's a non-dependent scope specifier, in which case we
11680218893Sdim  //     compute it and do a previous lookup there for a function
11681218893Sdim  //     or function template.
11682218893Sdim  } else if (!SS.getScopeRep()->isDependent()) {
11683218893Sdim    DC = computeDeclContext(SS);
11684212904Sdim    if (!DC) return 0;
11685198092Srdivacky
11686218893Sdim    if (RequireCompleteDeclContext(SS, DC)) return 0;
11687218893Sdim
11688199512Srdivacky    LookupQualifiedName(Previous, DC);
11689198092Srdivacky
11690210299Sed    // Ignore things found implicitly in the wrong scope.
11691198092Srdivacky    // TODO: better diagnostics for this case.  Suggesting the right
11692198092Srdivacky    // qualified scope would be nice...
11693210299Sed    LookupResult::Filter F = Previous.makeFilter();
11694210299Sed    while (F.hasNext()) {
11695210299Sed      NamedDecl *D = F.next();
11696212904Sdim      if (!DC->InEnclosingNamespaceSetOf(
11697212904Sdim              D->getDeclContext()->getRedeclContext()))
11698210299Sed        F.erase();
11699210299Sed    }
11700210299Sed    F.done();
11701210299Sed
11702210299Sed    if (Previous.empty()) {
11703198092Srdivacky      D.setInvalidType();
11704226633Sdim      Diag(Loc, diag::err_qualified_friend_not_found)
11705226633Sdim          << Name << TInfo->getType();
11706212904Sdim      return 0;
11707198092Srdivacky    }
11708198092Srdivacky
11709198092Srdivacky    // C++ [class.friend]p1: A friend of a class is a function or
11710198092Srdivacky    //   class that is not a member of the class . . .
11711198092Srdivacky    if (DC->Equals(CurContext))
11712234353Sdim      Diag(DS.getFriendSpecLoc(),
11713249423Sdim           getLangOpts().CPlusPlus11 ?
11714234353Sdim             diag::warn_cxx98_compat_friend_is_member :
11715234353Sdim             diag::err_friend_is_member);
11716226633Sdim
11717226633Sdim    if (D.isFunctionDefinition()) {
11718226633Sdim      // C++ [class.friend]p6:
11719226633Sdim      //   A function can be defined in a friend declaration of a class if and
11720226633Sdim      //   only if the class is a non-local class (9.8), the function name is
11721226633Sdim      //   unqualified, and the function has namespace scope.
11722226633Sdim      SemaDiagnosticBuilder DB
11723226633Sdim        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11724226633Sdim
11725226633Sdim      DB << SS.getScopeRep();
11726226633Sdim      if (DC->isFileContext())
11727226633Sdim        DB << FixItHint::CreateRemoval(SS.getRange());
11728226633Sdim      SS.clear();
11729226633Sdim    }
11730198092Srdivacky
11731218893Sdim  //   - There's a scope specifier that does not match any template
11732218893Sdim  //     parameter lists, in which case we use some arbitrary context,
11733218893Sdim  //     create a method or method template, and wait for instantiation.
11734218893Sdim  //   - There's a scope specifier that does match some template
11735218893Sdim  //     parameter lists, which we don't handle right now.
11736198092Srdivacky  } else {
11737226633Sdim    if (D.isFunctionDefinition()) {
11738226633Sdim      // C++ [class.friend]p6:
11739226633Sdim      //   A function can be defined in a friend declaration of a class if and
11740226633Sdim      //   only if the class is a non-local class (9.8), the function name is
11741226633Sdim      //   unqualified, and the function has namespace scope.
11742226633Sdim      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11743226633Sdim        << SS.getScopeRep();
11744226633Sdim    }
11745226633Sdim
11746198092Srdivacky    DC = CurContext;
11747218893Sdim    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11748198092Srdivacky  }
11749226633Sdim
11750218893Sdim  if (!DC->isRecord()) {
11751198092Srdivacky    // This implies that it has to be an operator or function.
11752198893Srdivacky    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11753198893Srdivacky        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11754198893Srdivacky        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11755198092Srdivacky      Diag(Loc, diag::err_introducing_special_friend) <<
11756198893Srdivacky        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11757198893Srdivacky         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11758212904Sdim      return 0;
11759198092Srdivacky    }
11760198092Srdivacky  }
11761198092Srdivacky
11762234353Sdim  // FIXME: This is an egregious hack to cope with cases where the scope stack
11763234353Sdim  // does not contain the declaration context, i.e., in an out-of-line
11764234353Sdim  // definition of a class.
11765234353Sdim  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11766234353Sdim  if (!DCScope) {
11767234353Sdim    FakeDCScope.setEntity(DC);
11768234353Sdim    DCScope = &FakeDCScope;
11769234353Sdim  }
11770263508Sdim
11771226633Sdim  bool AddToScope = true;
11772226633Sdim  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11773243830Sdim                                          TemplateParams, AddToScope);
11774212904Sdim  if (!ND) return 0;
11775198092Srdivacky
11776198092Srdivacky  assert(ND->getLexicalDeclContext() == CurContext);
11777198092Srdivacky
11778263508Sdim  // If we performed typo correction, we might have added a scope specifier
11779263508Sdim  // and changed the decl context.
11780263508Sdim  DC = ND->getDeclContext();
11781263508Sdim
11782198092Srdivacky  // Add the function declaration to the appropriate lookup tables,
11783198092Srdivacky  // adjusting the redeclarations list as necessary.  We don't
11784198092Srdivacky  // want to do this yet if the friending class is dependent.
11785198092Srdivacky  //
11786198092Srdivacky  // Also update the scope-based lookup if the target context's
11787198092Srdivacky  // lookup context is in lexical scope.
11788198092Srdivacky  if (!CurContext->isDependentContext()) {
11789212904Sdim    DC = DC->getRedeclContext();
11790234353Sdim    DC->makeDeclVisibleInContext(ND);
11791198092Srdivacky    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11792198092Srdivacky      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11793198092Srdivacky  }
11794198092Srdivacky
11795198092Srdivacky  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11796198092Srdivacky                                       D.getIdentifierLoc(), ND,
11797198092Srdivacky                                       DS.getFriendSpecLoc());
11798198092Srdivacky  FrD->setAccess(AS_public);
11799198092Srdivacky  CurContext->addDecl(FrD);
11800198092Srdivacky
11801239462Sdim  if (ND->isInvalidDecl()) {
11802218893Sdim    FrD->setInvalidDecl();
11803239462Sdim  } else {
11804239462Sdim    if (DC->isRecord()) CheckFriendAccess(ND);
11805239462Sdim
11806218893Sdim    FunctionDecl *FD;
11807218893Sdim    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11808218893Sdim      FD = FTD->getTemplatedDecl();
11809218893Sdim    else
11810218893Sdim      FD = cast<FunctionDecl>(ND);
11811218893Sdim
11812263508Sdim    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11813263508Sdim    // default argument expression, that declaration shall be a definition
11814263508Sdim    // and shall be the only declaration of the function or function
11815263508Sdim    // template in the translation unit.
11816263508Sdim    if (functionDeclHasDefaultArgument(FD)) {
11817263508Sdim      if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11818263508Sdim        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11819263508Sdim        Diag(OldFD->getLocation(), diag::note_previous_declaration);
11820263508Sdim      } else if (!D.isFunctionDefinition())
11821263508Sdim        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11822263508Sdim    }
11823263508Sdim
11824218893Sdim    // Mark templated-scope function declarations as unsupported.
11825218893Sdim    if (FD->getNumTemplateParameterLists())
11826218893Sdim      FrD->setUnsupportedFriend(true);
11827218893Sdim  }
11828218893Sdim
11829212904Sdim  return ND;
11830198092Srdivacky}
11831198092Srdivacky
11832212904Sdimvoid Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11833212904Sdim  AdjustDeclIfTemplate(Dcl);
11834198092Srdivacky
11835249423Sdim  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11836193326Sed  if (!Fn) {
11837193326Sed    Diag(DelLoc, diag::err_deleted_non_function);
11838193326Sed    return;
11839193326Sed  }
11840249423Sdim
11841234353Sdim  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11842239462Sdim    // Don't consider the implicit declaration we generate for explicit
11843239462Sdim    // specializations. FIXME: Do not generate these implicit declarations.
11844239462Sdim    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11845239462Sdim        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11846239462Sdim      Diag(DelLoc, diag::err_deleted_decl_not_first);
11847239462Sdim      Diag(Prev->getLocation(), diag::note_previous_declaration);
11848239462Sdim    }
11849193326Sed    // If the declaration wasn't the first, we delete the function anyway for
11850193326Sed    // recovery.
11851249423Sdim    Fn = Fn->getCanonicalDecl();
11852193326Sed  }
11853234353Sdim
11854249423Sdim  if (Fn->isDeleted())
11855234353Sdim    return;
11856234353Sdim
11857249423Sdim  // See if we're deleting a function which is already known to override a
11858249423Sdim  // non-deleted virtual function.
11859249423Sdim  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11860249423Sdim    bool IssuedDiagnostic = false;
11861249423Sdim    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11862249423Sdim                                        E = MD->end_overridden_methods();
11863249423Sdim         I != E; ++I) {
11864249423Sdim      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11865249423Sdim        if (!IssuedDiagnostic) {
11866249423Sdim          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11867249423Sdim          IssuedDiagnostic = true;
11868249423Sdim        }
11869249423Sdim        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11870249423Sdim      }
11871249423Sdim    }
11872234353Sdim  }
11873249423Sdim
11874249423Sdim  Fn->setDeletedAsWritten();
11875193326Sed}
11876193326Sed
11877223017Sdimvoid Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11878249423Sdim  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11879223017Sdim
11880223017Sdim  if (MD) {
11881223017Sdim    if (MD->getParent()->isDependentType()) {
11882223017Sdim      MD->setDefaulted();
11883223017Sdim      MD->setExplicitlyDefaulted();
11884223017Sdim      return;
11885223017Sdim    }
11886223017Sdim
11887223017Sdim    CXXSpecialMember Member = getSpecialMember(MD);
11888223017Sdim    if (Member == CXXInvalid) {
11889263508Sdim      if (!MD->isInvalidDecl())
11890263508Sdim        Diag(DefaultLoc, diag::err_default_special_members);
11891223017Sdim      return;
11892223017Sdim    }
11893223017Sdim
11894223017Sdim    MD->setDefaulted();
11895223017Sdim    MD->setExplicitlyDefaulted();
11896223017Sdim
11897223017Sdim    // If this definition appears within the record, do the checking when
11898223017Sdim    // the record is complete.
11899223017Sdim    const FunctionDecl *Primary = MD;
11900243830Sdim    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11901223017Sdim      // Find the uninstantiated declaration that actually had the '= default'
11902223017Sdim      // on it.
11903243830Sdim      Pattern->isDefined(Primary);
11904223017Sdim
11905249423Sdim    // If the method was defaulted on its first declaration, we will have
11906249423Sdim    // already performed the checking in CheckCompletedCXXClass. Such a
11907249423Sdim    // declaration doesn't trigger an implicit definition.
11908223017Sdim    if (Primary == Primary->getCanonicalDecl())
11909223017Sdim      return;
11910223017Sdim
11911239462Sdim    CheckExplicitlyDefaultedSpecialMember(MD);
11912239462Sdim
11913249423Sdim    // The exception specification is needed because we are defining the
11914249423Sdim    // function.
11915249423Sdim    ResolveExceptionSpec(DefaultLoc,
11916249423Sdim                         MD->getType()->castAs<FunctionProtoType>());
11917249423Sdim
11918263508Sdim    if (MD->isInvalidDecl())
11919263508Sdim      return;
11920263508Sdim
11921223017Sdim    switch (Member) {
11922263508Sdim    case CXXDefaultConstructor:
11923263508Sdim      DefineImplicitDefaultConstructor(DefaultLoc,
11924263508Sdim                                       cast<CXXConstructorDecl>(MD));
11925223017Sdim      break;
11926263508Sdim    case CXXCopyConstructor:
11927263508Sdim      DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11928223017Sdim      break;
11929263508Sdim    case CXXCopyAssignment:
11930263508Sdim      DefineImplicitCopyAssignment(DefaultLoc, MD);
11931223017Sdim      break;
11932263508Sdim    case CXXDestructor:
11933263508Sdim      DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11934223017Sdim      break;
11935263508Sdim    case CXXMoveConstructor:
11936263508Sdim      DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11937223017Sdim      break;
11938263508Sdim    case CXXMoveAssignment:
11939263508Sdim      DefineImplicitMoveAssignment(DefaultLoc, MD);
11940223017Sdim      break;
11941226633Sdim    case CXXInvalid:
11942226633Sdim      llvm_unreachable("Invalid special member.");
11943226633Sdim    }
11944223017Sdim  } else {
11945223017Sdim    Diag(DefaultLoc, diag::err_default_special_members);
11946223017Sdim  }
11947223017Sdim}
11948223017Sdim
11949193326Sedstatic void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11950218893Sdim  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11951193326Sed    Stmt *SubStmt = *CI;
11952193326Sed    if (!SubStmt)
11953193326Sed      continue;
11954193326Sed    if (isa<ReturnStmt>(SubStmt))
11955234353Sdim      Self.Diag(SubStmt->getLocStart(),
11956193326Sed           diag::err_return_in_constructor_handler);
11957193326Sed    if (!isa<Expr>(SubStmt))
11958193326Sed      SearchForReturnInStmt(Self, SubStmt);
11959193326Sed  }
11960193326Sed}
11961193326Sed
11962193326Sedvoid Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11963193326Sed  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11964193326Sed    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11965193326Sed    SearchForReturnInStmt(*this, Handler);
11966193326Sed  }
11967193326Sed}
11968193326Sed
11969249423Sdimbool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11970249423Sdim                                             const CXXMethodDecl *Old) {
11971249423Sdim  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11972249423Sdim  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11973249423Sdim
11974249423Sdim  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11975249423Sdim
11976249423Sdim  // If the calling conventions match, everything is fine
11977249423Sdim  if (NewCC == OldCC)
11978249423Sdim    return false;
11979249423Sdim
11980263508Sdim  Diag(New->getLocation(),
11981263508Sdim       diag::err_conflicting_overriding_cc_attributes)
11982263508Sdim    << New->getDeclName() << New->getType() << Old->getType();
11983263508Sdim  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11984263508Sdim  return true;
11985249423Sdim}
11986249423Sdim
11987198092Srdivackybool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11988193326Sed                                             const CXXMethodDecl *Old) {
11989198092Srdivacky  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11990198092Srdivacky  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11991193326Sed
11992203955Srdivacky  if (Context.hasSameType(NewTy, OldTy) ||
11993203955Srdivacky      NewTy->isDependentType() || OldTy->isDependentType())
11994193326Sed    return false;
11995198092Srdivacky
11996193326Sed  // Check if the return types are covariant
11997193326Sed  QualType NewClassTy, OldClassTy;
11998198092Srdivacky
11999193326Sed  /// Both types must be pointers or references to classes.
12000202879Srdivacky  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12001202879Srdivacky    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12002193326Sed      NewClassTy = NewPT->getPointeeType();
12003193326Sed      OldClassTy = OldPT->getPointeeType();
12004193326Sed    }
12005202879Srdivacky  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12006202879Srdivacky    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12007202879Srdivacky      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12008202879Srdivacky        NewClassTy = NewRT->getPointeeType();
12009202879Srdivacky        OldClassTy = OldRT->getPointeeType();
12010202879Srdivacky      }
12011193326Sed    }
12012193326Sed  }
12013198092Srdivacky
12014193326Sed  // The return types aren't either both pointers or references to a class type.
12015193326Sed  if (NewClassTy.isNull()) {
12016198092Srdivacky    Diag(New->getLocation(),
12017193326Sed         diag::err_different_return_type_for_overriding_virtual_function)
12018193326Sed      << New->getDeclName() << NewTy << OldTy;
12019193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12020198092Srdivacky
12021193326Sed    return true;
12022193326Sed  }
12023193326Sed
12024201361Srdivacky  // C++ [class.virtual]p6:
12025201361Srdivacky  //   If the return type of D::f differs from the return type of B::f, the
12026201361Srdivacky  //   class type in the return type of D::f shall be complete at the point of
12027201361Srdivacky  //   declaration of D::f or shall be the class type D.
12028201361Srdivacky  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12029201361Srdivacky    if (!RT->isBeingDefined() &&
12030201361Srdivacky        RequireCompleteType(New->getLocation(), NewClassTy,
12031239462Sdim                            diag::err_covariant_return_incomplete,
12032239462Sdim                            New->getDeclName()))
12033201361Srdivacky    return true;
12034201361Srdivacky  }
12035201361Srdivacky
12036199482Srdivacky  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12037193326Sed    // Check if the new class derives from the old class.
12038193326Sed    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12039193326Sed      Diag(New->getLocation(),
12040193326Sed           diag::err_covariant_return_not_derived)
12041193326Sed      << New->getDeclName() << NewTy << OldTy;
12042193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12043193326Sed      return true;
12044193326Sed    }
12045198092Srdivacky
12046193326Sed    // Check if we the conversion from derived to base is valid.
12047205219Srdivacky    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12048207619Srdivacky                    diag::err_covariant_return_inaccessible_base,
12049207619Srdivacky                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
12050207619Srdivacky                    // FIXME: Should this point to the return type?
12051207619Srdivacky                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12052218893Sdim      // FIXME: this note won't trigger for delayed access control
12053218893Sdim      // diagnostics, and it's impossible to get an undelayed error
12054218893Sdim      // here from access control during the original parse because
12055218893Sdim      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12056193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12057193326Sed      return true;
12058193326Sed    }
12059193326Sed  }
12060198092Srdivacky
12061193326Sed  // The qualifiers of the return types must be the same.
12062202879Srdivacky  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12063193326Sed    Diag(New->getLocation(),
12064193326Sed         diag::err_covariant_return_type_different_qualifications)
12065193326Sed    << New->getDeclName() << NewTy << OldTy;
12066193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12067193326Sed    return true;
12068193326Sed  };
12069193326Sed
12070198092Srdivacky
12071193326Sed  // The new class type must have the same or less qualifiers as the old type.
12072193326Sed  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12073193326Sed    Diag(New->getLocation(),
12074193326Sed         diag::err_covariant_return_type_class_type_more_qualified)
12075193326Sed    << New->getDeclName() << NewTy << OldTy;
12076193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12077193326Sed    return true;
12078193326Sed  };
12079198092Srdivacky
12080193326Sed  return false;
12081193326Sed}
12082194613Sed
12083200583Srdivacky/// \brief Mark the given method pure.
12084200583Srdivacky///
12085200583Srdivacky/// \param Method the method to be marked pure.
12086200583Srdivacky///
12087200583Srdivacky/// \param InitRange the source range that covers the "0" initializer.
12088200583Srdivackybool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12089221345Sdim  SourceLocation EndLoc = InitRange.getEnd();
12090221345Sdim  if (EndLoc.isValid())
12091221345Sdim    Method->setRangeEnd(EndLoc);
12092221345Sdim
12093200583Srdivacky  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12094200583Srdivacky    Method->setPure();
12095200583Srdivacky    return false;
12096221345Sdim  }
12097200583Srdivacky
12098200583Srdivacky  if (!Method->isInvalidDecl())
12099200583Srdivacky    Diag(Method->getLocation(), diag::err_non_virtual_pure)
12100200583Srdivacky      << Method->getDeclName() << InitRange;
12101200583Srdivacky  return true;
12102200583Srdivacky}
12103200583Srdivacky
12104234353Sdim/// \brief Determine whether the given declaration is a static data member.
12105263508Sdimstatic bool isStaticDataMember(const Decl *D) {
12106263508Sdim  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12107263508Sdim    return Var->isStaticDataMember();
12108263508Sdim
12109263508Sdim  return false;
12110234353Sdim}
12111263508Sdim
12112201361Srdivacky/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12113201361Srdivacky/// an initializer for the out-of-line declaration 'Dcl'.  The scope
12114201361Srdivacky/// is a fresh scope pushed for just this purpose.
12115201361Srdivacky///
12116194613Sed/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12117194613Sed/// static data member of class X, names should be looked up in the scope of
12118194613Sed/// class X.
12119212904Sdimvoid Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12120201361Srdivacky  // If there is no declaration, there was an error parsing it.
12121221345Sdim  if (D == 0 || D->isInvalidDecl()) return;
12122194613Sed
12123201361Srdivacky  // We should only get called for declarations with scope specifiers, like:
12124201361Srdivacky  //   int foo::bar;
12125201361Srdivacky  assert(D->isOutOfLine());
12126194613Sed  EnterDeclaratorContext(S, D->getDeclContext());
12127234353Sdim
12128234353Sdim  // If we are parsing the initializer for a static data member, push a
12129234353Sdim  // new expression evaluation context that is associated with this static
12130234353Sdim  // data member.
12131234353Sdim  if (isStaticDataMember(D))
12132234353Sdim    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12133194613Sed}
12134194613Sed
12135194613Sed/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12136212904Sdim/// initializer for the out-of-line declaration 'D'.
12137212904Sdimvoid Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12138201361Srdivacky  // If there is no declaration, there was an error parsing it.
12139221345Sdim  if (D == 0 || D->isInvalidDecl()) return;
12140194613Sed
12141234353Sdim  if (isStaticDataMember(D))
12142234353Sdim    PopExpressionEvaluationContext();
12143234353Sdim
12144201361Srdivacky  assert(D->isOutOfLine());
12145194613Sed  ExitDeclaratorContext(S);
12146194613Sed}
12147199990Srdivacky
12148199990Srdivacky/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12149199990Srdivacky/// C++ if/switch/while/for statement.
12150199990Srdivacky/// e.g: "if (int x = f()) {...}"
12151212904SdimDeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12152199990Srdivacky  // C++ 6.4p2:
12153199990Srdivacky  // The declarator shall not specify a function or an array.
12154199990Srdivacky  // The type-specifier-seq shall not contain typedef and shall not declare a
12155199990Srdivacky  // new class or enumeration.
12156199990Srdivacky  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12157199990Srdivacky         "Parser allowed 'typedef' as storage class of condition decl.");
12158224145Sdim
12159212904Sdim  Decl *Dcl = ActOnDeclarator(S, D);
12160199990Srdivacky  if (!Dcl)
12161224145Sdim    return true;
12162199990Srdivacky
12163224145Sdim  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12164224145Sdim    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12165224145Sdim      << D.getSourceRange();
12166224145Sdim    return true;
12167224145Sdim  }
12168224145Sdim
12169199990Srdivacky  return Dcl;
12170199990Srdivacky}
12171200583Srdivacky
12172226633Sdimvoid Sema::LoadExternalVTableUses() {
12173226633Sdim  if (!ExternalSource)
12174226633Sdim    return;
12175226633Sdim
12176226633Sdim  SmallVector<ExternalVTableUse, 4> VTables;
12177226633Sdim  ExternalSource->ReadUsedVTables(VTables);
12178226633Sdim  SmallVector<VTableUse, 4> NewUses;
12179226633Sdim  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12180226633Sdim    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12181226633Sdim      = VTablesUsed.find(VTables[I].Record);
12182226633Sdim    // Even if a definition wasn't required before, it may be required now.
12183226633Sdim    if (Pos != VTablesUsed.end()) {
12184226633Sdim      if (!Pos->second && VTables[I].DefinitionRequired)
12185226633Sdim        Pos->second = true;
12186226633Sdim      continue;
12187226633Sdim    }
12188226633Sdim
12189226633Sdim    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12190226633Sdim    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12191226633Sdim  }
12192226633Sdim
12193226633Sdim  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12194226633Sdim}
12195226633Sdim
12196208600Srdivackyvoid Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12197208600Srdivacky                          bool DefinitionRequired) {
12198208600Srdivacky  // Ignore any vtable uses in unevaluated operands or for classes that do
12199208600Srdivacky  // not have a vtable.
12200208600Srdivacky  if (!Class->isDynamicClass() || Class->isDependentContext() ||
12201251662Sdim      CurContext->isDependentContext() || isUnevaluatedContext())
12202208600Srdivacky    return;
12203204643Srdivacky
12204208600Srdivacky  // Try to insert this class into the map.
12205226633Sdim  LoadExternalVTableUses();
12206208600Srdivacky  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12207208600Srdivacky  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12208208600Srdivacky    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12209208600Srdivacky  if (!Pos.second) {
12210208600Srdivacky    // If we already had an entry, check to see if we are promoting this vtable
12211208600Srdivacky    // to required a definition. If so, we need to reappend to the VTableUses
12212208600Srdivacky    // list, since we may have already processed the first entry.
12213208600Srdivacky    if (DefinitionRequired && !Pos.first->second) {
12214208600Srdivacky      Pos.first->second = true;
12215208600Srdivacky    } else {
12216208600Srdivacky      // Otherwise, we can early exit.
12217208600Srdivacky      return;
12218208600Srdivacky    }
12219208600Srdivacky  }
12220204643Srdivacky
12221208600Srdivacky  // Local classes need to have their virtual members marked
12222208600Srdivacky  // immediately. For all other classes, we mark their virtual members
12223208600Srdivacky  // at the end of the translation unit.
12224208600Srdivacky  if (Class->isLocalClass())
12225208600Srdivacky    MarkVirtualMembersReferenced(Loc, Class);
12226208600Srdivacky  else
12227208600Srdivacky    VTableUses.push_back(std::make_pair(Class, Loc));
12228208600Srdivacky}
12229204643Srdivacky
12230208600Srdivackybool Sema::DefineUsedVTables() {
12231226633Sdim  LoadExternalVTableUses();
12232208600Srdivacky  if (VTableUses.empty())
12233204643Srdivacky    return false;
12234218893Sdim
12235208600Srdivacky  // Note: The VTableUses vector could grow as a result of marking
12236208600Srdivacky  // the members of a class as "used", so we check the size each
12237239462Sdim  // time through the loop and prefer indices (which are stable) to
12238208600Srdivacky  // iterators (which are not).
12239221345Sdim  bool DefinedAnything = false;
12240208600Srdivacky  for (unsigned I = 0; I != VTableUses.size(); ++I) {
12241208600Srdivacky    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12242208600Srdivacky    if (!Class)
12243208600Srdivacky      continue;
12244204643Srdivacky
12245208600Srdivacky    SourceLocation Loc = VTableUses[I].second;
12246204643Srdivacky
12247239462Sdim    bool DefineVTable = true;
12248239462Sdim
12249208600Srdivacky    // If this class has a key function, but that key function is
12250208600Srdivacky    // defined in another translation unit, we don't need to emit the
12251208600Srdivacky    // vtable even though we're using it.
12252249423Sdim    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12253210299Sed    if (KeyFunction && !KeyFunction->hasBody()) {
12254263508Sdim      // The key function is in another translation unit.
12255263508Sdim      DefineVTable = false;
12256263508Sdim      TemplateSpecializationKind TSK =
12257263508Sdim          KeyFunction->getTemplateSpecializationKind();
12258263508Sdim      assert(TSK != TSK_ExplicitInstantiationDefinition &&
12259263508Sdim             TSK != TSK_ImplicitInstantiation &&
12260263508Sdim             "Instantiations don't have key functions");
12261263508Sdim      (void)TSK;
12262208600Srdivacky    } else if (!KeyFunction) {
12263208600Srdivacky      // If we have a class with no key function that is the subject
12264208600Srdivacky      // of an explicit instantiation declaration, suppress the
12265208600Srdivacky      // vtable; it will live with the explicit instantiation
12266208600Srdivacky      // definition.
12267208600Srdivacky      bool IsExplicitInstantiationDeclaration
12268208600Srdivacky        = Class->getTemplateSpecializationKind()
12269208600Srdivacky                                      == TSK_ExplicitInstantiationDeclaration;
12270208600Srdivacky      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12271208600Srdivacky                                 REnd = Class->redecls_end();
12272208600Srdivacky           R != REnd; ++R) {
12273208600Srdivacky        TemplateSpecializationKind TSK
12274208600Srdivacky          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12275208600Srdivacky        if (TSK == TSK_ExplicitInstantiationDeclaration)
12276208600Srdivacky          IsExplicitInstantiationDeclaration = true;
12277208600Srdivacky        else if (TSK == TSK_ExplicitInstantiationDefinition) {
12278208600Srdivacky          IsExplicitInstantiationDeclaration = false;
12279208600Srdivacky          break;
12280208600Srdivacky        }
12281208600Srdivacky      }
12282204643Srdivacky
12283208600Srdivacky      if (IsExplicitInstantiationDeclaration)
12284239462Sdim        DefineVTable = false;
12285208600Srdivacky    }
12286204643Srdivacky
12287239462Sdim    // The exception specifications for all virtual members may be needed even
12288239462Sdim    // if we are not providing an authoritative form of the vtable in this TU.
12289239462Sdim    // We may choose to emit it available_externally anyway.
12290239462Sdim    if (!DefineVTable) {
12291239462Sdim      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12292239462Sdim      continue;
12293239462Sdim    }
12294239462Sdim
12295208600Srdivacky    // Mark all of the virtual members of this class as referenced, so
12296208600Srdivacky    // that we can build a vtable. Then, tell the AST consumer that a
12297208600Srdivacky    // vtable for this class is required.
12298221345Sdim    DefinedAnything = true;
12299208600Srdivacky    MarkVirtualMembersReferenced(Loc, Class);
12300208600Srdivacky    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12301208600Srdivacky    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12302204643Srdivacky
12303208600Srdivacky    // Optionally warn if we're emitting a weak vtable.
12304263508Sdim    if (Class->isExternallyVisible() &&
12305208600Srdivacky        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12306226633Sdim      const FunctionDecl *KeyFunctionDef = 0;
12307226633Sdim      if (!KeyFunction ||
12308226633Sdim          (KeyFunction->hasBody(KeyFunctionDef) &&
12309226633Sdim           KeyFunctionDef->isInlined()))
12310234353Sdim        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12311234353Sdim             TSK_ExplicitInstantiationDefinition
12312234353Sdim             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12313234353Sdim          << Class;
12314208600Srdivacky    }
12315208600Srdivacky  }
12316208600Srdivacky  VTableUses.clear();
12317204962Srdivacky
12318221345Sdim  return DefinedAnything;
12319200583Srdivacky}
12320200583Srdivacky
12321239462Sdimvoid Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12322239462Sdim                                                 const CXXRecordDecl *RD) {
12323239462Sdim  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12324239462Sdim                                      E = RD->method_end(); I != E; ++I)
12325239462Sdim    if ((*I)->isVirtual() && !(*I)->isPure())
12326239462Sdim      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12327239462Sdim}
12328239462Sdim
12329206084Srdivackyvoid Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12330206084Srdivacky                                        const CXXRecordDecl *RD) {
12331238429Sdim  // Mark all functions which will appear in RD's vtable as used.
12332238429Sdim  CXXFinalOverriderMap FinalOverriders;
12333238429Sdim  RD->getFinalOverriders(FinalOverriders);
12334238429Sdim  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12335238429Sdim                                            E = FinalOverriders.end();
12336238429Sdim       I != E; ++I) {
12337238429Sdim    for (OverridingMethods::const_iterator OI = I->second.begin(),
12338238429Sdim                                           OE = I->second.end();
12339238429Sdim         OI != OE; ++OI) {
12340238429Sdim      assert(OI->second.size() > 0 && "no final overrider");
12341238429Sdim      CXXMethodDecl *Overrider = OI->second.front().Method;
12342200583Srdivacky
12343238429Sdim      // C++ [basic.def.odr]p2:
12344238429Sdim      //   [...] A virtual member function is used if it is not pure. [...]
12345238429Sdim      if (!Overrider->isPure())
12346238429Sdim        MarkFunctionReferenced(Loc, Overrider);
12347238429Sdim    }
12348200583Srdivacky  }
12349206084Srdivacky
12350206084Srdivacky  // Only classes that have virtual bases need a VTT.
12351206084Srdivacky  if (RD->getNumVBases() == 0)
12352206084Srdivacky    return;
12353206084Srdivacky
12354206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12355206084Srdivacky           e = RD->bases_end(); i != e; ++i) {
12356206084Srdivacky    const CXXRecordDecl *Base =
12357206084Srdivacky        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12358206084Srdivacky    if (Base->getNumVBases() == 0)
12359206084Srdivacky      continue;
12360206084Srdivacky    MarkVirtualMembersReferenced(Loc, Base);
12361206084Srdivacky  }
12362200583Srdivacky}
12363207619Srdivacky
12364207619Srdivacky/// SetIvarInitializers - This routine builds initialization ASTs for the
12365207619Srdivacky/// Objective-C implementation whose ivars need be initialized.
12366207619Srdivackyvoid Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12367234353Sdim  if (!getLangOpts().CPlusPlus)
12368207619Srdivacky    return;
12369212904Sdim  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12370226633Sdim    SmallVector<ObjCIvarDecl*, 8> ivars;
12371207619Srdivacky    CollectIvarsToConstructOrDestruct(OID, ivars);
12372207619Srdivacky    if (ivars.empty())
12373207619Srdivacky      return;
12374226633Sdim    SmallVector<CXXCtorInitializer*, 32> AllToInit;
12375207619Srdivacky    for (unsigned i = 0; i < ivars.size(); i++) {
12376207619Srdivacky      FieldDecl *Field = ivars[i];
12377208600Srdivacky      if (Field->isInvalidDecl())
12378208600Srdivacky        continue;
12379208600Srdivacky
12380218893Sdim      CXXCtorInitializer *Member;
12381207619Srdivacky      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12382207619Srdivacky      InitializationKind InitKind =
12383207619Srdivacky        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12384251662Sdim
12385251662Sdim      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12386251662Sdim      ExprResult MemberInit =
12387251662Sdim        InitSeq.Perform(*this, InitEntity, InitKind, None);
12388218893Sdim      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12389207619Srdivacky      // Note, MemberInit could actually come back empty if no initialization
12390207619Srdivacky      // is required (e.g., because it would call a trivial default constructor)
12391207619Srdivacky      if (!MemberInit.get() || MemberInit.isInvalid())
12392207619Srdivacky        continue;
12393218893Sdim
12394207619Srdivacky      Member =
12395218893Sdim        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12396218893Sdim                                         SourceLocation(),
12397218893Sdim                                         MemberInit.takeAs<Expr>(),
12398218893Sdim                                         SourceLocation());
12399207619Srdivacky      AllToInit.push_back(Member);
12400208600Srdivacky
12401208600Srdivacky      // Be sure that the destructor is accessible and is marked as referenced.
12402208600Srdivacky      if (const RecordType *RecordTy
12403208600Srdivacky                  = Context.getBaseElementType(Field->getType())
12404208600Srdivacky                                                        ->getAs<RecordType>()) {
12405208600Srdivacky                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12406210299Sed        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12407234353Sdim          MarkFunctionReferenced(Field->getLocation(), Destructor);
12408208600Srdivacky          CheckDestructorAccess(Field->getLocation(), Destructor,
12409208600Srdivacky                            PDiag(diag::err_access_dtor_ivar)
12410208600Srdivacky                              << Context.getBaseElementType(Field->getType()));
12411208600Srdivacky        }
12412208600Srdivacky      }
12413207619Srdivacky    }
12414207619Srdivacky    ObjCImplementation->setIvarInitializers(Context,
12415207619Srdivacky                                            AllToInit.data(), AllToInit.size());
12416207619Srdivacky  }
12417207619Srdivacky}
12418223017Sdim
12419223017Sdimstatic
12420223017Sdimvoid DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12421223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12422223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12423223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12424223017Sdim                           Sema &S) {
12425223017Sdim  if (Ctor->isInvalidDecl())
12426223017Sdim    return;
12427223017Sdim
12428243830Sdim  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12429223017Sdim
12430243830Sdim  // Target may not be determinable yet, for instance if this is a dependent
12431243830Sdim  // call in an uninstantiated template.
12432243830Sdim  if (Target) {
12433243830Sdim    const FunctionDecl *FNTarget = 0;
12434243830Sdim    (void)Target->hasBody(FNTarget);
12435243830Sdim    Target = const_cast<CXXConstructorDecl*>(
12436243830Sdim      cast_or_null<CXXConstructorDecl>(FNTarget));
12437243830Sdim  }
12438243830Sdim
12439223017Sdim  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12440223017Sdim                     // Avoid dereferencing a null pointer here.
12441223017Sdim                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12442223017Sdim
12443223017Sdim  if (!Current.insert(Canonical))
12444223017Sdim    return;
12445223017Sdim
12446223017Sdim  // We know that beyond here, we aren't chaining into a cycle.
12447223017Sdim  if (!Target || !Target->isDelegatingConstructor() ||
12448223017Sdim      Target->isInvalidDecl() || Valid.count(TCanonical)) {
12449263508Sdim    Valid.insert(Current.begin(), Current.end());
12450223017Sdim    Current.clear();
12451223017Sdim  // We've hit a cycle.
12452223017Sdim  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12453223017Sdim             Current.count(TCanonical)) {
12454223017Sdim    // If we haven't diagnosed this cycle yet, do so now.
12455223017Sdim    if (!Invalid.count(TCanonical)) {
12456223017Sdim      S.Diag((*Ctor->init_begin())->getSourceLocation(),
12457223017Sdim             diag::warn_delegating_ctor_cycle)
12458223017Sdim        << Ctor;
12459223017Sdim
12460243830Sdim      // Don't add a note for a function delegating directly to itself.
12461223017Sdim      if (TCanonical != Canonical)
12462223017Sdim        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12463223017Sdim
12464223017Sdim      CXXConstructorDecl *C = Target;
12465223017Sdim      while (C->getCanonicalDecl() != Canonical) {
12466243830Sdim        const FunctionDecl *FNTarget = 0;
12467223017Sdim        (void)C->getTargetConstructor()->hasBody(FNTarget);
12468223017Sdim        assert(FNTarget && "Ctor cycle through bodiless function");
12469223017Sdim
12470243830Sdim        C = const_cast<CXXConstructorDecl*>(
12471243830Sdim          cast<CXXConstructorDecl>(FNTarget));
12472223017Sdim        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12473223017Sdim      }
12474223017Sdim    }
12475223017Sdim
12476263508Sdim    Invalid.insert(Current.begin(), Current.end());
12477223017Sdim    Current.clear();
12478223017Sdim  } else {
12479223017Sdim    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12480223017Sdim  }
12481223017Sdim}
12482223017Sdim
12483223017Sdim
12484223017Sdimvoid Sema::CheckDelegatingCtorCycles() {
12485223017Sdim  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12486223017Sdim
12487226633Sdim  for (DelegatingCtorDeclsType::iterator
12488226633Sdim         I = DelegatingCtorDecls.begin(ExternalSource),
12489223017Sdim         E = DelegatingCtorDecls.end();
12490243830Sdim       I != E; ++I)
12491243830Sdim    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12492223017Sdim
12493263508Sdim  for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12494263508Sdim                                                         CE = Invalid.end();
12495263508Sdim       CI != CE; ++CI)
12496223017Sdim    (*CI)->setInvalidDecl();
12497223017Sdim}
12498226633Sdim
12499234982Sdimnamespace {
12500234982Sdim  /// \brief AST visitor that finds references to the 'this' expression.
12501234982Sdim  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12502234982Sdim    Sema &S;
12503234982Sdim
12504234982Sdim  public:
12505234982Sdim    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12506234982Sdim
12507234982Sdim    bool VisitCXXThisExpr(CXXThisExpr *E) {
12508234982Sdim      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12509234982Sdim        << E->isImplicit();
12510234982Sdim      return false;
12511234982Sdim    }
12512234982Sdim  };
12513234982Sdim}
12514234982Sdim
12515234982Sdimbool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12516234982Sdim  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12517234982Sdim  if (!TSInfo)
12518234982Sdim    return false;
12519234982Sdim
12520234982Sdim  TypeLoc TL = TSInfo->getTypeLoc();
12521249423Sdim  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12522234982Sdim  if (!ProtoTL)
12523234982Sdim    return false;
12524234982Sdim
12525234982Sdim  // C++11 [expr.prim.general]p3:
12526234982Sdim  //   [The expression this] shall not appear before the optional
12527234982Sdim  //   cv-qualifier-seq and it shall not appear within the declaration of a
12528234982Sdim  //   static member function (although its type and value category are defined
12529234982Sdim  //   within a static member function as they are within a non-static member
12530234982Sdim  //   function). [ Note: this is because declaration matching does not occur
12531234982Sdim  //  until the complete declarator is known. - end note ]
12532249423Sdim  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12533234982Sdim  FindCXXThisExpr Finder(*this);
12534234982Sdim
12535234982Sdim  // If the return type came after the cv-qualifier-seq, check it now.
12536234982Sdim  if (Proto->hasTrailingReturn() &&
12537249423Sdim      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12538234982Sdim    return true;
12539234982Sdim
12540234982Sdim  // Check the exception specification.
12541234982Sdim  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12542234982Sdim    return true;
12543234982Sdim
12544234982Sdim  return checkThisInStaticMemberFunctionAttributes(Method);
12545234982Sdim}
12546234982Sdim
12547234982Sdimbool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12548234982Sdim  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12549234982Sdim  if (!TSInfo)
12550234982Sdim    return false;
12551234982Sdim
12552234982Sdim  TypeLoc TL = TSInfo->getTypeLoc();
12553249423Sdim  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12554234982Sdim  if (!ProtoTL)
12555234982Sdim    return false;
12556234982Sdim
12557249423Sdim  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12558234982Sdim  FindCXXThisExpr Finder(*this);
12559234982Sdim
12560234982Sdim  switch (Proto->getExceptionSpecType()) {
12561234982Sdim  case EST_Uninstantiated:
12562239462Sdim  case EST_Unevaluated:
12563234982Sdim  case EST_BasicNoexcept:
12564234982Sdim  case EST_DynamicNone:
12565234982Sdim  case EST_MSAny:
12566234982Sdim  case EST_None:
12567234982Sdim    break;
12568234982Sdim
12569234982Sdim  case EST_ComputedNoexcept:
12570234982Sdim    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12571234982Sdim      return true;
12572234982Sdim
12573234982Sdim  case EST_Dynamic:
12574234982Sdim    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12575234982Sdim         EEnd = Proto->exception_end();
12576234982Sdim         E != EEnd; ++E) {
12577234982Sdim      if (!Finder.TraverseType(*E))
12578234982Sdim        return true;
12579234982Sdim    }
12580234982Sdim    break;
12581234982Sdim  }
12582234982Sdim
12583234982Sdim  return false;
12584234982Sdim}
12585234982Sdim
12586234982Sdimbool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12587234982Sdim  FindCXXThisExpr Finder(*this);
12588234982Sdim
12589234982Sdim  // Check attributes.
12590234982Sdim  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12591234982Sdim       A != AEnd; ++A) {
12592234982Sdim    // FIXME: This should be emitted by tblgen.
12593234982Sdim    Expr *Arg = 0;
12594234982Sdim    ArrayRef<Expr *> Args;
12595234982Sdim    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12596234982Sdim      Arg = G->getArg();
12597234982Sdim    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12598234982Sdim      Arg = G->getArg();
12599234982Sdim    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12600234982Sdim      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12601234982Sdim    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12602234982Sdim      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12603234982Sdim    else if (ExclusiveLockFunctionAttr *ELF
12604234982Sdim               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12605234982Sdim      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12606234982Sdim    else if (SharedLockFunctionAttr *SLF
12607234982Sdim               = dyn_cast<SharedLockFunctionAttr>(*A))
12608234982Sdim      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12609234982Sdim    else if (ExclusiveTrylockFunctionAttr *ETLF
12610234982Sdim               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12611234982Sdim      Arg = ETLF->getSuccessValue();
12612234982Sdim      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12613234982Sdim    } else if (SharedTrylockFunctionAttr *STLF
12614234982Sdim                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12615234982Sdim      Arg = STLF->getSuccessValue();
12616234982Sdim      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12617234982Sdim    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12618234982Sdim      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12619234982Sdim    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12620234982Sdim      Arg = LR->getArg();
12621234982Sdim    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12622234982Sdim      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12623234982Sdim    else if (ExclusiveLocksRequiredAttr *ELR
12624234982Sdim               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12625234982Sdim      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12626234982Sdim    else if (SharedLocksRequiredAttr *SLR
12627234982Sdim               = dyn_cast<SharedLocksRequiredAttr>(*A))
12628234982Sdim      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12629234982Sdim
12630234982Sdim    if (Arg && !Finder.TraverseStmt(Arg))
12631234982Sdim      return true;
12632234982Sdim
12633234982Sdim    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12634234982Sdim      if (!Finder.TraverseStmt(Args[I]))
12635234982Sdim        return true;
12636234982Sdim    }
12637234982Sdim  }
12638234982Sdim
12639234982Sdim  return false;
12640234982Sdim}
12641234982Sdim
12642234982Sdimvoid
12643234982SdimSema::checkExceptionSpecification(ExceptionSpecificationType EST,
12644234982Sdim                                  ArrayRef<ParsedType> DynamicExceptions,
12645234982Sdim                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12646234982Sdim                                  Expr *NoexceptExpr,
12647249423Sdim                                  SmallVectorImpl<QualType> &Exceptions,
12648234982Sdim                                  FunctionProtoType::ExtProtoInfo &EPI) {
12649234982Sdim  Exceptions.clear();
12650234982Sdim  EPI.ExceptionSpecType = EST;
12651234982Sdim  if (EST == EST_Dynamic) {
12652234982Sdim    Exceptions.reserve(DynamicExceptions.size());
12653234982Sdim    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12654234982Sdim      // FIXME: Preserve type source info.
12655234982Sdim      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12656234982Sdim
12657234982Sdim      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12658234982Sdim      collectUnexpandedParameterPacks(ET, Unexpanded);
12659234982Sdim      if (!Unexpanded.empty()) {
12660234982Sdim        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12661234982Sdim                                         UPPC_ExceptionType,
12662234982Sdim                                         Unexpanded);
12663234982Sdim        continue;
12664234982Sdim      }
12665234982Sdim
12666234982Sdim      // Check that the type is valid for an exception spec, and
12667234982Sdim      // drop it if not.
12668234982Sdim      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12669234982Sdim        Exceptions.push_back(ET);
12670234982Sdim    }
12671234982Sdim    EPI.NumExceptions = Exceptions.size();
12672234982Sdim    EPI.Exceptions = Exceptions.data();
12673234982Sdim    return;
12674234982Sdim  }
12675234982Sdim
12676234982Sdim  if (EST == EST_ComputedNoexcept) {
12677234982Sdim    // If an error occurred, there's no expression here.
12678234982Sdim    if (NoexceptExpr) {
12679234982Sdim      assert((NoexceptExpr->isTypeDependent() ||
12680234982Sdim              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12681234982Sdim              Context.BoolTy) &&
12682234982Sdim             "Parser should have made sure that the expression is boolean");
12683234982Sdim      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12684234982Sdim        EPI.ExceptionSpecType = EST_BasicNoexcept;
12685234982Sdim        return;
12686234982Sdim      }
12687234982Sdim
12688234982Sdim      if (!NoexceptExpr->isValueDependent())
12689234982Sdim        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12690239462Sdim                         diag::err_noexcept_needs_constant_expression,
12691234982Sdim                         /*AllowFold*/ false).take();
12692234982Sdim      EPI.NoexceptExpr = NoexceptExpr;
12693234982Sdim    }
12694234982Sdim    return;
12695234982Sdim  }
12696234982Sdim}
12697234982Sdim
12698226633Sdim/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12699226633SdimSema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12700226633Sdim  // Implicitly declared functions (e.g. copy constructors) are
12701226633Sdim  // __host__ __device__
12702226633Sdim  if (D->isImplicit())
12703226633Sdim    return CFT_HostDevice;
12704226633Sdim
12705226633Sdim  if (D->hasAttr<CUDAGlobalAttr>())
12706226633Sdim    return CFT_Global;
12707226633Sdim
12708226633Sdim  if (D->hasAttr<CUDADeviceAttr>()) {
12709226633Sdim    if (D->hasAttr<CUDAHostAttr>())
12710226633Sdim      return CFT_HostDevice;
12711263508Sdim    return CFT_Device;
12712226633Sdim  }
12713226633Sdim
12714226633Sdim  return CFT_Host;
12715226633Sdim}
12716226633Sdim
12717226633Sdimbool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12718226633Sdim                           CUDAFunctionTarget CalleeTarget) {
12719226633Sdim  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12720226633Sdim  // Callable from the device only."
12721226633Sdim  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12722226633Sdim    return true;
12723226633Sdim
12724226633Sdim  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12725226633Sdim  // Callable from the host only."
12726226633Sdim  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12727226633Sdim  // Callable from the host only."
12728226633Sdim  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12729226633Sdim      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12730226633Sdim    return true;
12731226633Sdim
12732226633Sdim  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12733226633Sdim    return true;
12734226633Sdim
12735226633Sdim  return false;
12736226633Sdim}
12737251662Sdim
12738251662Sdim/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12739251662Sdim///
12740251662SdimMSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12741251662Sdim                                       SourceLocation DeclStart,
12742251662Sdim                                       Declarator &D, Expr *BitWidth,
12743251662Sdim                                       InClassInitStyle InitStyle,
12744251662Sdim                                       AccessSpecifier AS,
12745251662Sdim                                       AttributeList *MSPropertyAttr) {
12746251662Sdim  IdentifierInfo *II = D.getIdentifier();
12747251662Sdim  if (!II) {
12748251662Sdim    Diag(DeclStart, diag::err_anonymous_property);
12749251662Sdim    return NULL;
12750251662Sdim  }
12751251662Sdim  SourceLocation Loc = D.getIdentifierLoc();
12752251662Sdim
12753251662Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12754251662Sdim  QualType T = TInfo->getType();
12755251662Sdim  if (getLangOpts().CPlusPlus) {
12756251662Sdim    CheckExtraCXXDefaultArguments(D);
12757251662Sdim
12758251662Sdim    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12759251662Sdim                                        UPPC_DataMemberType)) {
12760251662Sdim      D.setInvalidType();
12761251662Sdim      T = Context.IntTy;
12762251662Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12763251662Sdim    }
12764251662Sdim  }
12765251662Sdim
12766251662Sdim  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12767251662Sdim
12768251662Sdim  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12769251662Sdim    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12770251662Sdim         diag::err_invalid_thread)
12771251662Sdim      << DeclSpec::getSpecifierName(TSCS);
12772251662Sdim
12773251662Sdim  // Check to see if this name was declared as a member previously
12774251662Sdim  NamedDecl *PrevDecl = 0;
12775251662Sdim  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12776251662Sdim  LookupName(Previous, S);
12777251662Sdim  switch (Previous.getResultKind()) {
12778251662Sdim  case LookupResult::Found:
12779251662Sdim  case LookupResult::FoundUnresolvedValue:
12780251662Sdim    PrevDecl = Previous.getAsSingle<NamedDecl>();
12781251662Sdim    break;
12782251662Sdim
12783251662Sdim  case LookupResult::FoundOverloaded:
12784251662Sdim    PrevDecl = Previous.getRepresentativeDecl();
12785251662Sdim    break;
12786251662Sdim
12787251662Sdim  case LookupResult::NotFound:
12788251662Sdim  case LookupResult::NotFoundInCurrentInstantiation:
12789251662Sdim  case LookupResult::Ambiguous:
12790251662Sdim    break;
12791251662Sdim  }
12792251662Sdim
12793251662Sdim  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12794251662Sdim    // Maybe we will complain about the shadowed template parameter.
12795251662Sdim    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12796251662Sdim    // Just pretend that we didn't see the previous declaration.
12797251662Sdim    PrevDecl = 0;
12798251662Sdim  }
12799251662Sdim
12800251662Sdim  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12801251662Sdim    PrevDecl = 0;
12802251662Sdim
12803251662Sdim  SourceLocation TSSL = D.getLocStart();
12804251662Sdim  MSPropertyDecl *NewPD;
12805251662Sdim  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12806251662Sdim  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12807251662Sdim                                       II, T, TInfo, TSSL,
12808251662Sdim                                       Data.GetterId, Data.SetterId);
12809251662Sdim  ProcessDeclAttributes(TUScope, NewPD, D);
12810251662Sdim  NewPD->setAccess(AS);
12811251662Sdim
12812251662Sdim  if (NewPD->isInvalidDecl())
12813251662Sdim    Record->setInvalidDecl();
12814251662Sdim
12815251662Sdim  if (D.getDeclSpec().isModulePrivateSpecified())
12816251662Sdim    NewPD->setModulePrivate();
12817251662Sdim
12818251662Sdim  if (NewPD->isInvalidDecl() && PrevDecl) {
12819251662Sdim    // Don't introduce NewFD into scope; there's already something
12820251662Sdim    // with the same name in the same scope.
12821251662Sdim  } else if (II) {
12822251662Sdim    PushOnScopeChains(NewPD, S);
12823251662Sdim  } else
12824251662Sdim    Record->addDecl(NewPD);
12825251662Sdim
12826251662Sdim  return NewPD;
12827251662Sdim}
12828