SemaDeclCXX.cpp revision 223017
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"
15212904Sdim#include "clang/Sema/CXXFieldCollector.h"
16212904Sdim#include "clang/Sema/Scope.h"
17212904Sdim#include "clang/Sema/Initialization.h"
18212904Sdim#include "clang/Sema/Lookup.h"
19193326Sed#include "clang/AST/ASTConsumer.h"
20193326Sed#include "clang/AST/ASTContext.h"
21221345Sdim#include "clang/AST/ASTMutationListener.h"
22207619Srdivacky#include "clang/AST/CharUnits.h"
23198092Srdivacky#include "clang/AST/CXXInheritance.h"
24193326Sed#include "clang/AST/DeclVisitor.h"
25221345Sdim#include "clang/AST/ExprCXX.h"
26207619Srdivacky#include "clang/AST/RecordLayout.h"
27207619Srdivacky#include "clang/AST/StmtVisitor.h"
28200583Srdivacky#include "clang/AST/TypeLoc.h"
29193326Sed#include "clang/AST/TypeOrdering.h"
30212904Sdim#include "clang/Sema/DeclSpec.h"
31212904Sdim#include "clang/Sema/ParsedTemplate.h"
32198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
33193326Sed#include "clang/Lex/Preprocessor.h"
34212904Sdim#include "llvm/ADT/DenseSet.h"
35193326Sed#include "llvm/ADT/STLExtras.h"
36193326Sed#include <map>
37198092Srdivacky#include <set>
38193326Sed
39193326Sedusing namespace clang;
40193326Sed
41193326Sed//===----------------------------------------------------------------------===//
42193326Sed// CheckDefaultArgumentVisitor
43193326Sed//===----------------------------------------------------------------------===//
44193326Sed
45193326Sednamespace {
46193326Sed  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47193326Sed  /// the default argument of a parameter to determine whether it
48193326Sed  /// contains any ill-formed subexpressions. For example, this will
49193326Sed  /// diagnose the use of local variables or parameters within the
50193326Sed  /// default argument expression.
51199990Srdivacky  class CheckDefaultArgumentVisitor
52193326Sed    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53193326Sed    Expr *DefaultArg;
54193326Sed    Sema *S;
55193326Sed
56193326Sed  public:
57198092Srdivacky    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58193326Sed      : DefaultArg(defarg), S(s) {}
59193326Sed
60193326Sed    bool VisitExpr(Expr *Node);
61193326Sed    bool VisitDeclRefExpr(DeclRefExpr *DRE);
62193326Sed    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63193326Sed  };
64193326Sed
65193326Sed  /// VisitExpr - Visit all of the children of this expression.
66193326Sed  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67193326Sed    bool IsInvalid = false;
68218893Sdim    for (Stmt::child_range I = Node->children(); I; ++I)
69193326Sed      IsInvalid |= Visit(*I);
70193326Sed    return IsInvalid;
71193326Sed  }
72193326Sed
73193326Sed  /// VisitDeclRefExpr - Visit a reference to a declaration, to
74193326Sed  /// determine whether this declaration can be used in the default
75193326Sed  /// argument expression.
76193326Sed  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77193326Sed    NamedDecl *Decl = DRE->getDecl();
78193326Sed    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79193326Sed      // C++ [dcl.fct.default]p9
80193326Sed      //   Default arguments are evaluated each time the function is
81193326Sed      //   called. The order of evaluation of function arguments is
82193326Sed      //   unspecified. Consequently, parameters of a function shall not
83193326Sed      //   be used in default argument expressions, even if they are not
84193326Sed      //   evaluated. Parameters of a function declared before a default
85193326Sed      //   argument expression are in scope and can hide namespace and
86193326Sed      //   class member names.
87198092Srdivacky      return S->Diag(DRE->getSourceRange().getBegin(),
88193326Sed                     diag::err_param_default_argument_references_param)
89193326Sed         << Param->getDeclName() << DefaultArg->getSourceRange();
90193326Sed    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91193326Sed      // C++ [dcl.fct.default]p7
92193326Sed      //   Local variables shall not be used in default argument
93193326Sed      //   expressions.
94218893Sdim      if (VDecl->isLocalVarDecl())
95198092Srdivacky        return S->Diag(DRE->getSourceRange().getBegin(),
96193326Sed                       diag::err_param_default_argument_references_local)
97193326Sed          << VDecl->getDeclName() << DefaultArg->getSourceRange();
98193326Sed    }
99193326Sed
100193326Sed    return false;
101193326Sed  }
102193326Sed
103193326Sed  /// VisitCXXThisExpr - Visit a C++ "this" expression.
104193326Sed  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105193326Sed    // C++ [dcl.fct.default]p8:
106193326Sed    //   The keyword this shall not be used in a default argument of a
107193326Sed    //   member function.
108193326Sed    return S->Diag(ThisE->getSourceRange().getBegin(),
109193326Sed                   diag::err_param_default_argument_references_this)
110193326Sed               << ThisE->getSourceRange();
111193326Sed  }
112193326Sed}
113193326Sed
114223017Sdimvoid Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115223017Sdim  assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116223017Sdim  // If we have an MSAny or unknown spec already, don't bother.
117223017Sdim  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
118223017Sdim    return;
119223017Sdim
120223017Sdim  const FunctionProtoType *Proto
121223017Sdim    = Method->getType()->getAs<FunctionProtoType>();
122223017Sdim
123223017Sdim  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124223017Sdim
125223017Sdim  // If this function can throw any exceptions, make a note of that.
126223017Sdim  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
127223017Sdim    ClearExceptions();
128223017Sdim    ComputedEST = EST;
129223017Sdim    return;
130223017Sdim  }
131223017Sdim
132223017Sdim  // FIXME: If the call to this decl is using any of its default arguments, we
133223017Sdim  // need to search them for potentially-throwing calls.
134223017Sdim
135223017Sdim  // If this function has a basic noexcept, it doesn't affect the outcome.
136223017Sdim  if (EST == EST_BasicNoexcept)
137223017Sdim    return;
138223017Sdim
139223017Sdim  // If we have a throw-all spec at this point, ignore the function.
140223017Sdim  if (ComputedEST == EST_None)
141223017Sdim    return;
142223017Sdim
143223017Sdim  // If we're still at noexcept(true) and there's a nothrow() callee,
144223017Sdim  // change to that specification.
145223017Sdim  if (EST == EST_DynamicNone) {
146223017Sdim    if (ComputedEST == EST_BasicNoexcept)
147223017Sdim      ComputedEST = EST_DynamicNone;
148223017Sdim    return;
149223017Sdim  }
150223017Sdim
151223017Sdim  // Check out noexcept specs.
152223017Sdim  if (EST == EST_ComputedNoexcept) {
153223017Sdim    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154223017Sdim    assert(NR != FunctionProtoType::NR_NoNoexcept &&
155223017Sdim           "Must have noexcept result for EST_ComputedNoexcept.");
156223017Sdim    assert(NR != FunctionProtoType::NR_Dependent &&
157223017Sdim           "Should not generate implicit declarations for dependent cases, "
158223017Sdim           "and don't know how to handle them anyway.");
159223017Sdim
160223017Sdim    // noexcept(false) -> no spec on the new function
161223017Sdim    if (NR == FunctionProtoType::NR_Throw) {
162223017Sdim      ClearExceptions();
163223017Sdim      ComputedEST = EST_None;
164223017Sdim    }
165223017Sdim    // noexcept(true) won't change anything either.
166223017Sdim    return;
167223017Sdim  }
168223017Sdim
169223017Sdim  assert(EST == EST_Dynamic && "EST case not considered earlier.");
170223017Sdim  assert(ComputedEST != EST_None &&
171223017Sdim         "Shouldn't collect exceptions when throw-all is guaranteed.");
172223017Sdim  ComputedEST = EST_Dynamic;
173223017Sdim  // Record the exceptions in this function's exception specification.
174223017Sdim  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175223017Sdim                                          EEnd = Proto->exception_end();
176223017Sdim       E != EEnd; ++E)
177223017Sdim    if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178223017Sdim      Exceptions.push_back(*E);
179223017Sdim}
180223017Sdim
181223017Sdimvoid Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182223017Sdim  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183223017Sdim    return;
184223017Sdim
185223017Sdim  // FIXME:
186223017Sdim  //
187223017Sdim  // C++0x [except.spec]p14:
188223017Sdim  //   [An] implicit exception-speci���cation speci���es the type-id T if and
189223017Sdim  // only if T is allowed by the exception-speci���cation of a function directly
190223017Sdim  // invoked by f���s implicit de���nition; f shall allow all exceptions if any
191223017Sdim  // function it directly invokes allows all exceptions, and f shall allow no
192223017Sdim  // exceptions if every function it directly invokes allows no exceptions.
193223017Sdim  //
194223017Sdim  // Note in particular that if an implicit exception-specification is generated
195223017Sdim  // for a function containing a throw-expression, that specification can still
196223017Sdim  // be noexcept(true).
197223017Sdim  //
198223017Sdim  // Note also that 'directly invoked' is not defined in the standard, and there
199223017Sdim  // is no indication that we should only consider potentially-evaluated calls.
200223017Sdim  //
201223017Sdim  // Ultimately we should implement the intent of the standard: the exception
202223017Sdim  // specification should be the set of exceptions which can be thrown by the
203223017Sdim  // implicit definition. For now, we assume that any non-nothrow expression can
204223017Sdim  // throw any exception.
205223017Sdim
206223017Sdim  if (E->CanThrow(*Context))
207223017Sdim    ComputedEST = EST_None;
208223017Sdim}
209223017Sdim
210198092Srdivackybool
211212904SdimSema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212198092Srdivacky                              SourceLocation EqualLoc) {
213198092Srdivacky  if (RequireCompleteType(Param->getLocation(), Param->getType(),
214198092Srdivacky                          diag::err_typecheck_decl_incomplete_type)) {
215198092Srdivacky    Param->setInvalidDecl();
216198092Srdivacky    return true;
217198092Srdivacky  }
218198092Srdivacky
219198092Srdivacky  // C++ [dcl.fct.default]p5
220198092Srdivacky  //   A default argument expression is implicitly converted (clause
221198092Srdivacky  //   4) to the parameter type. The default argument expression has
222198092Srdivacky  //   the same semantic constraints as the initializer expression in
223198092Srdivacky  //   a declaration of a variable of the parameter type, using the
224198092Srdivacky  //   copy-initialization semantics (8.5).
225218893Sdim  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226218893Sdim                                                                    Param);
227201361Srdivacky  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228201361Srdivacky                                                           EqualLoc);
229201361Srdivacky  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230212904Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231218893Sdim                                      MultiExprArg(*this, &Arg, 1));
232201361Srdivacky  if (Result.isInvalid())
233198092Srdivacky    return true;
234201361Srdivacky  Arg = Result.takeAs<Expr>();
235198092Srdivacky
236218893Sdim  CheckImplicitConversions(Arg, EqualLoc);
237218893Sdim  Arg = MaybeCreateExprWithCleanups(Arg);
238198092Srdivacky
239198092Srdivacky  // Okay: add the default argument to the parameter
240198092Srdivacky  Param->setDefaultArg(Arg);
241198092Srdivacky
242218893Sdim  // We have already instantiated this parameter; provide each of the
243218893Sdim  // instantiations with the uninstantiated default argument.
244218893Sdim  UnparsedDefaultArgInstantiationsMap::iterator InstPos
245218893Sdim    = UnparsedDefaultArgInstantiations.find(Param);
246218893Sdim  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247218893Sdim    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248218893Sdim      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249218893Sdim
250218893Sdim    // We're done tracking this parameter's instantiations.
251218893Sdim    UnparsedDefaultArgInstantiations.erase(InstPos);
252218893Sdim  }
253218893Sdim
254198092Srdivacky  return false;
255198092Srdivacky}
256198092Srdivacky
257193326Sed/// ActOnParamDefaultArgument - Check whether the default argument
258193326Sed/// provided for a function parameter is well-formed. If so, attach it
259193326Sed/// to the parameter declaration.
260193326Sedvoid
261212904SdimSema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
262212904Sdim                                Expr *DefaultArg) {
263212904Sdim  if (!param || !DefaultArg)
264194711Sed    return;
265198092Srdivacky
266212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
267194179Sed  UnparsedDefaultArgLocs.erase(Param);
268194179Sed
269193326Sed  // Default arguments are only permitted in C++
270193326Sed  if (!getLangOptions().CPlusPlus) {
271193326Sed    Diag(EqualLoc, diag::err_param_default_argument)
272193326Sed      << DefaultArg->getSourceRange();
273193326Sed    Param->setInvalidDecl();
274193326Sed    return;
275193326Sed  }
276193326Sed
277218893Sdim  // Check for unexpanded parameter packs.
278218893Sdim  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279218893Sdim    Param->setInvalidDecl();
280218893Sdim    return;
281218893Sdim  }
282218893Sdim
283193326Sed  // Check that the default argument is well-formed
284212904Sdim  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285212904Sdim  if (DefaultArgChecker.Visit(DefaultArg)) {
286193326Sed    Param->setInvalidDecl();
287193326Sed    return;
288193326Sed  }
289193326Sed
290212904Sdim  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
291193326Sed}
292193326Sed
293193326Sed/// ActOnParamUnparsedDefaultArgument - We've seen a default
294193326Sed/// argument for a function parameter, but we can't parse it yet
295193326Sed/// because we're inside a class definition. Note that this default
296193326Sed/// argument will be parsed later.
297212904Sdimvoid Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298194179Sed                                             SourceLocation EqualLoc,
299194179Sed                                             SourceLocation ArgLoc) {
300194711Sed  if (!param)
301194711Sed    return;
302198092Srdivacky
303212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
304193326Sed  if (Param)
305193326Sed    Param->setUnparsedDefaultArg();
306198092Srdivacky
307194179Sed  UnparsedDefaultArgLocs[Param] = ArgLoc;
308193326Sed}
309193326Sed
310193326Sed/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311193326Sed/// the default argument for the parameter param failed.
312212904Sdimvoid Sema::ActOnParamDefaultArgumentError(Decl *param) {
313194711Sed  if (!param)
314194711Sed    return;
315198092Srdivacky
316212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(param);
317198092Srdivacky
318194179Sed  Param->setInvalidDecl();
319198092Srdivacky
320194179Sed  UnparsedDefaultArgLocs.erase(Param);
321193326Sed}
322193326Sed
323193326Sed/// CheckExtraCXXDefaultArguments - Check for any extra default
324193326Sed/// arguments in the declarator, which is not a function declaration
325193326Sed/// or definition and therefore is not permitted to have default
326193326Sed/// arguments. This routine should be invoked for every declarator
327193326Sed/// that is not a function declaration or definition.
328193326Sedvoid Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329193326Sed  // C++ [dcl.fct.default]p3
330193326Sed  //   A default argument expression shall be specified only in the
331193326Sed  //   parameter-declaration-clause of a function declaration or in a
332193326Sed  //   template-parameter (14.1). It shall not be specified for a
333193326Sed  //   parameter pack. If it is specified in a
334193326Sed  //   parameter-declaration-clause, it shall not occur within a
335193326Sed  //   declarator or abstract-declarator of a parameter-declaration.
336193326Sed  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337193326Sed    DeclaratorChunk &chunk = D.getTypeObject(i);
338193326Sed    if (chunk.Kind == DeclaratorChunk::Function) {
339193326Sed      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340193326Sed        ParmVarDecl *Param =
341212904Sdim          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342193326Sed        if (Param->hasUnparsedDefaultArg()) {
343193326Sed          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345193326Sed            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346193326Sed          delete Toks;
347193326Sed          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348193326Sed        } else if (Param->getDefaultArg()) {
349193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350193326Sed            << Param->getDefaultArg()->getSourceRange();
351193326Sed          Param->setDefaultArg(0);
352193326Sed        }
353193326Sed      }
354193326Sed    }
355193326Sed  }
356193326Sed}
357193326Sed
358193326Sed// MergeCXXFunctionDecl - Merge two declarations of the same C++
359193326Sed// function, once we already know that they have the same
360193326Sed// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361193326Sed// error, false otherwise.
362193326Sedbool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363193326Sed  bool Invalid = false;
364193326Sed
365193326Sed  // C++ [dcl.fct.default]p4:
366193326Sed  //   For non-template functions, default arguments can be added in
367193326Sed  //   later declarations of a function in the same
368193326Sed  //   scope. Declarations in different scopes have completely
369193326Sed  //   distinct sets of default arguments. That is, declarations in
370193326Sed  //   inner scopes do not acquire default arguments from
371193326Sed  //   declarations in outer scopes, and vice versa. In a given
372193326Sed  //   function declaration, all parameters subsequent to a
373193326Sed  //   parameter with a default argument shall have default
374193326Sed  //   arguments supplied in this or previous declarations. A
375193326Sed  //   default argument shall not be redefined by a later
376193326Sed  //   declaration (not even to the same value).
377198092Srdivacky  //
378198092Srdivacky  // C++ [dcl.fct.default]p6:
379198092Srdivacky  //   Except for member functions of class templates, the default arguments
380198092Srdivacky  //   in a member function definition that appears outside of the class
381198092Srdivacky  //   definition are added to the set of default arguments provided by the
382198092Srdivacky  //   member function declaration in the class definition.
383193326Sed  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384193326Sed    ParmVarDecl *OldParam = Old->getParamDecl(p);
385193326Sed    ParmVarDecl *NewParam = New->getParamDecl(p);
386193326Sed
387198092Srdivacky    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
388221345Sdim
389221345Sdim      unsigned DiagDefaultParamID =
390221345Sdim        diag::err_param_default_argument_redefinition;
391221345Sdim
392221345Sdim      // MSVC accepts that default parameters be redefined for member functions
393221345Sdim      // of template class. The new default parameter's value is ignored.
394221345Sdim      Invalid = true;
395221345Sdim      if (getLangOptions().Microsoft) {
396221345Sdim        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397221345Sdim        if (MD && MD->getParent()->getDescribedClassTemplate()) {
398221345Sdim          // Merge the old default argument into the new parameter.
399221345Sdim          NewParam->setHasInheritedDefaultArg();
400221345Sdim          if (OldParam->hasUninstantiatedDefaultArg())
401221345Sdim            NewParam->setUninstantiatedDefaultArg(
402221345Sdim                                      OldParam->getUninstantiatedDefaultArg());
403221345Sdim          else
404221345Sdim            NewParam->setDefaultArg(OldParam->getInit());
405221345Sdim          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
406221345Sdim          Invalid = false;
407221345Sdim        }
408221345Sdim      }
409221345Sdim
410202379Srdivacky      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411202379Srdivacky      // hint here. Alternatively, we could walk the type-source information
412202379Srdivacky      // for NewParam to find the last source location in the type... but it
413202379Srdivacky      // isn't worth the effort right now. This is the kind of test case that
414202379Srdivacky      // is hard to get right:
415202379Srdivacky      //   int f(int);
416202379Srdivacky      //   void g(int (*fp)(int) = f);
417202379Srdivacky      //   void g(int (*fp)(int) = &f);
418221345Sdim      Diag(NewParam->getLocation(), DiagDefaultParamID)
419202379Srdivacky        << NewParam->getDefaultArgRange();
420198092Srdivacky
421198092Srdivacky      // Look for the function declaration where the default argument was
422198092Srdivacky      // actually written, which may be a declaration prior to Old.
423198092Srdivacky      for (FunctionDecl *Older = Old->getPreviousDeclaration();
424198092Srdivacky           Older; Older = Older->getPreviousDeclaration()) {
425198092Srdivacky        if (!Older->getParamDecl(p)->hasDefaultArg())
426198092Srdivacky          break;
427198092Srdivacky
428198092Srdivacky        OldParam = Older->getParamDecl(p);
429198092Srdivacky      }
430198092Srdivacky
431198092Srdivacky      Diag(OldParam->getLocation(), diag::note_previous_definition)
432198092Srdivacky        << OldParam->getDefaultArgRange();
433198092Srdivacky    } else if (OldParam->hasDefaultArg()) {
434207619Srdivacky      // Merge the old default argument into the new parameter.
435207619Srdivacky      // It's important to use getInit() here;  getDefaultArg()
436218893Sdim      // strips off any top-level ExprWithCleanups.
437205219Srdivacky      NewParam->setHasInheritedDefaultArg();
438198092Srdivacky      if (OldParam->hasUninstantiatedDefaultArg())
439198092Srdivacky        NewParam->setUninstantiatedDefaultArg(
440198092Srdivacky                                      OldParam->getUninstantiatedDefaultArg());
441198092Srdivacky      else
442207619Srdivacky        NewParam->setDefaultArg(OldParam->getInit());
443198092Srdivacky    } else if (NewParam->hasDefaultArg()) {
444198092Srdivacky      if (New->getDescribedFunctionTemplate()) {
445198092Srdivacky        // Paragraph 4, quoted above, only applies to non-template functions.
446198092Srdivacky        Diag(NewParam->getLocation(),
447198092Srdivacky             diag::err_param_default_argument_template_redecl)
448198092Srdivacky          << NewParam->getDefaultArgRange();
449198092Srdivacky        Diag(Old->getLocation(), diag::note_template_prev_declaration)
450198092Srdivacky          << false;
451198092Srdivacky      } else if (New->getTemplateSpecializationKind()
452198092Srdivacky                   != TSK_ImplicitInstantiation &&
453198092Srdivacky                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454198092Srdivacky        // C++ [temp.expr.spec]p21:
455198092Srdivacky        //   Default function arguments shall not be specified in a declaration
456198092Srdivacky        //   or a definition for one of the following explicit specializations:
457198092Srdivacky        //     - the explicit specialization of a function template;
458198092Srdivacky        //     - the explicit specialization of a member function template;
459198092Srdivacky        //     - the explicit specialization of a member function of a class
460198092Srdivacky        //       template where the class template specialization to which the
461198092Srdivacky        //       member function specialization belongs is implicitly
462198092Srdivacky        //       instantiated.
463198092Srdivacky        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464198092Srdivacky          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465198092Srdivacky          << New->getDeclName()
466198092Srdivacky          << NewParam->getDefaultArgRange();
467198092Srdivacky      } else if (New->getDeclContext()->isDependentContext()) {
468198092Srdivacky        // C++ [dcl.fct.default]p6 (DR217):
469198092Srdivacky        //   Default arguments for a member function of a class template shall
470198092Srdivacky        //   be specified on the initial declaration of the member function
471198092Srdivacky        //   within the class template.
472198092Srdivacky        //
473198092Srdivacky        // Reading the tea leaves a bit in DR217 and its reference to DR205
474198092Srdivacky        // leads me to the conclusion that one cannot add default function
475198092Srdivacky        // arguments for an out-of-line definition of a member function of a
476198092Srdivacky        // dependent type.
477198092Srdivacky        int WhichKind = 2;
478198092Srdivacky        if (CXXRecordDecl *Record
479198092Srdivacky              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480198092Srdivacky          if (Record->getDescribedClassTemplate())
481198092Srdivacky            WhichKind = 0;
482198092Srdivacky          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483198092Srdivacky            WhichKind = 1;
484198092Srdivacky          else
485198092Srdivacky            WhichKind = 2;
486198092Srdivacky        }
487198092Srdivacky
488198092Srdivacky        Diag(NewParam->getLocation(),
489198092Srdivacky             diag::err_param_default_argument_member_template_redecl)
490198092Srdivacky          << WhichKind
491198092Srdivacky          << NewParam->getDefaultArgRange();
492223017Sdim      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493223017Sdim        CXXSpecialMember NewSM = getSpecialMember(Ctor),
494223017Sdim                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495223017Sdim        if (NewSM != OldSM) {
496223017Sdim          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497223017Sdim            << NewParam->getDefaultArgRange() << NewSM;
498223017Sdim          Diag(Old->getLocation(), diag::note_previous_declaration_special)
499223017Sdim            << OldSM;
500223017Sdim        }
501198092Srdivacky      }
502193326Sed    }
503193326Sed  }
504193326Sed
505203955Srdivacky  if (CheckEquivalentExceptionSpec(Old, New))
506195341Sed    Invalid = true;
507195341Sed
508193326Sed  return Invalid;
509193326Sed}
510193326Sed
511221345Sdim/// \brief Merge the exception specifications of two variable declarations.
512221345Sdim///
513221345Sdim/// This is called when there's a redeclaration of a VarDecl. The function
514221345Sdim/// checks if the redeclaration might have an exception specification and
515221345Sdim/// validates compatibility and merges the specs if necessary.
516221345Sdimvoid Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517221345Sdim  // Shortcut if exceptions are disabled.
518221345Sdim  if (!getLangOptions().CXXExceptions)
519221345Sdim    return;
520221345Sdim
521221345Sdim  assert(Context.hasSameType(New->getType(), Old->getType()) &&
522221345Sdim         "Should only be called if types are otherwise the same.");
523221345Sdim
524221345Sdim  QualType NewType = New->getType();
525221345Sdim  QualType OldType = Old->getType();
526221345Sdim
527221345Sdim  // We're only interested in pointers and references to functions, as well
528221345Sdim  // as pointers to member functions.
529221345Sdim  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530221345Sdim    NewType = R->getPointeeType();
531221345Sdim    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532221345Sdim  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533221345Sdim    NewType = P->getPointeeType();
534221345Sdim    OldType = OldType->getAs<PointerType>()->getPointeeType();
535221345Sdim  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536221345Sdim    NewType = M->getPointeeType();
537221345Sdim    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538221345Sdim  }
539221345Sdim
540221345Sdim  if (!NewType->isFunctionProtoType())
541221345Sdim    return;
542221345Sdim
543221345Sdim  // There's lots of special cases for functions. For function pointers, system
544221345Sdim  // libraries are hopefully not as broken so that we don't need these
545221345Sdim  // workarounds.
546221345Sdim  if (CheckEquivalentExceptionSpec(
547221345Sdim        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548221345Sdim        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549221345Sdim    New->setInvalidDecl();
550221345Sdim  }
551221345Sdim}
552221345Sdim
553193326Sed/// CheckCXXDefaultArguments - Verify that the default arguments for a
554193326Sed/// function declaration are well-formed according to C++
555193326Sed/// [dcl.fct.default].
556193326Sedvoid Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557193326Sed  unsigned NumParams = FD->getNumParams();
558193326Sed  unsigned p;
559193326Sed
560193326Sed  // Find first parameter with a default argument
561193326Sed  for (p = 0; p < NumParams; ++p) {
562193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
563198092Srdivacky    if (Param->hasDefaultArg())
564193326Sed      break;
565193326Sed  }
566193326Sed
567193326Sed  // C++ [dcl.fct.default]p4:
568193326Sed  //   In a given function declaration, all parameters
569193326Sed  //   subsequent to a parameter with a default argument shall
570193326Sed  //   have default arguments supplied in this or previous
571193326Sed  //   declarations. A default argument shall not be redefined
572193326Sed  //   by a later declaration (not even to the same value).
573193326Sed  unsigned LastMissingDefaultArg = 0;
574198092Srdivacky  for (; p < NumParams; ++p) {
575193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
576198092Srdivacky    if (!Param->hasDefaultArg()) {
577193326Sed      if (Param->isInvalidDecl())
578193326Sed        /* We already complained about this parameter. */;
579193326Sed      else if (Param->getIdentifier())
580198092Srdivacky        Diag(Param->getLocation(),
581193326Sed             diag::err_param_default_argument_missing_name)
582193326Sed          << Param->getIdentifier();
583193326Sed      else
584198092Srdivacky        Diag(Param->getLocation(),
585193326Sed             diag::err_param_default_argument_missing);
586198092Srdivacky
587193326Sed      LastMissingDefaultArg = p;
588193326Sed    }
589193326Sed  }
590193326Sed
591193326Sed  if (LastMissingDefaultArg > 0) {
592193326Sed    // Some default arguments were missing. Clear out all of the
593193326Sed    // default arguments up to (and including) the last missing
594193326Sed    // default argument, so that we leave the function parameters
595193326Sed    // in a semantically valid state.
596193326Sed    for (p = 0; p <= LastMissingDefaultArg; ++p) {
597193326Sed      ParmVarDecl *Param = FD->getParamDecl(p);
598194179Sed      if (Param->hasDefaultArg()) {
599193326Sed        Param->setDefaultArg(0);
600193326Sed      }
601193326Sed    }
602193326Sed  }
603193326Sed}
604193326Sed
605193326Sed/// isCurrentClassName - Determine whether the identifier II is the
606193326Sed/// name of the class type currently being defined. In the case of
607193326Sed/// nested classes, this will only return true if II is the name of
608193326Sed/// the innermost class.
609193326Sedbool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610193326Sed                              const CXXScopeSpec *SS) {
611202379Srdivacky  assert(getLangOptions().CPlusPlus && "No class names in C!");
612202379Srdivacky
613193326Sed  CXXRecordDecl *CurDecl;
614193326Sed  if (SS && SS->isSet() && !SS->isInvalid()) {
615198092Srdivacky    DeclContext *DC = computeDeclContext(*SS, true);
616193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617193326Sed  } else
618193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619193326Sed
620203955Srdivacky  if (CurDecl && CurDecl->getIdentifier())
621193326Sed    return &II == CurDecl->getIdentifier();
622193326Sed  else
623193326Sed    return false;
624193326Sed}
625193326Sed
626198092Srdivacky/// \brief Check the validity of a C++ base class specifier.
627193326Sed///
628193326Sed/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629193326Sed/// and returns NULL otherwise.
630193326SedCXXBaseSpecifier *
631193326SedSema::CheckBaseSpecifier(CXXRecordDecl *Class,
632193326Sed                         SourceRange SpecifierRange,
633193326Sed                         bool Virtual, AccessSpecifier Access,
634218893Sdim                         TypeSourceInfo *TInfo,
635218893Sdim                         SourceLocation EllipsisLoc) {
636212904Sdim  QualType BaseType = TInfo->getType();
637212904Sdim
638193326Sed  // C++ [class.union]p1:
639193326Sed  //   A union shall not have base classes.
640193326Sed  if (Class->isUnion()) {
641193326Sed    Diag(Class->getLocation(), diag::err_base_clause_on_union)
642193326Sed      << SpecifierRange;
643193326Sed    return 0;
644193326Sed  }
645193326Sed
646218893Sdim  if (EllipsisLoc.isValid() &&
647218893Sdim      !TInfo->getType()->containsUnexpandedParameterPack()) {
648218893Sdim    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649218893Sdim      << TInfo->getTypeLoc().getSourceRange();
650218893Sdim    EllipsisLoc = SourceLocation();
651218893Sdim  }
652218893Sdim
653193326Sed  if (BaseType->isDependentType())
654198092Srdivacky    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655212904Sdim                                          Class->getTagKind() == TTK_Class,
656218893Sdim                                          Access, TInfo, EllipsisLoc);
657193326Sed
658212904Sdim  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
659212904Sdim
660193326Sed  // Base specifiers must be record types.
661193326Sed  if (!BaseType->isRecordType()) {
662193326Sed    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663193326Sed    return 0;
664193326Sed  }
665193326Sed
666193326Sed  // C++ [class.union]p1:
667193326Sed  //   A union shall not be used as a base class.
668193326Sed  if (BaseType->isUnionType()) {
669193326Sed    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670193326Sed    return 0;
671193326Sed  }
672193326Sed
673193326Sed  // C++ [class.derived]p2:
674193326Sed  //   The class-name in a base-specifier shall not be an incompletely
675193326Sed  //   defined class.
676198092Srdivacky  if (RequireCompleteType(BaseLoc, BaseType,
677198092Srdivacky                          PDiag(diag::err_incomplete_base_class)
678212904Sdim                            << SpecifierRange)) {
679212904Sdim    Class->setInvalidDecl();
680193326Sed    return 0;
681212904Sdim  }
682193326Sed
683198092Srdivacky  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684198092Srdivacky  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685193326Sed  assert(BaseDecl && "Record type has no declaration");
686203955Srdivacky  BaseDecl = BaseDecl->getDefinition();
687193326Sed  assert(BaseDecl && "Base type is not incomplete, but has no definition");
688198092Srdivacky  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689198092Srdivacky  assert(CXXBaseDecl && "Base type is not a C++ type");
690200583Srdivacky
691221345Sdim  // C++ [class]p3:
692221345Sdim  //   If a class is marked final and it appears as a base-type-specifier in
693221345Sdim  //   base-clause, the program is ill-formed.
694199990Srdivacky  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695218893Sdim    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696218893Sdim      << CXXBaseDecl->getDeclName();
697200583Srdivacky    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698218893Sdim      << CXXBaseDecl->getDeclName();
699199990Srdivacky    return 0;
700199990Srdivacky  }
701193326Sed
702212904Sdim  if (BaseDecl->isInvalidDecl())
703212904Sdim    Class->setInvalidDecl();
704200583Srdivacky
705200583Srdivacky  // Create the base specifier.
706200583Srdivacky  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707212904Sdim                                        Class->getTagKind() == TTK_Class,
708218893Sdim                                        Access, TInfo, EllipsisLoc);
709200583Srdivacky}
710200583Srdivacky
711193326Sed/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712193326Sed/// one entry in the base class list of a class specifier, for
713198092Srdivacky/// example:
714198092Srdivacky///    class foo : public bar, virtual private baz {
715193326Sed/// 'public bar' and 'virtual private baz' are each base-specifiers.
716212904SdimBaseResult
717212904SdimSema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718193326Sed                         bool Virtual, AccessSpecifier Access,
719218893Sdim                         ParsedType basetype, SourceLocation BaseLoc,
720218893Sdim                         SourceLocation EllipsisLoc) {
721194711Sed  if (!classdecl)
722194711Sed    return true;
723194711Sed
724193326Sed  AdjustDeclIfTemplate(classdecl);
725212904Sdim  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
726204643Srdivacky  if (!Class)
727204643Srdivacky    return true;
728204643Srdivacky
729212904Sdim  TypeSourceInfo *TInfo = 0;
730212904Sdim  GetTypeFromParser(basetype, &TInfo);
731218893Sdim
732218893Sdim  if (EllipsisLoc.isInvalid() &&
733218893Sdim      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
734218893Sdim                                      UPPC_BaseType))
735218893Sdim    return true;
736218893Sdim
737193326Sed  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738218893Sdim                                                      Virtual, Access, TInfo,
739218893Sdim                                                      EllipsisLoc))
740193326Sed    return BaseSpec;
741198092Srdivacky
742193326Sed  return true;
743193326Sed}
744193326Sed
745193326Sed/// \brief Performs the actual work of attaching the given base class
746193326Sed/// specifiers to a C++ class.
747193326Sedbool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748193326Sed                                unsigned NumBases) {
749193326Sed if (NumBases == 0)
750193326Sed    return false;
751193326Sed
752193326Sed  // Used to keep track of which base types we have already seen, so
753193326Sed  // that we can properly diagnose redundant direct base types. Note
754193326Sed  // that the key is always the unqualified canonical type of the base
755193326Sed  // class.
756193326Sed  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757193326Sed
758193326Sed  // Copy non-redundant base specifiers into permanent storage.
759193326Sed  unsigned NumGoodBases = 0;
760193326Sed  bool Invalid = false;
761193326Sed  for (unsigned idx = 0; idx < NumBases; ++idx) {
762198092Srdivacky    QualType NewBaseType
763193326Sed      = Context.getCanonicalType(Bases[idx]->getType());
764199482Srdivacky    NewBaseType = NewBaseType.getLocalUnqualifiedType();
765208600Srdivacky    if (!Class->hasObjectMember()) {
766208600Srdivacky      if (const RecordType *FDTTy =
767208600Srdivacky            NewBaseType.getTypePtr()->getAs<RecordType>())
768208600Srdivacky        if (FDTTy->getDecl()->hasObjectMember())
769208600Srdivacky          Class->setHasObjectMember(true);
770208600Srdivacky    }
771208600Srdivacky
772193326Sed    if (KnownBaseTypes[NewBaseType]) {
773193326Sed      // C++ [class.mi]p3:
774193326Sed      //   A class shall not be specified as a direct base class of a
775193326Sed      //   derived class more than once.
776193326Sed      Diag(Bases[idx]->getSourceRange().getBegin(),
777193326Sed           diag::err_duplicate_base_class)
778193326Sed        << KnownBaseTypes[NewBaseType]->getType()
779193326Sed        << Bases[idx]->getSourceRange();
780193326Sed
781193326Sed      // Delete the duplicate base class specifier; we're going to
782193326Sed      // overwrite its pointer later.
783198092Srdivacky      Context.Deallocate(Bases[idx]);
784193326Sed
785193326Sed      Invalid = true;
786193326Sed    } else {
787193326Sed      // Okay, add this new base class.
788193326Sed      KnownBaseTypes[NewBaseType] = Bases[idx];
789193326Sed      Bases[NumGoodBases++] = Bases[idx];
790193326Sed    }
791193326Sed  }
792193326Sed
793193326Sed  // Attach the remaining base class specifiers to the derived class.
794203955Srdivacky  Class->setBases(Bases, NumGoodBases);
795193326Sed
796193326Sed  // Delete the remaining (good) base class specifiers, since their
797193326Sed  // data has been copied into the CXXRecordDecl.
798193326Sed  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
799198092Srdivacky    Context.Deallocate(Bases[idx]);
800193326Sed
801193326Sed  return Invalid;
802193326Sed}
803193326Sed
804193326Sed/// ActOnBaseSpecifiers - Attach the given base specifiers to the
805193326Sed/// class, after checking whether there are any duplicate base
806193326Sed/// classes.
807212904Sdimvoid Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
808193326Sed                               unsigned NumBases) {
809193326Sed  if (!ClassDecl || !Bases || !NumBases)
810193326Sed    return;
811193326Sed
812193326Sed  AdjustDeclIfTemplate(ClassDecl);
813212904Sdim  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
814193326Sed                       (CXXBaseSpecifier**)(Bases), NumBases);
815193326Sed}
816193326Sed
817204962Srdivackystatic CXXRecordDecl *GetClassForType(QualType T) {
818204962Srdivacky  if (const RecordType *RT = T->getAs<RecordType>())
819204962Srdivacky    return cast<CXXRecordDecl>(RT->getDecl());
820204962Srdivacky  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
821204962Srdivacky    return ICT->getDecl();
822204962Srdivacky  else
823204962Srdivacky    return 0;
824204962Srdivacky}
825204962Srdivacky
826198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is
827198092Srdivacky/// derived from the type \p Base.
828198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
829198092Srdivacky  if (!getLangOptions().CPlusPlus)
830198092Srdivacky    return false;
831204962Srdivacky
832204962Srdivacky  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
833204962Srdivacky  if (!DerivedRD)
834198092Srdivacky    return false;
835198092Srdivacky
836204962Srdivacky  CXXRecordDecl *BaseRD = GetClassForType(Base);
837204962Srdivacky  if (!BaseRD)
838198092Srdivacky    return false;
839198092Srdivacky
840203955Srdivacky  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
841203955Srdivacky  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
842198092Srdivacky}
843198092Srdivacky
844198092Srdivacky/// \brief Determine whether the type \p Derived is a C++ class that is
845198092Srdivacky/// derived from the type \p Base.
846198092Srdivackybool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
847198092Srdivacky  if (!getLangOptions().CPlusPlus)
848198092Srdivacky    return false;
849198092Srdivacky
850204962Srdivacky  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
851204962Srdivacky  if (!DerivedRD)
852198092Srdivacky    return false;
853198092Srdivacky
854204962Srdivacky  CXXRecordDecl *BaseRD = GetClassForType(Base);
855204962Srdivacky  if (!BaseRD)
856198092Srdivacky    return false;
857198092Srdivacky
858198092Srdivacky  return DerivedRD->isDerivedFrom(BaseRD, Paths);
859198092Srdivacky}
860198092Srdivacky
861207619Srdivackyvoid Sema::BuildBasePathArray(const CXXBasePaths &Paths,
862212904Sdim                              CXXCastPath &BasePathArray) {
863207619Srdivacky  assert(BasePathArray.empty() && "Base path array must be empty!");
864207619Srdivacky  assert(Paths.isRecordingPaths() && "Must record paths!");
865207619Srdivacky
866207619Srdivacky  const CXXBasePath &Path = Paths.front();
867207619Srdivacky
868207619Srdivacky  // We first go backward and check if we have a virtual base.
869207619Srdivacky  // FIXME: It would be better if CXXBasePath had the base specifier for
870207619Srdivacky  // the nearest virtual base.
871207619Srdivacky  unsigned Start = 0;
872207619Srdivacky  for (unsigned I = Path.size(); I != 0; --I) {
873207619Srdivacky    if (Path[I - 1].Base->isVirtual()) {
874207619Srdivacky      Start = I - 1;
875207619Srdivacky      break;
876207619Srdivacky    }
877207619Srdivacky  }
878207619Srdivacky
879207619Srdivacky  // Now add all bases.
880207619Srdivacky  for (unsigned I = Start, E = Path.size(); I != E; ++I)
881212904Sdim    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
882207619Srdivacky}
883207619Srdivacky
884208600Srdivacky/// \brief Determine whether the given base path includes a virtual
885208600Srdivacky/// base class.
886212904Sdimbool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
887212904Sdim  for (CXXCastPath::const_iterator B = BasePath.begin(),
888212904Sdim                                BEnd = BasePath.end();
889208600Srdivacky       B != BEnd; ++B)
890208600Srdivacky    if ((*B)->isVirtual())
891208600Srdivacky      return true;
892208600Srdivacky
893208600Srdivacky  return false;
894208600Srdivacky}
895208600Srdivacky
896198092Srdivacky/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
897198092Srdivacky/// conversion (where Derived and Base are class types) is
898198092Srdivacky/// well-formed, meaning that the conversion is unambiguous (and
899198092Srdivacky/// that all of the base classes are accessible). Returns true
900198092Srdivacky/// and emits a diagnostic if the code is ill-formed, returns false
901198092Srdivacky/// otherwise. Loc is the location where this routine should point to
902198092Srdivacky/// if there is an error, and Range is the source range to highlight
903198092Srdivacky/// if there is an error.
904198092Srdivackybool
905198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
906205219Srdivacky                                   unsigned InaccessibleBaseID,
907198092Srdivacky                                   unsigned AmbigiousBaseConvID,
908198092Srdivacky                                   SourceLocation Loc, SourceRange Range,
909207619Srdivacky                                   DeclarationName Name,
910212904Sdim                                   CXXCastPath *BasePath) {
911198092Srdivacky  // First, determine whether the path from Derived to Base is
912198092Srdivacky  // ambiguous. This is slightly more expensive than checking whether
913198092Srdivacky  // the Derived to Base conversion exists, because here we need to
914198092Srdivacky  // explore multiple paths to determine if there is an ambiguity.
915198092Srdivacky  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
916198092Srdivacky                     /*DetectVirtual=*/false);
917198092Srdivacky  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
918198092Srdivacky  assert(DerivationOkay &&
919198092Srdivacky         "Can only be used with a derived-to-base conversion");
920198092Srdivacky  (void)DerivationOkay;
921198092Srdivacky
922198092Srdivacky  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
923207619Srdivacky    if (InaccessibleBaseID) {
924207619Srdivacky      // Check that the base class can be accessed.
925207619Srdivacky      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
926207619Srdivacky                                   InaccessibleBaseID)) {
927207619Srdivacky        case AR_inaccessible:
928207619Srdivacky          return true;
929207619Srdivacky        case AR_accessible:
930207619Srdivacky        case AR_dependent:
931207619Srdivacky        case AR_delayed:
932207619Srdivacky          break;
933207619Srdivacky      }
934203955Srdivacky    }
935207619Srdivacky
936207619Srdivacky    // Build a base path if necessary.
937207619Srdivacky    if (BasePath)
938207619Srdivacky      BuildBasePathArray(Paths, *BasePath);
939207619Srdivacky    return false;
940198092Srdivacky  }
941198092Srdivacky
942198092Srdivacky  // We know that the derived-to-base conversion is ambiguous, and
943198092Srdivacky  // we're going to produce a diagnostic. Perform the derived-to-base
944198092Srdivacky  // search just one more time to compute all of the possible paths so
945198092Srdivacky  // that we can print them out. This is more expensive than any of
946198092Srdivacky  // the previous derived-to-base checks we've done, but at this point
947198092Srdivacky  // performance isn't as much of an issue.
948198092Srdivacky  Paths.clear();
949198092Srdivacky  Paths.setRecordingPaths(true);
950198092Srdivacky  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
951198092Srdivacky  assert(StillOkay && "Can only be used with a derived-to-base conversion");
952198092Srdivacky  (void)StillOkay;
953198092Srdivacky
954198092Srdivacky  // Build up a textual representation of the ambiguous paths, e.g.,
955198092Srdivacky  // D -> B -> A, that will be used to illustrate the ambiguous
956198092Srdivacky  // conversions in the diagnostic. We only print one of the paths
957198092Srdivacky  // to each base class subobject.
958198092Srdivacky  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
959198092Srdivacky
960198092Srdivacky  Diag(Loc, AmbigiousBaseConvID)
961198092Srdivacky  << Derived << Base << PathDisplayStr << Range << Name;
962198092Srdivacky  return true;
963198092Srdivacky}
964198092Srdivacky
965198092Srdivackybool
966198092SrdivackySema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
967199482Srdivacky                                   SourceLocation Loc, SourceRange Range,
968212904Sdim                                   CXXCastPath *BasePath,
969199482Srdivacky                                   bool IgnoreAccess) {
970198092Srdivacky  return CheckDerivedToBaseConversion(Derived, Base,
971205219Srdivacky                                      IgnoreAccess ? 0
972205219Srdivacky                                       : diag::err_upcast_to_inaccessible_base,
973198092Srdivacky                                      diag::err_ambiguous_derived_to_base_conv,
974207619Srdivacky                                      Loc, Range, DeclarationName(),
975207619Srdivacky                                      BasePath);
976198092Srdivacky}
977198092Srdivacky
978198092Srdivacky
979198092Srdivacky/// @brief Builds a string representing ambiguous paths from a
980198092Srdivacky/// specific derived class to different subobjects of the same base
981198092Srdivacky/// class.
982198092Srdivacky///
983198092Srdivacky/// This function builds a string that can be used in error messages
984198092Srdivacky/// to show the different paths that one can take through the
985198092Srdivacky/// inheritance hierarchy to go from the derived class to different
986198092Srdivacky/// subobjects of a base class. The result looks something like this:
987198092Srdivacky/// @code
988198092Srdivacky/// struct D -> struct B -> struct A
989198092Srdivacky/// struct D -> struct C -> struct A
990198092Srdivacky/// @endcode
991198092Srdivackystd::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
992198092Srdivacky  std::string PathDisplayStr;
993198092Srdivacky  std::set<unsigned> DisplayedPaths;
994198092Srdivacky  for (CXXBasePaths::paths_iterator Path = Paths.begin();
995198092Srdivacky       Path != Paths.end(); ++Path) {
996198092Srdivacky    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
997198092Srdivacky      // We haven't displayed a path to this particular base
998198092Srdivacky      // class subobject yet.
999198092Srdivacky      PathDisplayStr += "\n    ";
1000198092Srdivacky      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1001198092Srdivacky      for (CXXBasePath::const_iterator Element = Path->begin();
1002198092Srdivacky           Element != Path->end(); ++Element)
1003198092Srdivacky        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1004198092Srdivacky    }
1005198092Srdivacky  }
1006198092Srdivacky
1007198092Srdivacky  return PathDisplayStr;
1008198092Srdivacky}
1009198092Srdivacky
1010193326Sed//===----------------------------------------------------------------------===//
1011193326Sed// C++ class member Handling
1012193326Sed//===----------------------------------------------------------------------===//
1013193326Sed
1014210299Sed/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1015212904SdimDecl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1016212904Sdim                                 SourceLocation ASLoc,
1017212904Sdim                                 SourceLocation ColonLoc) {
1018210299Sed  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1019212904Sdim  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1020210299Sed                                                  ASLoc, ColonLoc);
1021210299Sed  CurContext->addHiddenDecl(ASDecl);
1022212904Sdim  return ASDecl;
1023210299Sed}
1024210299Sed
1025218893Sdim/// CheckOverrideControl - Check C++0x override control semantics.
1026218893Sdimvoid Sema::CheckOverrideControl(const Decl *D) {
1027218893Sdim  const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1028218893Sdim  if (!MD || !MD->isVirtual())
1029218893Sdim    return;
1030218893Sdim
1031218893Sdim  if (MD->isDependentContext())
1032218893Sdim    return;
1033218893Sdim
1034218893Sdim  // C++0x [class.virtual]p3:
1035218893Sdim  //   If a virtual function is marked with the virt-specifier override and does
1036218893Sdim  //   not override a member function of a base class,
1037218893Sdim  //   the program is ill-formed.
1038218893Sdim  bool HasOverriddenMethods =
1039218893Sdim    MD->begin_overridden_methods() != MD->end_overridden_methods();
1040218893Sdim  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1041218893Sdim    Diag(MD->getLocation(),
1042218893Sdim                 diag::err_function_marked_override_not_overriding)
1043218893Sdim      << MD->getDeclName();
1044218893Sdim    return;
1045218893Sdim  }
1046218893Sdim}
1047218893Sdim
1048218893Sdim/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1049218893Sdim/// function overrides a virtual member function marked 'final', according to
1050218893Sdim/// C++0x [class.virtual]p3.
1051218893Sdimbool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1052218893Sdim                                                  const CXXMethodDecl *Old) {
1053218893Sdim  if (!Old->hasAttr<FinalAttr>())
1054218893Sdim    return false;
1055218893Sdim
1056218893Sdim  Diag(New->getLocation(), diag::err_final_function_overridden)
1057218893Sdim    << New->getDeclName();
1058218893Sdim  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1059218893Sdim  return true;
1060218893Sdim}
1061218893Sdim
1062193326Sed/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1063193326Sed/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1064223017Sdim/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1065223017Sdim/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1066223017Sdim/// present but parsing it has been deferred.
1067212904SdimDecl *
1068193326SedSema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1069198092Srdivacky                               MultiTemplateParamsArg TemplateParameterLists,
1070218893Sdim                               ExprTy *BW, const VirtSpecifiers &VS,
1071223017Sdim                               ExprTy *InitExpr, bool HasDeferredInit,
1072223017Sdim                               bool IsDefinition) {
1073193326Sed  const DeclSpec &DS = D.getDeclSpec();
1074212904Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1075212904Sdim  DeclarationName Name = NameInfo.getName();
1076212904Sdim  SourceLocation Loc = NameInfo.getLoc();
1077218893Sdim
1078218893Sdim  // For anonymous bitfields, the location should point to the type.
1079218893Sdim  if (Loc.isInvalid())
1080218893Sdim    Loc = D.getSourceRange().getBegin();
1081218893Sdim
1082193326Sed  Expr *BitWidth = static_cast<Expr*>(BW);
1083193326Sed  Expr *Init = static_cast<Expr*>(InitExpr);
1084193326Sed
1085210299Sed  assert(isa<CXXRecordDecl>(CurContext));
1086198092Srdivacky  assert(!DS.isFriendSpecified());
1087223017Sdim  assert(!Init || !HasDeferredInit);
1088198092Srdivacky
1089210299Sed  bool isFunc = false;
1090210299Sed  if (D.isFunctionDeclarator())
1091210299Sed    isFunc = true;
1092210299Sed  else if (D.getNumTypeObjects() == 0 &&
1093210299Sed           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
1094212904Sdim    QualType TDType = GetTypeFromParser(DS.getRepAsType());
1095210299Sed    isFunc = TDType->isFunctionType();
1096210299Sed  }
1097210299Sed
1098193326Sed  // C++ 9.2p6: A member shall not be declared to have automatic storage
1099193326Sed  // duration (auto, register) or with the extern storage-class-specifier.
1100193326Sed  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1101193326Sed  // data members and cannot be applied to names declared const or static,
1102193326Sed  // and cannot be applied to reference members.
1103193326Sed  switch (DS.getStorageClassSpec()) {
1104193326Sed    case DeclSpec::SCS_unspecified:
1105193326Sed    case DeclSpec::SCS_typedef:
1106193326Sed    case DeclSpec::SCS_static:
1107193326Sed      // FALL THROUGH.
1108193326Sed      break;
1109193326Sed    case DeclSpec::SCS_mutable:
1110193326Sed      if (isFunc) {
1111193326Sed        if (DS.getStorageClassSpecLoc().isValid())
1112193326Sed          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1113193326Sed        else
1114193326Sed          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1115198092Srdivacky
1116193326Sed        // FIXME: It would be nicer if the keyword was ignored only for this
1117193326Sed        // declarator. Otherwise we could get follow-up errors.
1118193326Sed        D.getMutableDeclSpec().ClearStorageClassSpecs();
1119193326Sed      }
1120193326Sed      break;
1121193326Sed    default:
1122193326Sed      if (DS.getStorageClassSpecLoc().isValid())
1123193326Sed        Diag(DS.getStorageClassSpecLoc(),
1124193326Sed             diag::err_storageclass_invalid_for_member);
1125193326Sed      else
1126193326Sed        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1127193326Sed      D.getMutableDeclSpec().ClearStorageClassSpecs();
1128193326Sed  }
1129193326Sed
1130193326Sed  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1131193326Sed                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1132193326Sed                      !isFunc);
1133193326Sed
1134193326Sed  Decl *Member;
1135193326Sed  if (isInstField) {
1136218893Sdim    CXXScopeSpec &SS = D.getCXXScopeSpec();
1137218893Sdim
1138218893Sdim    if (SS.isSet() && !SS.isInvalid()) {
1139218893Sdim      // The user provided a superfluous scope specifier inside a class
1140218893Sdim      // definition:
1141218893Sdim      //
1142218893Sdim      // class X {
1143218893Sdim      //   int X::member;
1144218893Sdim      // };
1145218893Sdim      DeclContext *DC = 0;
1146218893Sdim      if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1147218893Sdim        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1148218893Sdim        << Name << FixItHint::CreateRemoval(SS.getRange());
1149218893Sdim      else
1150218893Sdim        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1151218893Sdim          << Name << SS.getRange();
1152218893Sdim
1153218893Sdim      SS.clear();
1154218893Sdim    }
1155218893Sdim
1156198092Srdivacky    // FIXME: Check for template parameters!
1157218893Sdim    // FIXME: Check that the name is an identifier!
1158193326Sed    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1159223017Sdim                         HasDeferredInit, AS);
1160193326Sed    assert(Member && "HandleField never returns null");
1161193326Sed  } else {
1162223017Sdim    assert(!HasDeferredInit);
1163223017Sdim
1164212904Sdim    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1165193326Sed    if (!Member) {
1166212904Sdim      return 0;
1167193326Sed    }
1168193326Sed
1169193326Sed    // Non-instance-fields can't have a bitfield.
1170193326Sed    if (BitWidth) {
1171193326Sed      if (Member->isInvalidDecl()) {
1172193326Sed        // don't emit another diagnostic.
1173193326Sed      } else if (isa<VarDecl>(Member)) {
1174193326Sed        // C++ 9.6p3: A bit-field shall not be a static member.
1175193326Sed        // "static member 'A' cannot be a bit-field"
1176193326Sed        Diag(Loc, diag::err_static_not_bitfield)
1177193326Sed          << Name << BitWidth->getSourceRange();
1178193326Sed      } else if (isa<TypedefDecl>(Member)) {
1179193326Sed        // "typedef member 'x' cannot be a bit-field"
1180193326Sed        Diag(Loc, diag::err_typedef_not_bitfield)
1181193326Sed          << Name << BitWidth->getSourceRange();
1182193326Sed      } else {
1183193326Sed        // A function typedef ("typedef int f(); f a;").
1184193326Sed        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1185193326Sed        Diag(Loc, diag::err_not_integral_type_bitfield)
1186198092Srdivacky          << Name << cast<ValueDecl>(Member)->getType()
1187193326Sed          << BitWidth->getSourceRange();
1188193326Sed      }
1189198092Srdivacky
1190193326Sed      BitWidth = 0;
1191193326Sed      Member->setInvalidDecl();
1192193326Sed    }
1193193326Sed
1194193326Sed    Member->setAccess(AS);
1195198092Srdivacky
1196198092Srdivacky    // If we have declared a member function template, set the access of the
1197198092Srdivacky    // templated declaration as well.
1198198092Srdivacky    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1199198092Srdivacky      FunTmpl->getTemplatedDecl()->setAccess(AS);
1200193326Sed  }
1201193326Sed
1202218893Sdim  if (VS.isOverrideSpecified()) {
1203218893Sdim    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1204218893Sdim    if (!MD || !MD->isVirtual()) {
1205218893Sdim      Diag(Member->getLocStart(),
1206218893Sdim           diag::override_keyword_only_allowed_on_virtual_member_functions)
1207218893Sdim        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1208218893Sdim    } else
1209218893Sdim      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1210218893Sdim  }
1211218893Sdim  if (VS.isFinalSpecified()) {
1212218893Sdim    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1213218893Sdim    if (!MD || !MD->isVirtual()) {
1214218893Sdim      Diag(Member->getLocStart(),
1215218893Sdim           diag::override_keyword_only_allowed_on_virtual_member_functions)
1216218893Sdim      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1217218893Sdim    } else
1218218893Sdim      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1219218893Sdim  }
1220218893Sdim
1221221345Sdim  if (VS.getLastLocation().isValid()) {
1222221345Sdim    // Update the end location of a method that has a virt-specifiers.
1223221345Sdim    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1224221345Sdim      MD->setRangeEnd(VS.getLastLocation());
1225221345Sdim  }
1226221345Sdim
1227218893Sdim  CheckOverrideControl(Member);
1228218893Sdim
1229193326Sed  assert((Name || isInstField) && "No identifier for non-field ?");
1230193326Sed
1231193326Sed  if (Init)
1232218893Sdim    AddInitializerToDecl(Member, Init, false,
1233218893Sdim                         DS.getTypeSpecType() == DeclSpec::TST_auto);
1234223017Sdim  else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1235223017Sdim           DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1236223017Sdim    // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1237223017Sdim    // data member if a brace-or-equal-initializer is provided.
1238223017Sdim    Diag(Loc, diag::err_auto_var_requires_init)
1239223017Sdim      << Name << cast<ValueDecl>(Member)->getType();
1240223017Sdim    Member->setInvalidDecl();
1241223017Sdim  }
1242193326Sed
1243219077Sdim  FinalizeDeclaration(Member);
1244219077Sdim
1245218893Sdim  if (isInstField)
1246193326Sed    FieldCollector->Add(cast<FieldDecl>(Member));
1247212904Sdim  return Member;
1248193326Sed}
1249193326Sed
1250223017Sdim/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1251223017Sdim/// in-class initializer for a non-static C++ class member. Such parsing
1252223017Sdim/// is deferred until the class is complete.
1253223017Sdimvoid
1254223017SdimSema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1255223017Sdim                                       Expr *InitExpr) {
1256223017Sdim  FieldDecl *FD = cast<FieldDecl>(D);
1257223017Sdim
1258223017Sdim  if (!InitExpr) {
1259223017Sdim    FD->setInvalidDecl();
1260223017Sdim    FD->removeInClassInitializer();
1261223017Sdim    return;
1262223017Sdim  }
1263223017Sdim
1264223017Sdim  ExprResult Init = InitExpr;
1265223017Sdim  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1266223017Sdim    // FIXME: if there is no EqualLoc, this is list-initialization.
1267223017Sdim    Init = PerformCopyInitialization(
1268223017Sdim      InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1269223017Sdim    if (Init.isInvalid()) {
1270223017Sdim      FD->setInvalidDecl();
1271223017Sdim      return;
1272223017Sdim    }
1273223017Sdim
1274223017Sdim    CheckImplicitConversions(Init.get(), EqualLoc);
1275223017Sdim  }
1276223017Sdim
1277223017Sdim  // C++0x [class.base.init]p7:
1278223017Sdim  //   The initialization of each base and member constitutes a
1279223017Sdim  //   full-expression.
1280223017Sdim  Init = MaybeCreateExprWithCleanups(Init);
1281223017Sdim  if (Init.isInvalid()) {
1282223017Sdim    FD->setInvalidDecl();
1283223017Sdim    return;
1284223017Sdim  }
1285223017Sdim
1286223017Sdim  InitExpr = Init.release();
1287223017Sdim
1288223017Sdim  FD->setInClassInitializer(InitExpr);
1289223017Sdim}
1290223017Sdim
1291201361Srdivacky/// \brief Find the direct and/or virtual base specifiers that
1292201361Srdivacky/// correspond to the given base type, for use in base initialization
1293201361Srdivacky/// within a constructor.
1294201361Srdivackystatic bool FindBaseInitializer(Sema &SemaRef,
1295201361Srdivacky                                CXXRecordDecl *ClassDecl,
1296201361Srdivacky                                QualType BaseType,
1297201361Srdivacky                                const CXXBaseSpecifier *&DirectBaseSpec,
1298201361Srdivacky                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1299201361Srdivacky  // First, check for a direct base class.
1300201361Srdivacky  DirectBaseSpec = 0;
1301201361Srdivacky  for (CXXRecordDecl::base_class_const_iterator Base
1302201361Srdivacky         = ClassDecl->bases_begin();
1303201361Srdivacky       Base != ClassDecl->bases_end(); ++Base) {
1304201361Srdivacky    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1305201361Srdivacky      // We found a direct base of this type. That's what we're
1306201361Srdivacky      // initializing.
1307201361Srdivacky      DirectBaseSpec = &*Base;
1308201361Srdivacky      break;
1309201361Srdivacky    }
1310201361Srdivacky  }
1311201361Srdivacky
1312201361Srdivacky  // Check for a virtual base class.
1313201361Srdivacky  // FIXME: We might be able to short-circuit this if we know in advance that
1314201361Srdivacky  // there are no virtual bases.
1315201361Srdivacky  VirtualBaseSpec = 0;
1316201361Srdivacky  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1317201361Srdivacky    // We haven't found a base yet; search the class hierarchy for a
1318201361Srdivacky    // virtual base class.
1319201361Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1320201361Srdivacky                       /*DetectVirtual=*/false);
1321201361Srdivacky    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1322201361Srdivacky                              BaseType, Paths)) {
1323201361Srdivacky      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1324201361Srdivacky           Path != Paths.end(); ++Path) {
1325201361Srdivacky        if (Path->back().Base->isVirtual()) {
1326201361Srdivacky          VirtualBaseSpec = Path->back().Base;
1327201361Srdivacky          break;
1328201361Srdivacky        }
1329201361Srdivacky      }
1330201361Srdivacky    }
1331201361Srdivacky  }
1332201361Srdivacky
1333201361Srdivacky  return DirectBaseSpec || VirtualBaseSpec;
1334201361Srdivacky}
1335201361Srdivacky
1336193326Sed/// ActOnMemInitializer - Handle a C++ member initializer.
1337212904SdimMemInitResult
1338212904SdimSema::ActOnMemInitializer(Decl *ConstructorD,
1339193326Sed                          Scope *S,
1340207619Srdivacky                          CXXScopeSpec &SS,
1341193326Sed                          IdentifierInfo *MemberOrBase,
1342212904Sdim                          ParsedType TemplateTypeTy,
1343193326Sed                          SourceLocation IdLoc,
1344193326Sed                          SourceLocation LParenLoc,
1345193326Sed                          ExprTy **Args, unsigned NumArgs,
1346218893Sdim                          SourceLocation RParenLoc,
1347218893Sdim                          SourceLocation EllipsisLoc) {
1348194711Sed  if (!ConstructorD)
1349194711Sed    return true;
1350198092Srdivacky
1351198092Srdivacky  AdjustDeclIfTemplate(ConstructorD);
1352198092Srdivacky
1353198092Srdivacky  CXXConstructorDecl *Constructor
1354212904Sdim    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1355193326Sed  if (!Constructor) {
1356193326Sed    // The user wrote a constructor initializer on a function that is
1357193326Sed    // not a C++ constructor. Ignore the error for now, because we may
1358193326Sed    // have more member initializers coming; we'll diagnose it just
1359193326Sed    // once in ActOnMemInitializers.
1360193326Sed    return true;
1361193326Sed  }
1362193326Sed
1363193326Sed  CXXRecordDecl *ClassDecl = Constructor->getParent();
1364193326Sed
1365193326Sed  // C++ [class.base.init]p2:
1366193326Sed  //   Names in a mem-initializer-id are looked up in the scope of the
1367218893Sdim  //   constructor's class and, if not found in that scope, are looked
1368218893Sdim  //   up in the scope containing the constructor's definition.
1369218893Sdim  //   [Note: if the constructor's class contains a member with the
1370218893Sdim  //   same name as a direct or virtual base class of the class, a
1371218893Sdim  //   mem-initializer-id naming the member or base class and composed
1372218893Sdim  //   of a single identifier refers to the class member. A
1373193326Sed  //   mem-initializer-id for the hidden base class may be specified
1374193326Sed  //   using a qualified name. ]
1375195341Sed  if (!SS.getScopeRep() && !TemplateTypeTy) {
1376195341Sed    // Look for a member, first.
1377195341Sed    FieldDecl *Member = 0;
1378198092Srdivacky    DeclContext::lookup_result Result
1379195341Sed      = ClassDecl->lookup(MemberOrBase);
1380218893Sdim    if (Result.first != Result.second) {
1381195341Sed      Member = dyn_cast<FieldDecl>(*Result.first);
1382218893Sdim
1383218893Sdim      if (Member) {
1384218893Sdim        if (EllipsisLoc.isValid())
1385218893Sdim          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1386218893Sdim            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1387218893Sdim
1388218893Sdim        return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1389218893Sdim                                    LParenLoc, RParenLoc);
1390218893Sdim      }
1391218893Sdim
1392218893Sdim      // Handle anonymous union case.
1393218893Sdim      if (IndirectFieldDecl* IndirectField
1394218893Sdim            = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1395218893Sdim        if (EllipsisLoc.isValid())
1396218893Sdim          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1397218893Sdim            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1398193326Sed
1399218893Sdim         return BuildMemberInitializer(IndirectField, (Expr**)Args,
1400218893Sdim                                       NumArgs, IdLoc,
1401218893Sdim                                       LParenLoc, RParenLoc);
1402218893Sdim      }
1403218893Sdim    }
1404193326Sed  }
1405193326Sed  // It didn't name a member, so see if it names a class.
1406200583Srdivacky  QualType BaseType;
1407201361Srdivacky  TypeSourceInfo *TInfo = 0;
1408200583Srdivacky
1409201361Srdivacky  if (TemplateTypeTy) {
1410200583Srdivacky    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1411201361Srdivacky  } else {
1412201361Srdivacky    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1413201361Srdivacky    LookupParsedName(R, S, &SS);
1414193326Sed
1415201361Srdivacky    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1416201361Srdivacky    if (!TyD) {
1417201361Srdivacky      if (R.isAmbiguous()) return true;
1418201361Srdivacky
1419207619Srdivacky      // We don't want access-control diagnostics here.
1420207619Srdivacky      R.suppressDiagnostics();
1421207619Srdivacky
1422202879Srdivacky      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1423202879Srdivacky        bool NotUnknownSpecialization = false;
1424202879Srdivacky        DeclContext *DC = computeDeclContext(SS, false);
1425202879Srdivacky        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1426202879Srdivacky          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1427202879Srdivacky
1428202879Srdivacky        if (!NotUnknownSpecialization) {
1429202879Srdivacky          // When the scope specifier can refer to a member of an unknown
1430202879Srdivacky          // specialization, we take it as a type name.
1431221345Sdim          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1432221345Sdim                                       SS.getWithLocInContext(Context),
1433221345Sdim                                       *MemberOrBase, IdLoc);
1434204962Srdivacky          if (BaseType.isNull())
1435204962Srdivacky            return true;
1436204962Srdivacky
1437202879Srdivacky          R.clear();
1438210299Sed          R.setLookupName(MemberOrBase);
1439202879Srdivacky        }
1440202879Srdivacky      }
1441202879Srdivacky
1442201361Srdivacky      // If no results were found, try to correct typos.
1443202879Srdivacky      if (R.empty() && BaseType.isNull() &&
1444207619Srdivacky          CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1445207619Srdivacky          R.isSingleResult()) {
1446201361Srdivacky        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1447212904Sdim          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1448201361Srdivacky            // We have found a non-static data member with a similar
1449201361Srdivacky            // name to what was typed; complain and initialize that
1450201361Srdivacky            // member.
1451201361Srdivacky            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1452201361Srdivacky              << MemberOrBase << true << R.getLookupName()
1453206084Srdivacky              << FixItHint::CreateReplacement(R.getNameLoc(),
1454206084Srdivacky                                              R.getLookupName().getAsString());
1455202379Srdivacky            Diag(Member->getLocation(), diag::note_previous_decl)
1456202379Srdivacky              << Member->getDeclName();
1457201361Srdivacky
1458201361Srdivacky            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1459201361Srdivacky                                          LParenLoc, RParenLoc);
1460201361Srdivacky          }
1461201361Srdivacky        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1462201361Srdivacky          const CXXBaseSpecifier *DirectBaseSpec;
1463201361Srdivacky          const CXXBaseSpecifier *VirtualBaseSpec;
1464201361Srdivacky          if (FindBaseInitializer(*this, ClassDecl,
1465201361Srdivacky                                  Context.getTypeDeclType(Type),
1466201361Srdivacky                                  DirectBaseSpec, VirtualBaseSpec)) {
1467201361Srdivacky            // We have found a direct or virtual base class with a
1468201361Srdivacky            // similar name to what was typed; complain and initialize
1469201361Srdivacky            // that base class.
1470201361Srdivacky            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1471201361Srdivacky              << MemberOrBase << false << R.getLookupName()
1472206084Srdivacky              << FixItHint::CreateReplacement(R.getNameLoc(),
1473206084Srdivacky                                              R.getLookupName().getAsString());
1474202379Srdivacky
1475202379Srdivacky            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1476202379Srdivacky                                                             : VirtualBaseSpec;
1477202379Srdivacky            Diag(BaseSpec->getSourceRange().getBegin(),
1478202379Srdivacky                 diag::note_base_class_specified_here)
1479202379Srdivacky              << BaseSpec->getType()
1480202379Srdivacky              << BaseSpec->getSourceRange();
1481202379Srdivacky
1482201361Srdivacky            TyD = Type;
1483201361Srdivacky          }
1484201361Srdivacky        }
1485201361Srdivacky      }
1486201361Srdivacky
1487202879Srdivacky      if (!TyD && BaseType.isNull()) {
1488201361Srdivacky        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1489201361Srdivacky          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1490201361Srdivacky        return true;
1491201361Srdivacky      }
1492201361Srdivacky    }
1493201361Srdivacky
1494202879Srdivacky    if (BaseType.isNull()) {
1495202879Srdivacky      BaseType = Context.getTypeDeclType(TyD);
1496202879Srdivacky      if (SS.isSet()) {
1497202879Srdivacky        NestedNameSpecifier *Qualifier =
1498202879Srdivacky          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1499201361Srdivacky
1500202879Srdivacky        // FIXME: preserve source range information
1501208600Srdivacky        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1502202879Srdivacky      }
1503201361Srdivacky    }
1504201361Srdivacky  }
1505201361Srdivacky
1506200583Srdivacky  if (!TInfo)
1507200583Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1508198092Srdivacky
1509200583Srdivacky  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1510218893Sdim                              LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1511198092Srdivacky}
1512198092Srdivacky
1513198954Srdivacky/// Checks an initializer expression for use of uninitialized fields, such as
1514198954Srdivacky/// containing the field that is being initialized. Returns true if there is an
1515198954Srdivacky/// uninitialized field was used an updates the SourceLocation parameter; false
1516198954Srdivacky/// otherwise.
1517210299Sedstatic bool InitExprContainsUninitializedFields(const Stmt *S,
1518218893Sdim                                                const ValueDecl *LhsField,
1519210299Sed                                                SourceLocation *L) {
1520218893Sdim  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1521218893Sdim
1522210299Sed  if (isa<CallExpr>(S)) {
1523210299Sed    // Do not descend into function calls or constructors, as the use
1524210299Sed    // of an uninitialized field may be valid. One would have to inspect
1525210299Sed    // the contents of the function/ctor to determine if it is safe or not.
1526210299Sed    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1527210299Sed    // may be safe, depending on what the function/ctor does.
1528210299Sed    return false;
1529210299Sed  }
1530210299Sed  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1531210299Sed    const NamedDecl *RhsField = ME->getMemberDecl();
1532218893Sdim
1533218893Sdim    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1534218893Sdim      // The member expression points to a static data member.
1535218893Sdim      assert(VD->isStaticDataMember() &&
1536218893Sdim             "Member points to non-static data member!");
1537218893Sdim      (void)VD;
1538218893Sdim      return false;
1539218893Sdim    }
1540218893Sdim
1541218893Sdim    if (isa<EnumConstantDecl>(RhsField)) {
1542218893Sdim      // The member expression points to an enum.
1543218893Sdim      return false;
1544218893Sdim    }
1545218893Sdim
1546198954Srdivacky    if (RhsField == LhsField) {
1547198954Srdivacky      // Initializing a field with itself. Throw a warning.
1548198954Srdivacky      // But wait; there are exceptions!
1549198954Srdivacky      // Exception #1:  The field may not belong to this record.
1550198954Srdivacky      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1551210299Sed      const Expr *base = ME->getBase();
1552198954Srdivacky      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1553198954Srdivacky        // Even though the field matches, it does not belong to this record.
1554198954Srdivacky        return false;
1555198954Srdivacky      }
1556198954Srdivacky      // None of the exceptions triggered; return true to indicate an
1557198954Srdivacky      // uninitialized field was used.
1558198954Srdivacky      *L = ME->getMemberLoc();
1559198954Srdivacky      return true;
1560198954Srdivacky    }
1561221345Sdim  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1562218893Sdim    // sizeof/alignof doesn't reference contents, do not warn.
1563218893Sdim    return false;
1564218893Sdim  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1565218893Sdim    // address-of doesn't reference contents (the pointer may be dereferenced
1566218893Sdim    // in the same expression but it would be rare; and weird).
1567218893Sdim    if (UOE->getOpcode() == UO_AddrOf)
1568218893Sdim      return false;
1569198954Srdivacky  }
1570218893Sdim  for (Stmt::const_child_range it = S->children(); it; ++it) {
1571210299Sed    if (!*it) {
1572210299Sed      // An expression such as 'member(arg ?: "")' may trigger this.
1573198954Srdivacky      continue;
1574198954Srdivacky    }
1575210299Sed    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1576210299Sed      return true;
1577198954Srdivacky  }
1578210299Sed  return false;
1579198954Srdivacky}
1580198954Srdivacky
1581212904SdimMemInitResult
1582218893SdimSema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1583198092Srdivacky                             unsigned NumArgs, SourceLocation IdLoc,
1584200583Srdivacky                             SourceLocation LParenLoc,
1585198092Srdivacky                             SourceLocation RParenLoc) {
1586218893Sdim  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1587218893Sdim  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1588218893Sdim  assert((DirectMember || IndirectMember) &&
1589218893Sdim         "Member must be a FieldDecl or IndirectFieldDecl");
1590218893Sdim
1591218893Sdim  if (Member->isInvalidDecl())
1592218893Sdim    return true;
1593218893Sdim
1594198954Srdivacky  // Diagnose value-uses of fields to initialize themselves, e.g.
1595198954Srdivacky  //   foo(foo)
1596198954Srdivacky  // where foo is not also a parameter to the constructor.
1597198954Srdivacky  // TODO: implement -Wuninitialized and fold this into that framework.
1598198954Srdivacky  for (unsigned i = 0; i < NumArgs; ++i) {
1599198954Srdivacky    SourceLocation L;
1600198954Srdivacky    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1601198954Srdivacky      // FIXME: Return true in the case when other fields are used before being
1602198954Srdivacky      // uninitialized. For example, let this field be the i'th field. When
1603198954Srdivacky      // initializing the i'th field, throw a warning if any of the >= i'th
1604198954Srdivacky      // fields are used, as they are not yet initialized.
1605198954Srdivacky      // Right now we are only handling the case where the i'th field uses
1606198954Srdivacky      // itself in its initializer.
1607198954Srdivacky      Diag(L, diag::warn_field_is_uninit);
1608198954Srdivacky    }
1609198954Srdivacky  }
1610198954Srdivacky
1611198092Srdivacky  bool HasDependentArg = false;
1612198092Srdivacky  for (unsigned i = 0; i < NumArgs; i++)
1613198092Srdivacky    HasDependentArg |= Args[i]->isTypeDependent();
1614198092Srdivacky
1615218893Sdim  Expr *Init;
1616212904Sdim  if (Member->getType()->isDependentType() || HasDependentArg) {
1617203955Srdivacky    // Can't check initialization for a member of dependent type or when
1618203955Srdivacky    // any of the arguments are type-dependent expressions.
1619218893Sdim    Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1620218893Sdim                                       RParenLoc);
1621203955Srdivacky
1622203955Srdivacky    // Erase any temporaries within this evaluation context; we're not
1623203955Srdivacky    // going to track them in the AST, since we'll be rebuilding the
1624203955Srdivacky    // ASTs during template instantiation.
1625203955Srdivacky    ExprTemporaries.erase(
1626203955Srdivacky              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1627203955Srdivacky                          ExprTemporaries.end());
1628218893Sdim  } else {
1629218893Sdim    // Initialize the member.
1630218893Sdim    InitializedEntity MemberEntity =
1631218893Sdim      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1632218893Sdim                   : InitializedEntity::InitializeMember(IndirectMember, 0);
1633218893Sdim    InitializationKind Kind =
1634218893Sdim      InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1635218893Sdim
1636218893Sdim    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1637218893Sdim
1638218893Sdim    ExprResult MemberInit =
1639218893Sdim      InitSeq.Perform(*this, MemberEntity, Kind,
1640218893Sdim                      MultiExprArg(*this, Args, NumArgs), 0);
1641218893Sdim    if (MemberInit.isInvalid())
1642218893Sdim      return true;
1643218893Sdim
1644218893Sdim    CheckImplicitConversions(MemberInit.get(), LParenLoc);
1645218893Sdim
1646218893Sdim    // C++0x [class.base.init]p7:
1647218893Sdim    //   The initialization of each base and member constitutes a
1648218893Sdim    //   full-expression.
1649218893Sdim    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1650218893Sdim    if (MemberInit.isInvalid())
1651218893Sdim      return true;
1652218893Sdim
1653218893Sdim    // If we are in a dependent context, template instantiation will
1654218893Sdim    // perform this type-checking again. Just save the arguments that we
1655218893Sdim    // received in a ParenListExpr.
1656218893Sdim    // FIXME: This isn't quite ideal, since our ASTs don't capture all
1657218893Sdim    // of the information that we have about the member
1658218893Sdim    // initializer. However, deconstructing the ASTs is a dicey process,
1659218893Sdim    // and this approach is far more likely to get the corner cases right.
1660218893Sdim    if (CurContext->isDependentContext())
1661218893Sdim      Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1662218893Sdim                                               RParenLoc);
1663218893Sdim    else
1664218893Sdim      Init = MemberInit.get();
1665193326Sed  }
1666203955Srdivacky
1667218893Sdim  if (DirectMember) {
1668218893Sdim    return new (Context) CXXCtorInitializer(Context, DirectMember,
1669218893Sdim                                                    IdLoc, LParenLoc, Init,
1670203955Srdivacky                                                    RParenLoc);
1671218893Sdim  } else {
1672218893Sdim    return new (Context) CXXCtorInitializer(Context, IndirectMember,
1673218893Sdim                                                    IdLoc, LParenLoc, Init,
1674218893Sdim                                                    RParenLoc);
1675203955Srdivacky  }
1676218893Sdim}
1677203955Srdivacky
1678218893SdimMemInitResult
1679218893SdimSema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1680218893Sdim                                 Expr **Args, unsigned NumArgs,
1681221345Sdim                                 SourceLocation NameLoc,
1682218893Sdim                                 SourceLocation LParenLoc,
1683218893Sdim                                 SourceLocation RParenLoc,
1684221345Sdim                                 CXXRecordDecl *ClassDecl) {
1685218893Sdim  SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1686218893Sdim  if (!LangOpts.CPlusPlus0x)
1687218893Sdim    return Diag(Loc, diag::err_delegation_0x_only)
1688218893Sdim      << TInfo->getTypeLoc().getLocalSourceRange();
1689218893Sdim
1690221345Sdim  // Initialize the object.
1691221345Sdim  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1692221345Sdim                                     QualType(ClassDecl->getTypeForDecl(), 0));
1693221345Sdim  InitializationKind Kind =
1694221345Sdim    InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1695221345Sdim
1696221345Sdim  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1697221345Sdim
1698221345Sdim  ExprResult DelegationInit =
1699221345Sdim    InitSeq.Perform(*this, DelegationEntity, Kind,
1700221345Sdim                    MultiExprArg(*this, Args, NumArgs), 0);
1701221345Sdim  if (DelegationInit.isInvalid())
1702221345Sdim    return true;
1703221345Sdim
1704221345Sdim  CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1705223017Sdim  CXXConstructorDecl *Constructor
1706223017Sdim    = ConExpr->getConstructor();
1707221345Sdim  assert(Constructor && "Delegating constructor with no target?");
1708221345Sdim
1709221345Sdim  CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1710221345Sdim
1711221345Sdim  // C++0x [class.base.init]p7:
1712221345Sdim  //   The initialization of each base and member constitutes a
1713221345Sdim  //   full-expression.
1714221345Sdim  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1715221345Sdim  if (DelegationInit.isInvalid())
1716221345Sdim    return true;
1717221345Sdim
1718221345Sdim  // If we are in a dependent context, template instantiation will
1719221345Sdim  // perform this type-checking again. Just save the arguments that we
1720221345Sdim  // received in a ParenListExpr.
1721221345Sdim  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1722221345Sdim  // of the information that we have about the base
1723221345Sdim  // initializer. However, deconstructing the ASTs is a dicey process,
1724221345Sdim  // and this approach is far more likely to get the corner cases right.
1725221345Sdim  if (CurContext->isDependentContext()) {
1726221345Sdim    ExprResult Init
1727221345Sdim      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1728221345Sdim                                          NumArgs, RParenLoc));
1729221345Sdim    return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1730221345Sdim                                            Constructor, Init.takeAs<Expr>(),
1731221345Sdim                                            RParenLoc);
1732221345Sdim  }
1733221345Sdim
1734221345Sdim  return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1735221345Sdim                                          DelegationInit.takeAs<Expr>(),
1736221345Sdim                                          RParenLoc);
1737198092Srdivacky}
1738198092Srdivacky
1739212904SdimMemInitResult
1740200583SrdivackySema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1741200583Srdivacky                           Expr **Args, unsigned NumArgs,
1742200583Srdivacky                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1743218893Sdim                           CXXRecordDecl *ClassDecl,
1744218893Sdim                           SourceLocation EllipsisLoc) {
1745198092Srdivacky  bool HasDependentArg = false;
1746198092Srdivacky  for (unsigned i = 0; i < NumArgs; i++)
1747198092Srdivacky    HasDependentArg |= Args[i]->isTypeDependent();
1748198092Srdivacky
1749210299Sed  SourceLocation BaseLoc
1750210299Sed    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1751210299Sed
1752210299Sed  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1753210299Sed    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1754210299Sed             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1755210299Sed
1756210299Sed  // C++ [class.base.init]p2:
1757210299Sed  //   [...] Unless the mem-initializer-id names a nonstatic data
1758218893Sdim  //   member of the constructor's class or a direct or virtual base
1759210299Sed  //   of that class, the mem-initializer is ill-formed. A
1760210299Sed  //   mem-initializer-list can initialize a base class using any
1761210299Sed  //   name that denotes that base class type.
1762210299Sed  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1763210299Sed
1764218893Sdim  if (EllipsisLoc.isValid()) {
1765218893Sdim    // This is a pack expansion.
1766218893Sdim    if (!BaseType->containsUnexpandedParameterPack())  {
1767218893Sdim      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1768218893Sdim        << SourceRange(BaseLoc, RParenLoc);
1769218893Sdim
1770218893Sdim      EllipsisLoc = SourceLocation();
1771218893Sdim    }
1772218893Sdim  } else {
1773218893Sdim    // Check for any unexpanded parameter packs.
1774218893Sdim    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1775218893Sdim      return true;
1776218893Sdim
1777218893Sdim    for (unsigned I = 0; I != NumArgs; ++I)
1778218893Sdim      if (DiagnoseUnexpandedParameterPack(Args[I]))
1779218893Sdim        return true;
1780218893Sdim  }
1781218893Sdim
1782210299Sed  // Check for direct and virtual base classes.
1783210299Sed  const CXXBaseSpecifier *DirectBaseSpec = 0;
1784210299Sed  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1785210299Sed  if (!Dependent) {
1786218893Sdim    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1787218893Sdim                                       BaseType))
1788221345Sdim      return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1789221345Sdim                                        LParenLoc, RParenLoc, ClassDecl);
1790218893Sdim
1791210299Sed    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1792210299Sed                        VirtualBaseSpec);
1793210299Sed
1794210299Sed    // C++ [base.class.init]p2:
1795210299Sed    // Unless the mem-initializer-id names a nonstatic data member of the
1796210299Sed    // constructor's class or a direct or virtual base of that class, the
1797210299Sed    // mem-initializer is ill-formed.
1798210299Sed    if (!DirectBaseSpec && !VirtualBaseSpec) {
1799210299Sed      // If the class has any dependent bases, then it's possible that
1800210299Sed      // one of those types will resolve to the same type as
1801210299Sed      // BaseType. Therefore, just treat this as a dependent base
1802210299Sed      // class initialization.  FIXME: Should we try to check the
1803210299Sed      // initialization anyway? It seems odd.
1804210299Sed      if (ClassDecl->hasAnyDependentBases())
1805210299Sed        Dependent = true;
1806210299Sed      else
1807210299Sed        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1808210299Sed          << BaseType << Context.getTypeDeclType(ClassDecl)
1809210299Sed          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1810210299Sed    }
1811210299Sed  }
1812210299Sed
1813210299Sed  if (Dependent) {
1814203955Srdivacky    // Can't check initialization for a base of dependent type or when
1815203955Srdivacky    // any of the arguments are type-dependent expressions.
1816212904Sdim    ExprResult BaseInit
1817203955Srdivacky      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1818203955Srdivacky                                          RParenLoc));
1819198092Srdivacky
1820203955Srdivacky    // Erase any temporaries within this evaluation context; we're not
1821203955Srdivacky    // going to track them in the AST, since we'll be rebuilding the
1822203955Srdivacky    // ASTs during template instantiation.
1823203955Srdivacky    ExprTemporaries.erase(
1824203955Srdivacky              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1825203955Srdivacky                          ExprTemporaries.end());
1826198092Srdivacky
1827218893Sdim    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1828207619Srdivacky                                                    /*IsVirtual=*/false,
1829203955Srdivacky                                                    LParenLoc,
1830203955Srdivacky                                                    BaseInit.takeAs<Expr>(),
1831218893Sdim                                                    RParenLoc,
1832218893Sdim                                                    EllipsisLoc);
1833193326Sed  }
1834193326Sed
1835203955Srdivacky  // C++ [base.class.init]p2:
1836203955Srdivacky  //   If a mem-initializer-id is ambiguous because it designates both
1837203955Srdivacky  //   a direct non-virtual base class and an inherited virtual base
1838203955Srdivacky  //   class, the mem-initializer is ill-formed.
1839203955Srdivacky  if (DirectBaseSpec && VirtualBaseSpec)
1840203955Srdivacky    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1841208600Srdivacky      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1842203955Srdivacky
1843203955Srdivacky  CXXBaseSpecifier *BaseSpec
1844203955Srdivacky    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1845203955Srdivacky  if (!BaseSpec)
1846203955Srdivacky    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1847203955Srdivacky
1848203955Srdivacky  // Initialize the base.
1849203955Srdivacky  InitializedEntity BaseEntity =
1850207619Srdivacky    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1851203955Srdivacky  InitializationKind Kind =
1852203955Srdivacky    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1853203955Srdivacky
1854203955Srdivacky  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1855203955Srdivacky
1856212904Sdim  ExprResult BaseInit =
1857203955Srdivacky    InitSeq.Perform(*this, BaseEntity, Kind,
1858212904Sdim                    MultiExprArg(*this, Args, NumArgs), 0);
1859203955Srdivacky  if (BaseInit.isInvalid())
1860203955Srdivacky    return true;
1861218893Sdim
1862218893Sdim  CheckImplicitConversions(BaseInit.get(), LParenLoc);
1863203955Srdivacky
1864203955Srdivacky  // C++0x [class.base.init]p7:
1865203955Srdivacky  //   The initialization of each base and member constitutes a
1866203955Srdivacky  //   full-expression.
1867218893Sdim  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1868203955Srdivacky  if (BaseInit.isInvalid())
1869203955Srdivacky    return true;
1870203955Srdivacky
1871203955Srdivacky  // If we are in a dependent context, template instantiation will
1872203955Srdivacky  // perform this type-checking again. Just save the arguments that we
1873203955Srdivacky  // received in a ParenListExpr.
1874203955Srdivacky  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1875203955Srdivacky  // of the information that we have about the base
1876203955Srdivacky  // initializer. However, deconstructing the ASTs is a dicey process,
1877203955Srdivacky  // and this approach is far more likely to get the corner cases right.
1878203955Srdivacky  if (CurContext->isDependentContext()) {
1879212904Sdim    ExprResult Init
1880203955Srdivacky      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1881203955Srdivacky                                          RParenLoc));
1882218893Sdim    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1883207619Srdivacky                                                    BaseSpec->isVirtual(),
1884203955Srdivacky                                                    LParenLoc,
1885203955Srdivacky                                                    Init.takeAs<Expr>(),
1886218893Sdim                                                    RParenLoc,
1887218893Sdim                                                    EllipsisLoc);
1888198092Srdivacky  }
1889198092Srdivacky
1890218893Sdim  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1891207619Srdivacky                                                  BaseSpec->isVirtual(),
1892203955Srdivacky                                                  LParenLoc,
1893203955Srdivacky                                                  BaseInit.takeAs<Expr>(),
1894218893Sdim                                                  RParenLoc,
1895218893Sdim                                                  EllipsisLoc);
1896193326Sed}
1897193326Sed
1898207619Srdivacky/// ImplicitInitializerKind - How an implicit base or member initializer should
1899207619Srdivacky/// initialize its base or member.
1900207619Srdivackyenum ImplicitInitializerKind {
1901207619Srdivacky  IIK_Default,
1902207619Srdivacky  IIK_Copy,
1903207619Srdivacky  IIK_Move
1904207619Srdivacky};
1905207619Srdivacky
1906207619Srdivackystatic bool
1907207619SrdivackyBuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1908207619Srdivacky                             ImplicitInitializerKind ImplicitInitKind,
1909207619Srdivacky                             CXXBaseSpecifier *BaseSpec,
1910207619Srdivacky                             bool IsInheritedVirtualBase,
1911218893Sdim                             CXXCtorInitializer *&CXXBaseInit) {
1912207619Srdivacky  InitializedEntity InitEntity
1913207619Srdivacky    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1914207619Srdivacky                                        IsInheritedVirtualBase);
1915207619Srdivacky
1916212904Sdim  ExprResult BaseInit;
1917207619Srdivacky
1918207619Srdivacky  switch (ImplicitInitKind) {
1919207619Srdivacky  case IIK_Default: {
1920207619Srdivacky    InitializationKind InitKind
1921207619Srdivacky      = InitializationKind::CreateDefault(Constructor->getLocation());
1922207619Srdivacky    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1923207619Srdivacky    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1924212904Sdim                               MultiExprArg(SemaRef, 0, 0));
1925207619Srdivacky    break;
1926207619Srdivacky  }
1927207619Srdivacky
1928207619Srdivacky  case IIK_Copy: {
1929207619Srdivacky    ParmVarDecl *Param = Constructor->getParamDecl(0);
1930207619Srdivacky    QualType ParamType = Param->getType().getNonReferenceType();
1931207619Srdivacky
1932207619Srdivacky    Expr *CopyCtorArg =
1933221345Sdim      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1934218893Sdim                          Constructor->getLocation(), ParamType,
1935218893Sdim                          VK_LValue, 0);
1936207619Srdivacky
1937207619Srdivacky    // Cast to the base class to avoid ambiguities.
1938207619Srdivacky    QualType ArgTy =
1939207619Srdivacky      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1940207619Srdivacky                                       ParamType.getQualifiers());
1941207619Srdivacky
1942212904Sdim    CXXCastPath BasePath;
1943212904Sdim    BasePath.push_back(BaseSpec);
1944221345Sdim    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1945221345Sdim                                            CK_UncheckedDerivedToBase,
1946221345Sdim                                            VK_LValue, &BasePath).take();
1947212904Sdim
1948207619Srdivacky    InitializationKind InitKind
1949207619Srdivacky      = InitializationKind::CreateDirect(Constructor->getLocation(),
1950207619Srdivacky                                         SourceLocation(), SourceLocation());
1951207619Srdivacky    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1952207619Srdivacky                                   &CopyCtorArg, 1);
1953207619Srdivacky    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1954212904Sdim                               MultiExprArg(&CopyCtorArg, 1));
1955207619Srdivacky    break;
1956207619Srdivacky  }
1957207619Srdivacky
1958207619Srdivacky  case IIK_Move:
1959207619Srdivacky    assert(false && "Unhandled initializer kind!");
1960207619Srdivacky  }
1961212904Sdim
1962218893Sdim  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1963212904Sdim  if (BaseInit.isInvalid())
1964212904Sdim    return true;
1965207619Srdivacky
1966207619Srdivacky  CXXBaseInit =
1967218893Sdim    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1968207619Srdivacky               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1969207619Srdivacky                                                        SourceLocation()),
1970207619Srdivacky                                             BaseSpec->isVirtual(),
1971207619Srdivacky                                             SourceLocation(),
1972207619Srdivacky                                             BaseInit.takeAs<Expr>(),
1973218893Sdim                                             SourceLocation(),
1974207619Srdivacky                                             SourceLocation());
1975207619Srdivacky
1976207619Srdivacky  return false;
1977207619Srdivacky}
1978207619Srdivacky
1979207619Srdivackystatic bool
1980207619SrdivackyBuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1981207619Srdivacky                               ImplicitInitializerKind ImplicitInitKind,
1982207619Srdivacky                               FieldDecl *Field,
1983218893Sdim                               CXXCtorInitializer *&CXXMemberInit) {
1984208600Srdivacky  if (Field->isInvalidDecl())
1985208600Srdivacky    return true;
1986208600Srdivacky
1987210299Sed  SourceLocation Loc = Constructor->getLocation();
1988210299Sed
1989207619Srdivacky  if (ImplicitInitKind == IIK_Copy) {
1990207619Srdivacky    ParmVarDecl *Param = Constructor->getParamDecl(0);
1991207619Srdivacky    QualType ParamType = Param->getType().getNonReferenceType();
1992207619Srdivacky
1993207619Srdivacky    Expr *MemberExprBase =
1994221345Sdim      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1995218893Sdim                          Loc, ParamType, VK_LValue, 0);
1996208600Srdivacky
1997208600Srdivacky    // Build a reference to this field within the parameter.
1998208600Srdivacky    CXXScopeSpec SS;
1999208600Srdivacky    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2000208600Srdivacky                              Sema::LookupMemberName);
2001208600Srdivacky    MemberLookup.addDecl(Field, AS_public);
2002208600Srdivacky    MemberLookup.resolveKind();
2003212904Sdim    ExprResult CopyCtorArg
2004212904Sdim      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2005208600Srdivacky                                         ParamType, Loc,
2006208600Srdivacky                                         /*IsArrow=*/false,
2007208600Srdivacky                                         SS,
2008208600Srdivacky                                         /*FirstQualifierInScope=*/0,
2009208600Srdivacky                                         MemberLookup,
2010208600Srdivacky                                         /*TemplateArgs=*/0);
2011208600Srdivacky    if (CopyCtorArg.isInvalid())
2012208600Srdivacky      return true;
2013207619Srdivacky
2014208600Srdivacky    // When the field we are copying is an array, create index variables for
2015208600Srdivacky    // each dimension of the array. We use these index variables to subscript
2016208600Srdivacky    // the source array, and other clients (e.g., CodeGen) will perform the
2017208600Srdivacky    // necessary iteration with these index variables.
2018208600Srdivacky    llvm::SmallVector<VarDecl *, 4> IndexVariables;
2019208600Srdivacky    QualType BaseType = Field->getType();
2020208600Srdivacky    QualType SizeType = SemaRef.Context.getSizeType();
2021208600Srdivacky    while (const ConstantArrayType *Array
2022208600Srdivacky                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2023208600Srdivacky      // Create the iteration variable for this array index.
2024208600Srdivacky      IdentifierInfo *IterationVarName = 0;
2025208600Srdivacky      {
2026208600Srdivacky        llvm::SmallString<8> Str;
2027208600Srdivacky        llvm::raw_svector_ostream OS(Str);
2028208600Srdivacky        OS << "__i" << IndexVariables.size();
2029208600Srdivacky        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2030208600Srdivacky      }
2031208600Srdivacky      VarDecl *IterationVar
2032221345Sdim        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2033208600Srdivacky                          IterationVarName, SizeType,
2034208600Srdivacky                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2035212904Sdim                          SC_None, SC_None);
2036208600Srdivacky      IndexVariables.push_back(IterationVar);
2037208600Srdivacky
2038208600Srdivacky      // Create a reference to the iteration variable.
2039212904Sdim      ExprResult IterationVarRef
2040218893Sdim        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2041208600Srdivacky      assert(!IterationVarRef.isInvalid() &&
2042208600Srdivacky             "Reference to invented variable cannot fail!");
2043208600Srdivacky
2044208600Srdivacky      // Subscript the array with this iteration variable.
2045212904Sdim      CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
2046208600Srdivacky                                                            Loc,
2047212904Sdim                                                        IterationVarRef.take(),
2048208600Srdivacky                                                            Loc);
2049208600Srdivacky      if (CopyCtorArg.isInvalid())
2050208600Srdivacky        return true;
2051208600Srdivacky
2052208600Srdivacky      BaseType = Array->getElementType();
2053208600Srdivacky    }
2054207619Srdivacky
2055208600Srdivacky    // Construct the entity that we will be initializing. For an array, this
2056208600Srdivacky    // will be first element in the array, which may require several levels
2057208600Srdivacky    // of array-subscript entities.
2058208600Srdivacky    llvm::SmallVector<InitializedEntity, 4> Entities;
2059208600Srdivacky    Entities.reserve(1 + IndexVariables.size());
2060208600Srdivacky    Entities.push_back(InitializedEntity::InitializeMember(Field));
2061208600Srdivacky    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2062208600Srdivacky      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2063208600Srdivacky                                                              0,
2064208600Srdivacky                                                              Entities.back()));
2065207619Srdivacky
2066208600Srdivacky    // Direct-initialize to use the copy constructor.
2067207619Srdivacky    InitializationKind InitKind =
2068208600Srdivacky      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2069207619Srdivacky
2070208600Srdivacky    Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2071208600Srdivacky    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2072208600Srdivacky                                   &CopyCtorArgE, 1);
2073207619Srdivacky
2074212904Sdim    ExprResult MemberInit
2075208600Srdivacky      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2076212904Sdim                        MultiExprArg(&CopyCtorArgE, 1));
2077218893Sdim    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2078207619Srdivacky    if (MemberInit.isInvalid())
2079207619Srdivacky      return true;
2080208600Srdivacky
2081208600Srdivacky    CXXMemberInit
2082218893Sdim      = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
2083208600Srdivacky                                           MemberInit.takeAs<Expr>(), Loc,
2084208600Srdivacky                                           IndexVariables.data(),
2085208600Srdivacky                                           IndexVariables.size());
2086207619Srdivacky    return false;
2087207619Srdivacky  }
2088207619Srdivacky
2089207619Srdivacky  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2090207619Srdivacky
2091207619Srdivacky  QualType FieldBaseElementType =
2092207619Srdivacky    SemaRef.Context.getBaseElementType(Field->getType());
2093207619Srdivacky
2094207619Srdivacky  if (FieldBaseElementType->isRecordType()) {
2095207619Srdivacky    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2096207619Srdivacky    InitializationKind InitKind =
2097210299Sed      InitializationKind::CreateDefault(Loc);
2098207619Srdivacky
2099207619Srdivacky    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2100212904Sdim    ExprResult MemberInit =
2101212904Sdim      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2102212904Sdim
2103218893Sdim    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2104212904Sdim    if (MemberInit.isInvalid())
2105212904Sdim      return true;
2106207619Srdivacky
2107207619Srdivacky    CXXMemberInit =
2108218893Sdim      new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2109210299Sed                                                       Field, Loc, Loc,
2110212904Sdim                                                       MemberInit.get(),
2111210299Sed                                                       Loc);
2112207619Srdivacky    return false;
2113207619Srdivacky  }
2114207619Srdivacky
2115223017Sdim  if (!Field->getParent()->isUnion()) {
2116223017Sdim    if (FieldBaseElementType->isReferenceType()) {
2117223017Sdim      SemaRef.Diag(Constructor->getLocation(),
2118223017Sdim                   diag::err_uninitialized_member_in_ctor)
2119223017Sdim      << (int)Constructor->isImplicit()
2120223017Sdim      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2121223017Sdim      << 0 << Field->getDeclName();
2122223017Sdim      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2123223017Sdim      return true;
2124223017Sdim    }
2125207619Srdivacky
2126223017Sdim    if (FieldBaseElementType.isConstQualified()) {
2127223017Sdim      SemaRef.Diag(Constructor->getLocation(),
2128223017Sdim                   diag::err_uninitialized_member_in_ctor)
2129223017Sdim      << (int)Constructor->isImplicit()
2130223017Sdim      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2131223017Sdim      << 1 << Field->getDeclName();
2132223017Sdim      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2133223017Sdim      return true;
2134223017Sdim    }
2135207619Srdivacky  }
2136207619Srdivacky
2137207619Srdivacky  // Nothing to initialize.
2138207619Srdivacky  CXXMemberInit = 0;
2139207619Srdivacky  return false;
2140207619Srdivacky}
2141208600Srdivacky
2142208600Srdivackynamespace {
2143208600Srdivackystruct BaseAndFieldInfo {
2144208600Srdivacky  Sema &S;
2145208600Srdivacky  CXXConstructorDecl *Ctor;
2146208600Srdivacky  bool AnyErrorsInInits;
2147208600Srdivacky  ImplicitInitializerKind IIK;
2148218893Sdim  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2149218893Sdim  llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2150208600Srdivacky
2151208600Srdivacky  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2152208600Srdivacky    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2153208600Srdivacky    // FIXME: Handle implicit move constructors.
2154208600Srdivacky    if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2155208600Srdivacky      IIK = IIK_Copy;
2156208600Srdivacky    else
2157208600Srdivacky      IIK = IIK_Default;
2158208600Srdivacky  }
2159208600Srdivacky};
2160208600Srdivacky}
2161208600Srdivacky
2162223017Sdimstatic bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2163208600Srdivacky                                    FieldDecl *Top, FieldDecl *Field) {
2164208600Srdivacky
2165210299Sed  // Overwhelmingly common case: we have a direct initializer for this field.
2166218893Sdim  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2167218893Sdim    Info.AllToInit.push_back(Init);
2168208600Srdivacky    return false;
2169208600Srdivacky  }
2170208600Srdivacky
2171223017Sdim  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2172223017Sdim  // has a brace-or-equal-initializer, the entity is initialized as specified
2173223017Sdim  // in [dcl.init].
2174223017Sdim  if (Field->hasInClassInitializer()) {
2175223017Sdim    Info.AllToInit.push_back(
2176223017Sdim      new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2177223017Sdim                                               SourceLocation(),
2178223017Sdim                                               SourceLocation(), 0,
2179223017Sdim                                               SourceLocation()));
2180223017Sdim    return false;
2181223017Sdim  }
2182223017Sdim
2183208600Srdivacky  if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2184208600Srdivacky    const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2185208600Srdivacky    assert(FieldClassType && "anonymous struct/union without record type");
2186210299Sed    CXXRecordDecl *FieldClassDecl
2187210299Sed      = cast<CXXRecordDecl>(FieldClassType->getDecl());
2188208600Srdivacky
2189210299Sed    // Even though union members never have non-trivial default
2190210299Sed    // constructions in C++03, we still build member initializers for aggregate
2191210299Sed    // record types which can be union members, and C++0x allows non-trivial
2192210299Sed    // default constructors for union members, so we ensure that only one
2193210299Sed    // member is initialized for these.
2194210299Sed    if (FieldClassDecl->isUnion()) {
2195210299Sed      // First check for an explicit initializer for one field.
2196210299Sed      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2197210299Sed           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2198218893Sdim        if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2199218893Sdim          Info.AllToInit.push_back(Init);
2200208600Srdivacky
2201210299Sed          // Once we've initialized a field of an anonymous union, the union
2202210299Sed          // field in the class is also initialized, so exit immediately.
2203210299Sed          return false;
2204212904Sdim        } else if ((*FA)->isAnonymousStructOrUnion()) {
2205223017Sdim          if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2206212904Sdim            return true;
2207210299Sed        }
2208210299Sed      }
2209210299Sed
2210210299Sed      // Fallthrough and construct a default initializer for the union as
2211210299Sed      // a whole, which can call its default constructor if such a thing exists
2212210299Sed      // (C++0x perhaps). FIXME: It's not clear that this is the correct
2213210299Sed      // behavior going forward with C++0x, when anonymous unions there are
2214210299Sed      // finalized, we should revisit this.
2215210299Sed    } else {
2216210299Sed      // For structs, we simply descend through to initialize all members where
2217210299Sed      // necessary.
2218210299Sed      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2219210299Sed           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2220223017Sdim        if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2221210299Sed          return true;
2222210299Sed      }
2223210299Sed    }
2224208600Srdivacky  }
2225208600Srdivacky
2226208600Srdivacky  // Don't try to build an implicit initializer if there were semantic
2227208600Srdivacky  // errors in any of the initializers (and therefore we might be
2228208600Srdivacky  // missing some that the user actually wrote).
2229223017Sdim  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2230208600Srdivacky    return false;
2231208600Srdivacky
2232218893Sdim  CXXCtorInitializer *Init = 0;
2233208600Srdivacky  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2234208600Srdivacky    return true;
2235208600Srdivacky
2236218893Sdim  if (Init)
2237218893Sdim    Info.AllToInit.push_back(Init);
2238218893Sdim
2239208600Srdivacky  return false;
2240208600Srdivacky}
2241221345Sdim
2242221345Sdimbool
2243221345SdimSema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2244221345Sdim                               CXXCtorInitializer *Initializer) {
2245223017Sdim  assert(Initializer->isDelegatingInitializer());
2246221345Sdim  Constructor->setNumCtorInitializers(1);
2247221345Sdim  CXXCtorInitializer **initializer =
2248221345Sdim    new (Context) CXXCtorInitializer*[1];
2249221345Sdim  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2250221345Sdim  Constructor->setCtorInitializers(initializer);
2251221345Sdim
2252223017Sdim  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2253223017Sdim    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2254223017Sdim    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2255221345Sdim  }
2256221345Sdim
2257223017Sdim  DelegatingCtorDecls.push_back(Constructor);
2258223017Sdim
2259221345Sdim  return false;
2260221345Sdim}
2261207619Srdivacky
2262199482Srdivackybool
2263218893SdimSema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2264218893Sdim                                  CXXCtorInitializer **Initializers,
2265203955Srdivacky                                  unsigned NumInitializers,
2266203955Srdivacky                                  bool AnyErrors) {
2267207619Srdivacky  if (Constructor->getDeclContext()->isDependentContext()) {
2268206084Srdivacky    // Just store the initializers as written, they will be checked during
2269206084Srdivacky    // instantiation.
2270206084Srdivacky    if (NumInitializers > 0) {
2271218893Sdim      Constructor->setNumCtorInitializers(NumInitializers);
2272218893Sdim      CXXCtorInitializer **baseOrMemberInitializers =
2273218893Sdim        new (Context) CXXCtorInitializer*[NumInitializers];
2274206084Srdivacky      memcpy(baseOrMemberInitializers, Initializers,
2275218893Sdim             NumInitializers * sizeof(CXXCtorInitializer*));
2276218893Sdim      Constructor->setCtorInitializers(baseOrMemberInitializers);
2277206084Srdivacky    }
2278206084Srdivacky
2279206084Srdivacky    return false;
2280206084Srdivacky  }
2281206084Srdivacky
2282208600Srdivacky  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2283207619Srdivacky
2284198092Srdivacky  // We need to build the initializer AST according to order of construction
2285198092Srdivacky  // and not what user specified in the Initializers list.
2286206084Srdivacky  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2287206084Srdivacky  if (!ClassDecl)
2288206084Srdivacky    return true;
2289206084Srdivacky
2290199482Srdivacky  bool HadError = false;
2291198092Srdivacky
2292198092Srdivacky  for (unsigned i = 0; i < NumInitializers; i++) {
2293218893Sdim    CXXCtorInitializer *Member = Initializers[i];
2294206084Srdivacky
2295206084Srdivacky    if (Member->isBaseInitializer())
2296208600Srdivacky      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2297206084Srdivacky    else
2298218893Sdim      Info.AllBaseFields[Member->getAnyMember()] = Member;
2299198092Srdivacky  }
2300198092Srdivacky
2301207619Srdivacky  // Keep track of the direct virtual bases.
2302207619Srdivacky  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2303207619Srdivacky  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2304207619Srdivacky       E = ClassDecl->bases_end(); I != E; ++I) {
2305207619Srdivacky    if (I->isVirtual())
2306207619Srdivacky      DirectVBases.insert(I);
2307207619Srdivacky  }
2308198092Srdivacky
2309206084Srdivacky  // Push virtual bases before others.
2310206084Srdivacky  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2311206084Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2312206084Srdivacky
2313218893Sdim    if (CXXCtorInitializer *Value
2314208600Srdivacky        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2315208600Srdivacky      Info.AllToInit.push_back(Value);
2316206084Srdivacky    } else if (!AnyErrors) {
2317207619Srdivacky      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2318218893Sdim      CXXCtorInitializer *CXXBaseInit;
2319208600Srdivacky      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2320207619Srdivacky                                       VBase, IsInheritedVirtualBase,
2321207619Srdivacky                                       CXXBaseInit)) {
2322206084Srdivacky        HadError = true;
2323198092Srdivacky        continue;
2324206084Srdivacky      }
2325207619Srdivacky
2326208600Srdivacky      Info.AllToInit.push_back(CXXBaseInit);
2327198092Srdivacky    }
2328206084Srdivacky  }
2329198092Srdivacky
2330208600Srdivacky  // Non-virtual bases.
2331206084Srdivacky  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2332206084Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
2333206084Srdivacky    // Virtuals are in the virtual base list and already constructed.
2334206084Srdivacky    if (Base->isVirtual())
2335206084Srdivacky      continue;
2336206084Srdivacky
2337218893Sdim    if (CXXCtorInitializer *Value
2338208600Srdivacky          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2339208600Srdivacky      Info.AllToInit.push_back(Value);
2340206084Srdivacky    } else if (!AnyErrors) {
2341218893Sdim      CXXCtorInitializer *CXXBaseInit;
2342208600Srdivacky      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2343207619Srdivacky                                       Base, /*IsInheritedVirtualBase=*/false,
2344207619Srdivacky                                       CXXBaseInit)) {
2345206084Srdivacky        HadError = true;
2346198092Srdivacky        continue;
2347198092Srdivacky      }
2348206084Srdivacky
2349208600Srdivacky      Info.AllToInit.push_back(CXXBaseInit);
2350198092Srdivacky    }
2351198092Srdivacky  }
2352198092Srdivacky
2353208600Srdivacky  // Fields.
2354198092Srdivacky  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2355198092Srdivacky       E = ClassDecl->field_end(); Field != E; ++Field) {
2356208600Srdivacky    if ((*Field)->getType()->isIncompleteArrayType()) {
2357208600Srdivacky      assert(ClassDecl->hasFlexibleArrayMember() &&
2358208600Srdivacky             "Incomplete array type is not valid");
2359198092Srdivacky      continue;
2360198092Srdivacky    }
2361223017Sdim    if (CollectFieldInitializer(*this, Info, *Field, *Field))
2362199482Srdivacky      HadError = true;
2363198092Srdivacky  }
2364198092Srdivacky
2365208600Srdivacky  NumInitializers = Info.AllToInit.size();
2366198092Srdivacky  if (NumInitializers > 0) {
2367218893Sdim    Constructor->setNumCtorInitializers(NumInitializers);
2368218893Sdim    CXXCtorInitializer **baseOrMemberInitializers =
2369218893Sdim      new (Context) CXXCtorInitializer*[NumInitializers];
2370208600Srdivacky    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2371218893Sdim           NumInitializers * sizeof(CXXCtorInitializer*));
2372218893Sdim    Constructor->setCtorInitializers(baseOrMemberInitializers);
2373205219Srdivacky
2374205408Srdivacky    // Constructors implicitly reference the base and member
2375205408Srdivacky    // destructors.
2376205408Srdivacky    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2377205408Srdivacky                                           Constructor->getParent());
2378198092Srdivacky  }
2379198092Srdivacky
2380199482Srdivacky  return HadError;
2381198092Srdivacky}
2382198092Srdivacky
2383198092Srdivackystatic void *GetKeyForTopLevelField(FieldDecl *Field) {
2384198092Srdivacky  // For anonymous unions, use the class declaration as the key.
2385198092Srdivacky  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2386198092Srdivacky    if (RT->getDecl()->isAnonymousStructOrUnion())
2387198092Srdivacky      return static_cast<void *>(RT->getDecl());
2388198092Srdivacky  }
2389198092Srdivacky  return static_cast<void *>(Field);
2390198092Srdivacky}
2391198092Srdivacky
2392206084Srdivackystatic void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2393218893Sdim  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2394198092Srdivacky}
2395198092Srdivacky
2396206084Srdivackystatic void *GetKeyForMember(ASTContext &Context,
2397218893Sdim                             CXXCtorInitializer *Member) {
2398218893Sdim  if (!Member->isAnyMemberInitializer())
2399206084Srdivacky    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2400206084Srdivacky
2401198092Srdivacky  // For fields injected into the class via declaration of an anonymous union,
2402198092Srdivacky  // use its anonymous union class declaration as the unique key.
2403218893Sdim  FieldDecl *Field = Member->getAnyMember();
2404218893Sdim
2405207619Srdivacky  // If the field is a member of an anonymous struct or union, our key
2406207619Srdivacky  // is the anonymous record decl that's a direct child of the class.
2407206084Srdivacky  RecordDecl *RD = Field->getParent();
2408207619Srdivacky  if (RD->isAnonymousStructOrUnion()) {
2409207619Srdivacky    while (true) {
2410207619Srdivacky      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2411207619Srdivacky      if (Parent->isAnonymousStructOrUnion())
2412207619Srdivacky        RD = Parent;
2413207619Srdivacky      else
2414207619Srdivacky        break;
2415207619Srdivacky    }
2416207619Srdivacky
2417206084Srdivacky    return static_cast<void *>(RD);
2418207619Srdivacky  }
2419198092Srdivacky
2420206084Srdivacky  return static_cast<void *>(Field);
2421198092Srdivacky}
2422198092Srdivacky
2423206084Srdivackystatic void
2424206084SrdivackyDiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2425206084Srdivacky                                  const CXXConstructorDecl *Constructor,
2426218893Sdim                                  CXXCtorInitializer **Inits,
2427207619Srdivacky                                  unsigned NumInits) {
2428207619Srdivacky  if (Constructor->getDeclContext()->isDependentContext())
2429198092Srdivacky    return;
2430198092Srdivacky
2431218893Sdim  // Don't check initializers order unless the warning is enabled at the
2432218893Sdim  // location of at least one initializer.
2433218893Sdim  bool ShouldCheckOrder = false;
2434218893Sdim  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2435218893Sdim    CXXCtorInitializer *Init = Inits[InitIndex];
2436218893Sdim    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2437218893Sdim                                         Init->getSourceLocation())
2438218893Sdim          != Diagnostic::Ignored) {
2439218893Sdim      ShouldCheckOrder = true;
2440218893Sdim      break;
2441218893Sdim    }
2442218893Sdim  }
2443218893Sdim  if (!ShouldCheckOrder)
2444198092Srdivacky    return;
2445206084Srdivacky
2446207619Srdivacky  // Build the list of bases and members in the order that they'll
2447207619Srdivacky  // actually be initialized.  The explicit initializers should be in
2448207619Srdivacky  // this same order but may be missing things.
2449207619Srdivacky  llvm::SmallVector<const void*, 32> IdealInitKeys;
2450198092Srdivacky
2451206084Srdivacky  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2452206084Srdivacky
2453207619Srdivacky  // 1. Virtual bases.
2454206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator VBase =
2455198092Srdivacky       ClassDecl->vbases_begin(),
2456198092Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2457207619Srdivacky    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2458198092Srdivacky
2459207619Srdivacky  // 2. Non-virtual bases.
2460206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2461198092Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
2462198092Srdivacky    if (Base->isVirtual())
2463198092Srdivacky      continue;
2464207619Srdivacky    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2465198092Srdivacky  }
2466198092Srdivacky
2467207619Srdivacky  // 3. Direct fields.
2468198092Srdivacky  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2469198092Srdivacky       E = ClassDecl->field_end(); Field != E; ++Field)
2470207619Srdivacky    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2471198092Srdivacky
2472207619Srdivacky  unsigned NumIdealInits = IdealInitKeys.size();
2473207619Srdivacky  unsigned IdealIndex = 0;
2474198092Srdivacky
2475218893Sdim  CXXCtorInitializer *PrevInit = 0;
2476207619Srdivacky  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2477218893Sdim    CXXCtorInitializer *Init = Inits[InitIndex];
2478218893Sdim    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2479207619Srdivacky
2480207619Srdivacky    // Scan forward to try to find this initializer in the idealized
2481207619Srdivacky    // initializers list.
2482207619Srdivacky    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2483207619Srdivacky      if (InitKey == IdealInitKeys[IdealIndex])
2484198092Srdivacky        break;
2485207619Srdivacky
2486207619Srdivacky    // If we didn't find this initializer, it must be because we
2487207619Srdivacky    // scanned past it on a previous iteration.  That can only
2488207619Srdivacky    // happen if we're out of order;  emit a warning.
2489208600Srdivacky    if (IdealIndex == NumIdealInits && PrevInit) {
2490207619Srdivacky      Sema::SemaDiagnosticBuilder D =
2491207619Srdivacky        SemaRef.Diag(PrevInit->getSourceLocation(),
2492207619Srdivacky                     diag::warn_initializer_out_of_order);
2493207619Srdivacky
2494218893Sdim      if (PrevInit->isAnyMemberInitializer())
2495218893Sdim        D << 0 << PrevInit->getAnyMember()->getDeclName();
2496207619Srdivacky      else
2497207619Srdivacky        D << 1 << PrevInit->getBaseClassInfo()->getType();
2498207619Srdivacky
2499218893Sdim      if (Init->isAnyMemberInitializer())
2500218893Sdim        D << 0 << Init->getAnyMember()->getDeclName();
2501207619Srdivacky      else
2502207619Srdivacky        D << 1 << Init->getBaseClassInfo()->getType();
2503207619Srdivacky
2504207619Srdivacky      // Move back to the initializer's location in the ideal list.
2505207619Srdivacky      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2506207619Srdivacky        if (InitKey == IdealInitKeys[IdealIndex])
2507198092Srdivacky          break;
2508207619Srdivacky
2509207619Srdivacky      assert(IdealIndex != NumIdealInits &&
2510207619Srdivacky             "initializer not found in initializer list");
2511198092Srdivacky    }
2512207619Srdivacky
2513207619Srdivacky    PrevInit = Init;
2514198092Srdivacky  }
2515198092Srdivacky}
2516198092Srdivacky
2517207619Srdivackynamespace {
2518207619Srdivackybool CheckRedundantInit(Sema &S,
2519218893Sdim                        CXXCtorInitializer *Init,
2520218893Sdim                        CXXCtorInitializer *&PrevInit) {
2521207619Srdivacky  if (!PrevInit) {
2522207619Srdivacky    PrevInit = Init;
2523207619Srdivacky    return false;
2524207619Srdivacky  }
2525207619Srdivacky
2526207619Srdivacky  if (FieldDecl *Field = Init->getMember())
2527207619Srdivacky    S.Diag(Init->getSourceLocation(),
2528207619Srdivacky           diag::err_multiple_mem_initialization)
2529207619Srdivacky      << Field->getDeclName()
2530207619Srdivacky      << Init->getSourceRange();
2531207619Srdivacky  else {
2532218893Sdim    const Type *BaseClass = Init->getBaseClass();
2533207619Srdivacky    assert(BaseClass && "neither field nor base");
2534207619Srdivacky    S.Diag(Init->getSourceLocation(),
2535207619Srdivacky           diag::err_multiple_base_initialization)
2536207619Srdivacky      << QualType(BaseClass, 0)
2537207619Srdivacky      << Init->getSourceRange();
2538207619Srdivacky  }
2539207619Srdivacky  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2540207619Srdivacky    << 0 << PrevInit->getSourceRange();
2541207619Srdivacky
2542207619Srdivacky  return true;
2543207619Srdivacky}
2544207619Srdivacky
2545218893Sdimtypedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2546207619Srdivackytypedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2547207619Srdivacky
2548207619Srdivackybool CheckRedundantUnionInit(Sema &S,
2549218893Sdim                             CXXCtorInitializer *Init,
2550207619Srdivacky                             RedundantUnionMap &Unions) {
2551218893Sdim  FieldDecl *Field = Init->getAnyMember();
2552207619Srdivacky  RecordDecl *Parent = Field->getParent();
2553207619Srdivacky  if (!Parent->isAnonymousStructOrUnion())
2554207619Srdivacky    return false;
2555207619Srdivacky
2556207619Srdivacky  NamedDecl *Child = Field;
2557207619Srdivacky  do {
2558207619Srdivacky    if (Parent->isUnion()) {
2559207619Srdivacky      UnionEntry &En = Unions[Parent];
2560207619Srdivacky      if (En.first && En.first != Child) {
2561207619Srdivacky        S.Diag(Init->getSourceLocation(),
2562207619Srdivacky               diag::err_multiple_mem_union_initialization)
2563207619Srdivacky          << Field->getDeclName()
2564207619Srdivacky          << Init->getSourceRange();
2565207619Srdivacky        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2566207619Srdivacky          << 0 << En.second->getSourceRange();
2567207619Srdivacky        return true;
2568207619Srdivacky      } else if (!En.first) {
2569207619Srdivacky        En.first = Child;
2570207619Srdivacky        En.second = Init;
2571207619Srdivacky      }
2572207619Srdivacky    }
2573207619Srdivacky
2574207619Srdivacky    Child = Parent;
2575207619Srdivacky    Parent = cast<RecordDecl>(Parent->getDeclContext());
2576207619Srdivacky  } while (Parent->isAnonymousStructOrUnion());
2577207619Srdivacky
2578207619Srdivacky  return false;
2579207619Srdivacky}
2580207619Srdivacky}
2581207619Srdivacky
2582206084Srdivacky/// ActOnMemInitializers - Handle the member initializers for a constructor.
2583212904Sdimvoid Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2584206084Srdivacky                                SourceLocation ColonLoc,
2585206084Srdivacky                                MemInitTy **meminits, unsigned NumMemInits,
2586206084Srdivacky                                bool AnyErrors) {
2587206084Srdivacky  if (!ConstructorDecl)
2588206084Srdivacky    return;
2589206084Srdivacky
2590206084Srdivacky  AdjustDeclIfTemplate(ConstructorDecl);
2591206084Srdivacky
2592206084Srdivacky  CXXConstructorDecl *Constructor
2593212904Sdim    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2594206084Srdivacky
2595206084Srdivacky  if (!Constructor) {
2596206084Srdivacky    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2597206084Srdivacky    return;
2598206084Srdivacky  }
2599206084Srdivacky
2600218893Sdim  CXXCtorInitializer **MemInits =
2601218893Sdim    reinterpret_cast<CXXCtorInitializer **>(meminits);
2602207619Srdivacky
2603207619Srdivacky  // Mapping for the duplicate initializers check.
2604207619Srdivacky  // For member initializers, this is keyed with a FieldDecl*.
2605207619Srdivacky  // For base initializers, this is keyed with a Type*.
2606218893Sdim  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2607207619Srdivacky
2608207619Srdivacky  // Mapping for the inconsistent anonymous-union initializers check.
2609207619Srdivacky  RedundantUnionMap MemberUnions;
2610207619Srdivacky
2611206084Srdivacky  bool HadError = false;
2612206084Srdivacky  for (unsigned i = 0; i < NumMemInits; i++) {
2613218893Sdim    CXXCtorInitializer *Init = MemInits[i];
2614206084Srdivacky
2615208600Srdivacky    // Set the source order index.
2616208600Srdivacky    Init->setSourceOrder(i);
2617208600Srdivacky
2618218893Sdim    if (Init->isAnyMemberInitializer()) {
2619218893Sdim      FieldDecl *Field = Init->getAnyMember();
2620207619Srdivacky      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2621207619Srdivacky          CheckRedundantUnionInit(*this, Init, MemberUnions))
2622207619Srdivacky        HadError = true;
2623221345Sdim    } else if (Init->isBaseInitializer()) {
2624207619Srdivacky      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2625207619Srdivacky      if (CheckRedundantInit(*this, Init, Members[Key]))
2626207619Srdivacky        HadError = true;
2627221345Sdim    } else {
2628221345Sdim      assert(Init->isDelegatingInitializer());
2629221345Sdim      // This must be the only initializer
2630221345Sdim      if (i != 0 || NumMemInits > 1) {
2631221345Sdim        Diag(MemInits[0]->getSourceLocation(),
2632221345Sdim             diag::err_delegating_initializer_alone)
2633221345Sdim          << MemInits[0]->getSourceRange();
2634221345Sdim        HadError = true;
2635221345Sdim        // We will treat this as being the only initializer.
2636221345Sdim      }
2637223017Sdim      SetDelegatingInitializer(Constructor, MemInits[i]);
2638221345Sdim      // Return immediately as the initializer is set.
2639221345Sdim      return;
2640206084Srdivacky    }
2641206084Srdivacky  }
2642206084Srdivacky
2643206084Srdivacky  if (HadError)
2644206084Srdivacky    return;
2645206084Srdivacky
2646206084Srdivacky  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2647206084Srdivacky
2648218893Sdim  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2649206084Srdivacky}
2650206084Srdivacky
2651198092Srdivackyvoid
2652205408SrdivackySema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2653205408Srdivacky                                             CXXRecordDecl *ClassDecl) {
2654205408Srdivacky  // Ignore dependent contexts.
2655205408Srdivacky  if (ClassDecl->isDependentContext())
2656199482Srdivacky    return;
2657205219Srdivacky
2658205219Srdivacky  // FIXME: all the access-control diagnostics are positioned on the
2659205219Srdivacky  // field/base declaration.  That's probably good; that said, the
2660205219Srdivacky  // user might reasonably want to know why the destructor is being
2661205219Srdivacky  // emitted, and we currently don't say.
2662199482Srdivacky
2663199482Srdivacky  // Non-static data members.
2664199482Srdivacky  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2665199482Srdivacky       E = ClassDecl->field_end(); I != E; ++I) {
2666199482Srdivacky    FieldDecl *Field = *I;
2667208600Srdivacky    if (Field->isInvalidDecl())
2668208600Srdivacky      continue;
2669199482Srdivacky    QualType FieldType = Context.getBaseElementType(Field->getType());
2670199482Srdivacky
2671199482Srdivacky    const RecordType* RT = FieldType->getAs<RecordType>();
2672199482Srdivacky    if (!RT)
2673195341Sed      continue;
2674199482Srdivacky
2675199482Srdivacky    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2676221345Sdim    if (FieldClassDecl->isInvalidDecl())
2677221345Sdim      continue;
2678199482Srdivacky    if (FieldClassDecl->hasTrivialDestructor())
2679198092Srdivacky      continue;
2680198092Srdivacky
2681210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2682221345Sdim    assert(Dtor && "No dtor found for FieldClassDecl!");
2683205219Srdivacky    CheckDestructorAccess(Field->getLocation(), Dtor,
2684206084Srdivacky                          PDiag(diag::err_access_dtor_field)
2685205219Srdivacky                            << Field->getDeclName()
2686205219Srdivacky                            << FieldType);
2687205219Srdivacky
2688205408Srdivacky    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2689198092Srdivacky  }
2690199482Srdivacky
2691205219Srdivacky  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2692205219Srdivacky
2693199482Srdivacky  // Bases.
2694199482Srdivacky  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2695198092Srdivacky       E = ClassDecl->bases_end(); Base != E; ++Base) {
2696205219Srdivacky    // Bases are always records in a well-formed non-dependent class.
2697205219Srdivacky    const RecordType *RT = Base->getType()->getAs<RecordType>();
2698205219Srdivacky
2699205219Srdivacky    // Remember direct virtual bases.
2700198092Srdivacky    if (Base->isVirtual())
2701205219Srdivacky      DirectVirtualBases.insert(RT);
2702199482Srdivacky
2703221345Sdim    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2704221345Sdim    // If our base class is invalid, we probably can't get its dtor anyway.
2705221345Sdim    if (BaseClassDecl->isInvalidDecl())
2706221345Sdim      continue;
2707199482Srdivacky    // Ignore trivial destructors.
2708199482Srdivacky    if (BaseClassDecl->hasTrivialDestructor())
2709198092Srdivacky      continue;
2710205219Srdivacky
2711210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2712221345Sdim    assert(Dtor && "No dtor found for BaseClassDecl!");
2713205219Srdivacky
2714205219Srdivacky    // FIXME: caret should be on the start of the class name
2715205219Srdivacky    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2716206084Srdivacky                          PDiag(diag::err_access_dtor_base)
2717205219Srdivacky                            << Base->getType()
2718205219Srdivacky                            << Base->getSourceRange());
2719199482Srdivacky
2720205408Srdivacky    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2721199482Srdivacky  }
2722199482Srdivacky
2723199482Srdivacky  // Virtual bases.
2724199482Srdivacky  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2725199482Srdivacky       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2726205219Srdivacky
2727205219Srdivacky    // Bases are always records in a well-formed non-dependent class.
2728205219Srdivacky    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2729205219Srdivacky
2730205219Srdivacky    // Ignore direct virtual bases.
2731205219Srdivacky    if (DirectVirtualBases.count(RT))
2732205219Srdivacky      continue;
2733205219Srdivacky
2734221345Sdim    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2735221345Sdim    // If our base class is invalid, we probably can't get its dtor anyway.
2736221345Sdim    if (BaseClassDecl->isInvalidDecl())
2737221345Sdim      continue;
2738199482Srdivacky    // Ignore trivial destructors.
2739198092Srdivacky    if (BaseClassDecl->hasTrivialDestructor())
2740198092Srdivacky      continue;
2741205219Srdivacky
2742210299Sed    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2743221345Sdim    assert(Dtor && "No dtor found for BaseClassDecl!");
2744205219Srdivacky    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2745206084Srdivacky                          PDiag(diag::err_access_dtor_vbase)
2746205219Srdivacky                            << VBase->getType());
2747205219Srdivacky
2748205408Srdivacky    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2749198092Srdivacky  }
2750193326Sed}
2751193326Sed
2752212904Sdimvoid Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2753198092Srdivacky  if (!CDtorDecl)
2754198092Srdivacky    return;
2755198092Srdivacky
2756198092Srdivacky  if (CXXConstructorDecl *Constructor
2757212904Sdim      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2758218893Sdim    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2759198092Srdivacky}
2760198092Srdivacky
2761198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2762212904Sdim                                  unsigned DiagID, AbstractDiagSelID SelID) {
2763198092Srdivacky  if (SelID == -1)
2764212904Sdim    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2765198092Srdivacky  else
2766212904Sdim    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2767198092Srdivacky}
2768198092Srdivacky
2769198092Srdivackybool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2770212904Sdim                                  const PartialDiagnostic &PD) {
2771193326Sed  if (!getLangOptions().CPlusPlus)
2772193326Sed    return false;
2773198092Srdivacky
2774193326Sed  if (const ArrayType *AT = Context.getAsArrayType(T))
2775212904Sdim    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2776198092Srdivacky
2777198092Srdivacky  if (const PointerType *PT = T->getAs<PointerType>()) {
2778193326Sed    // Find the innermost pointer type.
2779198092Srdivacky    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2780193326Sed      PT = T;
2781198092Srdivacky
2782193326Sed    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2783212904Sdim      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2784193326Sed  }
2785198092Srdivacky
2786198092Srdivacky  const RecordType *RT = T->getAs<RecordType>();
2787193326Sed  if (!RT)
2788193326Sed    return false;
2789198092Srdivacky
2790203955Srdivacky  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2791193326Sed
2792212904Sdim  // We can't answer whether something is abstract until it has a
2793212904Sdim  // definition.  If it's currently being defined, we'll walk back
2794212904Sdim  // over all the declarations when we have a full definition.
2795212904Sdim  const CXXRecordDecl *Def = RD->getDefinition();
2796212904Sdim  if (!Def || Def->isBeingDefined())
2797193326Sed    return false;
2798198092Srdivacky
2799193326Sed  if (!RD->isAbstract())
2800193326Sed    return false;
2801198092Srdivacky
2802198092Srdivacky  Diag(Loc, PD) << RD->getDeclName();
2803212904Sdim  DiagnoseAbstractType(RD);
2804198092Srdivacky
2805212904Sdim  return true;
2806212904Sdim}
2807212904Sdim
2808212904Sdimvoid Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2809212904Sdim  // Check if we've already emitted the list of pure virtual functions
2810212904Sdim  // for this class.
2811193326Sed  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2812212904Sdim    return;
2813198092Srdivacky
2814206084Srdivacky  CXXFinalOverriderMap FinalOverriders;
2815206084Srdivacky  RD->getFinalOverriders(FinalOverriders);
2816198092Srdivacky
2817210299Sed  // Keep a set of seen pure methods so we won't diagnose the same method
2818210299Sed  // more than once.
2819210299Sed  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2820210299Sed
2821206084Srdivacky  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2822206084Srdivacky                                   MEnd = FinalOverriders.end();
2823206084Srdivacky       M != MEnd;
2824206084Srdivacky       ++M) {
2825206084Srdivacky    for (OverridingMethods::iterator SO = M->second.begin(),
2826206084Srdivacky                                  SOEnd = M->second.end();
2827206084Srdivacky         SO != SOEnd; ++SO) {
2828206084Srdivacky      // C++ [class.abstract]p4:
2829206084Srdivacky      //   A class is abstract if it contains or inherits at least one
2830206084Srdivacky      //   pure virtual function for which the final overrider is pure
2831206084Srdivacky      //   virtual.
2832198092Srdivacky
2833206084Srdivacky      //
2834206084Srdivacky      if (SO->second.size() != 1)
2835206084Srdivacky        continue;
2836206084Srdivacky
2837206084Srdivacky      if (!SO->second.front().Method->isPure())
2838206084Srdivacky        continue;
2839206084Srdivacky
2840210299Sed      if (!SeenPureMethods.insert(SO->second.front().Method))
2841210299Sed        continue;
2842210299Sed
2843206084Srdivacky      Diag(SO->second.front().Method->getLocation(),
2844206084Srdivacky           diag::note_pure_virtual_function)
2845218893Sdim        << SO->second.front().Method->getDeclName() << RD->getDeclName();
2846206084Srdivacky    }
2847193326Sed  }
2848193326Sed
2849193326Sed  if (!PureVirtualClassDiagSet)
2850193326Sed    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2851193326Sed  PureVirtualClassDiagSet->insert(RD);
2852193326Sed}
2853193326Sed
2854193326Sednamespace {
2855212904Sdimstruct AbstractUsageInfo {
2856212904Sdim  Sema &S;
2857212904Sdim  CXXRecordDecl *Record;
2858212904Sdim  CanQualType AbstractType;
2859212904Sdim  bool Invalid;
2860198092Srdivacky
2861212904Sdim  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2862212904Sdim    : S(S), Record(Record),
2863212904Sdim      AbstractType(S.Context.getCanonicalType(
2864212904Sdim                   S.Context.getTypeDeclType(Record))),
2865212904Sdim      Invalid(false) {}
2866193326Sed
2867212904Sdim  void DiagnoseAbstractType() {
2868212904Sdim    if (Invalid) return;
2869212904Sdim    S.DiagnoseAbstractType(Record);
2870212904Sdim    Invalid = true;
2871212904Sdim  }
2872193326Sed
2873212904Sdim  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2874212904Sdim};
2875212904Sdim
2876212904Sdimstruct CheckAbstractUsage {
2877212904Sdim  AbstractUsageInfo &Info;
2878212904Sdim  const NamedDecl *Ctx;
2879212904Sdim
2880212904Sdim  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2881212904Sdim    : Info(Info), Ctx(Ctx) {}
2882212904Sdim
2883212904Sdim  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2884212904Sdim    switch (TL.getTypeLocClass()) {
2885212904Sdim#define ABSTRACT_TYPELOC(CLASS, PARENT)
2886212904Sdim#define TYPELOC(CLASS, PARENT) \
2887212904Sdim    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2888212904Sdim#include "clang/AST/TypeLocNodes.def"
2889193326Sed    }
2890212904Sdim  }
2891198092Srdivacky
2892212904Sdim  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2893212904Sdim    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2894212904Sdim    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2895219077Sdim      if (!TL.getArg(I))
2896219077Sdim        continue;
2897219077Sdim
2898212904Sdim      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2899212904Sdim      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2900193326Sed    }
2901212904Sdim  }
2902193326Sed
2903212904Sdim  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2904212904Sdim    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2905212904Sdim  }
2906198092Srdivacky
2907212904Sdim  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2908212904Sdim    // Visit the type parameters from a permissive context.
2909212904Sdim    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2910212904Sdim      TemplateArgumentLoc TAL = TL.getArgLoc(I);
2911212904Sdim      if (TAL.getArgument().getKind() == TemplateArgument::Type)
2912212904Sdim        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2913212904Sdim          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2914212904Sdim      // TODO: other template argument types?
2915212904Sdim    }
2916212904Sdim  }
2917193326Sed
2918212904Sdim  // Visit pointee types from a permissive context.
2919212904Sdim#define CheckPolymorphic(Type) \
2920212904Sdim  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2921212904Sdim    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2922212904Sdim  }
2923212904Sdim  CheckPolymorphic(PointerTypeLoc)
2924212904Sdim  CheckPolymorphic(ReferenceTypeLoc)
2925212904Sdim  CheckPolymorphic(MemberPointerTypeLoc)
2926212904Sdim  CheckPolymorphic(BlockPointerTypeLoc)
2927193326Sed
2928212904Sdim  /// Handle all the types we haven't given a more specific
2929212904Sdim  /// implementation for above.
2930212904Sdim  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2931212904Sdim    // Every other kind of type that we haven't called out already
2932212904Sdim    // that has an inner type is either (1) sugar or (2) contains that
2933212904Sdim    // inner type in some way as a subobject.
2934212904Sdim    if (TypeLoc Next = TL.getNextTypeLoc())
2935212904Sdim      return Visit(Next, Sel);
2936212904Sdim
2937212904Sdim    // If there's no inner type and we're in a permissive context,
2938212904Sdim    // don't diagnose.
2939212904Sdim    if (Sel == Sema::AbstractNone) return;
2940212904Sdim
2941212904Sdim    // Check whether the type matches the abstract type.
2942212904Sdim    QualType T = TL.getType();
2943212904Sdim    if (T->isArrayType()) {
2944212904Sdim      Sel = Sema::AbstractArrayType;
2945212904Sdim      T = Info.S.Context.getBaseElementType(T);
2946193326Sed    }
2947212904Sdim    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2948212904Sdim    if (CT != Info.AbstractType) return;
2949198092Srdivacky
2950212904Sdim    // It matched; do some magic.
2951212904Sdim    if (Sel == Sema::AbstractArrayType) {
2952212904Sdim      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2953212904Sdim        << T << TL.getSourceRange();
2954212904Sdim    } else {
2955212904Sdim      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2956212904Sdim        << Sel << T << TL.getSourceRange();
2957212904Sdim    }
2958212904Sdim    Info.DiagnoseAbstractType();
2959212904Sdim  }
2960212904Sdim};
2961198092Srdivacky
2962212904Sdimvoid AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2963212904Sdim                                  Sema::AbstractDiagSelID Sel) {
2964212904Sdim  CheckAbstractUsage(*this, D).Visit(TL, Sel);
2965212904Sdim}
2966212904Sdim
2967212904Sdim}
2968212904Sdim
2969212904Sdim/// Check for invalid uses of an abstract type in a method declaration.
2970212904Sdimstatic void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2971212904Sdim                                    CXXMethodDecl *MD) {
2972212904Sdim  // No need to do the check on definitions, which require that
2973212904Sdim  // the return/param types be complete.
2974223017Sdim  if (MD->doesThisDeclarationHaveABody())
2975212904Sdim    return;
2976212904Sdim
2977212904Sdim  // For safety's sake, just ignore it if we don't have type source
2978212904Sdim  // information.  This should never happen for non-implicit methods,
2979212904Sdim  // but...
2980212904Sdim  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2981212904Sdim    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2982212904Sdim}
2983212904Sdim
2984212904Sdim/// Check for invalid uses of an abstract type within a class definition.
2985212904Sdimstatic void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2986212904Sdim                                    CXXRecordDecl *RD) {
2987212904Sdim  for (CXXRecordDecl::decl_iterator
2988212904Sdim         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2989212904Sdim    Decl *D = *I;
2990212904Sdim    if (D->isImplicit()) continue;
2991212904Sdim
2992212904Sdim    // Methods and method templates.
2993212904Sdim    if (isa<CXXMethodDecl>(D)) {
2994212904Sdim      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2995212904Sdim    } else if (isa<FunctionTemplateDecl>(D)) {
2996212904Sdim      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2997212904Sdim      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2998212904Sdim
2999212904Sdim    // Fields and static variables.
3000212904Sdim    } else if (isa<FieldDecl>(D)) {
3001212904Sdim      FieldDecl *FD = cast<FieldDecl>(D);
3002212904Sdim      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3003212904Sdim        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3004212904Sdim    } else if (isa<VarDecl>(D)) {
3005212904Sdim      VarDecl *VD = cast<VarDecl>(D);
3006212904Sdim      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3007212904Sdim        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3008212904Sdim
3009212904Sdim    // Nested classes and class templates.
3010212904Sdim    } else if (isa<CXXRecordDecl>(D)) {
3011212904Sdim      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3012212904Sdim    } else if (isa<ClassTemplateDecl>(D)) {
3013212904Sdim      CheckAbstractClassUsage(Info,
3014212904Sdim                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3015193326Sed    }
3016212904Sdim  }
3017193326Sed}
3018193326Sed
3019200583Srdivacky/// \brief Perform semantic checks on a class definition that has been
3020200583Srdivacky/// completing, introducing implicitly-declared members, checking for
3021200583Srdivacky/// abstract types, etc.
3022210299Sedvoid Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3023218893Sdim  if (!Record)
3024200583Srdivacky    return;
3025200583Srdivacky
3026212904Sdim  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3027212904Sdim    AbstractUsageInfo Info(*this, Record);
3028212904Sdim    CheckAbstractClassUsage(Info, Record);
3029212904Sdim  }
3030207619Srdivacky
3031207619Srdivacky  // If this is not an aggregate type and has no user-declared constructor,
3032207619Srdivacky  // complain about any non-static data members of reference or const scalar
3033207619Srdivacky  // type, since they will never get initializers.
3034207619Srdivacky  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3035207619Srdivacky      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3036207619Srdivacky    bool Complained = false;
3037207619Srdivacky    for (RecordDecl::field_iterator F = Record->field_begin(),
3038207619Srdivacky                                 FEnd = Record->field_end();
3039207619Srdivacky         F != FEnd; ++F) {
3040223017Sdim      if (F->hasInClassInitializer())
3041223017Sdim        continue;
3042223017Sdim
3043207619Srdivacky      if (F->getType()->isReferenceType() ||
3044207619Srdivacky          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3045207619Srdivacky        if (!Complained) {
3046207619Srdivacky          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3047207619Srdivacky            << Record->getTagKind() << Record;
3048207619Srdivacky          Complained = true;
3049207619Srdivacky        }
3050207619Srdivacky
3051207619Srdivacky        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3052207619Srdivacky          << F->getType()->isReferenceType()
3053207619Srdivacky          << F->getDeclName();
3054207619Srdivacky      }
3055207619Srdivacky    }
3056207619Srdivacky  }
3057208600Srdivacky
3058218893Sdim  if (Record->isDynamicClass() && !Record->isDependentType())
3059208600Srdivacky    DynamicClasses.push_back(Record);
3060218893Sdim
3061218893Sdim  if (Record->getIdentifier()) {
3062218893Sdim    // C++ [class.mem]p13:
3063218893Sdim    //   If T is the name of a class, then each of the following shall have a
3064218893Sdim    //   name different from T:
3065218893Sdim    //     - every member of every anonymous union that is a member of class T.
3066218893Sdim    //
3067218893Sdim    // C++ [class.mem]p14:
3068218893Sdim    //   In addition, if class T has a user-declared constructor (12.1), every
3069218893Sdim    //   non-static data member of class T shall have a name different from T.
3070218893Sdim    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3071218893Sdim         R.first != R.second; ++R.first) {
3072218893Sdim      NamedDecl *D = *R.first;
3073218893Sdim      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3074218893Sdim          isa<IndirectFieldDecl>(D)) {
3075218893Sdim        Diag(D->getLocation(), diag::err_member_name_of_class)
3076218893Sdim          << D->getDeclName();
3077218893Sdim        break;
3078218893Sdim      }
3079218893Sdim    }
3080218893Sdim  }
3081218893Sdim
3082218893Sdim  // Warn if the class has virtual methods but non-virtual public destructor.
3083218893Sdim  if (Record->isPolymorphic() && !Record->isDependentType()) {
3084218893Sdim    CXXDestructorDecl *dtor = Record->getDestructor();
3085218893Sdim    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3086218893Sdim      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3087218893Sdim           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3088218893Sdim  }
3089218893Sdim
3090218893Sdim  // See if a method overloads virtual methods in a base
3091218893Sdim  /// class without overriding any.
3092218893Sdim  if (!Record->isDependentType()) {
3093218893Sdim    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3094218893Sdim                                     MEnd = Record->method_end();
3095218893Sdim         M != MEnd; ++M) {
3096221345Sdim      if (!(*M)->isStatic())
3097221345Sdim        DiagnoseHiddenVirtualMethods(Record, *M);
3098218893Sdim    }
3099218893Sdim  }
3100218893Sdim
3101218893Sdim  // Declare inherited constructors. We do this eagerly here because:
3102218893Sdim  // - The standard requires an eager diagnostic for conflicting inherited
3103218893Sdim  //   constructors from different classes.
3104218893Sdim  // - The lazy declaration of the other implicit constructors is so as to not
3105218893Sdim  //   waste space and performance on classes that are not meant to be
3106218893Sdim  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3107218893Sdim  //   have inherited constructors.
3108218893Sdim  DeclareInheritedConstructors(Record);
3109223017Sdim
3110223017Sdim  if (!Record->isDependentType())
3111223017Sdim    CheckExplicitlyDefaultedMethods(Record);
3112200583Srdivacky}
3113200583Srdivacky
3114223017Sdimvoid Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3115223017Sdim  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3116223017Sdim                                      ME = Record->method_end();
3117223017Sdim       MI != ME; ++MI) {
3118223017Sdim    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3119223017Sdim      switch (getSpecialMember(*MI)) {
3120223017Sdim      case CXXDefaultConstructor:
3121223017Sdim        CheckExplicitlyDefaultedDefaultConstructor(
3122223017Sdim                                                  cast<CXXConstructorDecl>(*MI));
3123223017Sdim        break;
3124223017Sdim
3125223017Sdim      case CXXDestructor:
3126223017Sdim        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3127223017Sdim        break;
3128223017Sdim
3129223017Sdim      case CXXCopyConstructor:
3130223017Sdim        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3131223017Sdim        break;
3132223017Sdim
3133223017Sdim      case CXXCopyAssignment:
3134223017Sdim        CheckExplicitlyDefaultedCopyAssignment(*MI);
3135223017Sdim        break;
3136223017Sdim
3137223017Sdim      case CXXMoveConstructor:
3138223017Sdim      case CXXMoveAssignment:
3139223017Sdim        Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3140223017Sdim        break;
3141223017Sdim
3142223017Sdim      default:
3143223017Sdim        // FIXME: Do moves once they exist
3144223017Sdim        llvm_unreachable("non-special member explicitly defaulted!");
3145223017Sdim      }
3146223017Sdim    }
3147223017Sdim  }
3148223017Sdim
3149223017Sdim}
3150223017Sdim
3151223017Sdimvoid Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3152223017Sdim  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3153223017Sdim
3154223017Sdim  // Whether this was the first-declared instance of the constructor.
3155223017Sdim  // This affects whether we implicitly add an exception spec (and, eventually,
3156223017Sdim  // constexpr). It is also ill-formed to explicitly default a constructor such
3157223017Sdim  // that it would be deleted. (C++0x [decl.fct.def.default])
3158223017Sdim  bool First = CD == CD->getCanonicalDecl();
3159223017Sdim
3160223017Sdim  bool HadError = false;
3161223017Sdim  if (CD->getNumParams() != 0) {
3162223017Sdim    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3163223017Sdim      << CD->getSourceRange();
3164223017Sdim    HadError = true;
3165223017Sdim  }
3166223017Sdim
3167223017Sdim  ImplicitExceptionSpecification Spec
3168223017Sdim    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3169223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3170223017Sdim  if (EPI.ExceptionSpecType == EST_Delayed) {
3171223017Sdim    // Exception specification depends on some deferred part of the class. We'll
3172223017Sdim    // try again when the class's definition has been fully processed.
3173223017Sdim    return;
3174223017Sdim  }
3175223017Sdim  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3176223017Sdim                          *ExceptionType = Context.getFunctionType(
3177223017Sdim                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3178223017Sdim
3179223017Sdim  if (CtorType->hasExceptionSpec()) {
3180223017Sdim    if (CheckEquivalentExceptionSpec(
3181223017Sdim          PDiag(diag::err_incorrect_defaulted_exception_spec)
3182223017Sdim            << CXXDefaultConstructor,
3183223017Sdim          PDiag(),
3184223017Sdim          ExceptionType, SourceLocation(),
3185223017Sdim          CtorType, CD->getLocation())) {
3186223017Sdim      HadError = true;
3187223017Sdim    }
3188223017Sdim  } else if (First) {
3189223017Sdim    // We set the declaration to have the computed exception spec here.
3190223017Sdim    // We know there are no parameters.
3191223017Sdim    EPI.ExtInfo = CtorType->getExtInfo();
3192223017Sdim    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3193223017Sdim  }
3194223017Sdim
3195223017Sdim  if (HadError) {
3196223017Sdim    CD->setInvalidDecl();
3197223017Sdim    return;
3198223017Sdim  }
3199223017Sdim
3200223017Sdim  if (ShouldDeleteDefaultConstructor(CD)) {
3201223017Sdim    if (First) {
3202223017Sdim      CD->setDeletedAsWritten();
3203223017Sdim    } else {
3204223017Sdim      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3205223017Sdim        << CXXDefaultConstructor;
3206223017Sdim      CD->setInvalidDecl();
3207223017Sdim    }
3208223017Sdim  }
3209223017Sdim}
3210223017Sdim
3211223017Sdimvoid Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3212223017Sdim  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3213223017Sdim
3214223017Sdim  // Whether this was the first-declared instance of the constructor.
3215223017Sdim  bool First = CD == CD->getCanonicalDecl();
3216223017Sdim
3217223017Sdim  bool HadError = false;
3218223017Sdim  if (CD->getNumParams() != 1) {
3219223017Sdim    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3220223017Sdim      << CD->getSourceRange();
3221223017Sdim    HadError = true;
3222223017Sdim  }
3223223017Sdim
3224223017Sdim  ImplicitExceptionSpecification Spec(Context);
3225223017Sdim  bool Const;
3226223017Sdim  llvm::tie(Spec, Const) =
3227223017Sdim    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3228223017Sdim
3229223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3230223017Sdim  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3231223017Sdim                          *ExceptionType = Context.getFunctionType(
3232223017Sdim                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3233223017Sdim
3234223017Sdim  // Check for parameter type matching.
3235223017Sdim  // This is a copy ctor so we know it's a cv-qualified reference to T.
3236223017Sdim  QualType ArgType = CtorType->getArgType(0);
3237223017Sdim  if (ArgType->getPointeeType().isVolatileQualified()) {
3238223017Sdim    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3239223017Sdim    HadError = true;
3240223017Sdim  }
3241223017Sdim  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3242223017Sdim    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3243223017Sdim    HadError = true;
3244223017Sdim  }
3245223017Sdim
3246223017Sdim  if (CtorType->hasExceptionSpec()) {
3247223017Sdim    if (CheckEquivalentExceptionSpec(
3248223017Sdim          PDiag(diag::err_incorrect_defaulted_exception_spec)
3249223017Sdim            << CXXCopyConstructor,
3250223017Sdim          PDiag(),
3251223017Sdim          ExceptionType, SourceLocation(),
3252223017Sdim          CtorType, CD->getLocation())) {
3253223017Sdim      HadError = true;
3254223017Sdim    }
3255223017Sdim  } else if (First) {
3256223017Sdim    // We set the declaration to have the computed exception spec here.
3257223017Sdim    // We duplicate the one parameter type.
3258223017Sdim    EPI.ExtInfo = CtorType->getExtInfo();
3259223017Sdim    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3260223017Sdim  }
3261223017Sdim
3262223017Sdim  if (HadError) {
3263223017Sdim    CD->setInvalidDecl();
3264223017Sdim    return;
3265223017Sdim  }
3266223017Sdim
3267223017Sdim  if (ShouldDeleteCopyConstructor(CD)) {
3268223017Sdim    if (First) {
3269223017Sdim      CD->setDeletedAsWritten();
3270223017Sdim    } else {
3271223017Sdim      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3272223017Sdim        << CXXCopyConstructor;
3273223017Sdim      CD->setInvalidDecl();
3274223017Sdim    }
3275223017Sdim  }
3276223017Sdim}
3277223017Sdim
3278223017Sdimvoid Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3279223017Sdim  assert(MD->isExplicitlyDefaulted());
3280223017Sdim
3281223017Sdim  // Whether this was the first-declared instance of the operator
3282223017Sdim  bool First = MD == MD->getCanonicalDecl();
3283223017Sdim
3284223017Sdim  bool HadError = false;
3285223017Sdim  if (MD->getNumParams() != 1) {
3286223017Sdim    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3287223017Sdim      << MD->getSourceRange();
3288223017Sdim    HadError = true;
3289223017Sdim  }
3290223017Sdim
3291223017Sdim  QualType ReturnType =
3292223017Sdim    MD->getType()->getAs<FunctionType>()->getResultType();
3293223017Sdim  if (!ReturnType->isLValueReferenceType() ||
3294223017Sdim      !Context.hasSameType(
3295223017Sdim        Context.getCanonicalType(ReturnType->getPointeeType()),
3296223017Sdim        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3297223017Sdim    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3298223017Sdim    HadError = true;
3299223017Sdim  }
3300223017Sdim
3301223017Sdim  ImplicitExceptionSpecification Spec(Context);
3302223017Sdim  bool Const;
3303223017Sdim  llvm::tie(Spec, Const) =
3304223017Sdim    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3305223017Sdim
3306223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3307223017Sdim  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3308223017Sdim                          *ExceptionType = Context.getFunctionType(
3309223017Sdim                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3310223017Sdim
3311223017Sdim  QualType ArgType = OperType->getArgType(0);
3312223017Sdim  if (!ArgType->isReferenceType()) {
3313223017Sdim    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3314223017Sdim    HadError = true;
3315223017Sdim  } else {
3316223017Sdim    if (ArgType->getPointeeType().isVolatileQualified()) {
3317223017Sdim      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3318223017Sdim      HadError = true;
3319223017Sdim    }
3320223017Sdim    if (ArgType->getPointeeType().isConstQualified() && !Const) {
3321223017Sdim      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3322223017Sdim      HadError = true;
3323223017Sdim    }
3324223017Sdim  }
3325223017Sdim
3326223017Sdim  if (OperType->getTypeQuals()) {
3327223017Sdim    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3328223017Sdim    HadError = true;
3329223017Sdim  }
3330223017Sdim
3331223017Sdim  if (OperType->hasExceptionSpec()) {
3332223017Sdim    if (CheckEquivalentExceptionSpec(
3333223017Sdim          PDiag(diag::err_incorrect_defaulted_exception_spec)
3334223017Sdim            << CXXCopyAssignment,
3335223017Sdim          PDiag(),
3336223017Sdim          ExceptionType, SourceLocation(),
3337223017Sdim          OperType, MD->getLocation())) {
3338223017Sdim      HadError = true;
3339223017Sdim    }
3340223017Sdim  } else if (First) {
3341223017Sdim    // We set the declaration to have the computed exception spec here.
3342223017Sdim    // We duplicate the one parameter type.
3343223017Sdim    EPI.RefQualifier = OperType->getRefQualifier();
3344223017Sdim    EPI.ExtInfo = OperType->getExtInfo();
3345223017Sdim    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3346223017Sdim  }
3347223017Sdim
3348223017Sdim  if (HadError) {
3349223017Sdim    MD->setInvalidDecl();
3350223017Sdim    return;
3351223017Sdim  }
3352223017Sdim
3353223017Sdim  if (ShouldDeleteCopyAssignmentOperator(MD)) {
3354223017Sdim    if (First) {
3355223017Sdim      MD->setDeletedAsWritten();
3356223017Sdim    } else {
3357223017Sdim      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3358223017Sdim        << CXXCopyAssignment;
3359223017Sdim      MD->setInvalidDecl();
3360223017Sdim    }
3361223017Sdim  }
3362223017Sdim}
3363223017Sdim
3364223017Sdimvoid Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3365223017Sdim  assert(DD->isExplicitlyDefaulted());
3366223017Sdim
3367223017Sdim  // Whether this was the first-declared instance of the destructor.
3368223017Sdim  bool First = DD == DD->getCanonicalDecl();
3369223017Sdim
3370223017Sdim  ImplicitExceptionSpecification Spec
3371223017Sdim    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3372223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3373223017Sdim  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3374223017Sdim                          *ExceptionType = Context.getFunctionType(
3375223017Sdim                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3376223017Sdim
3377223017Sdim  if (DtorType->hasExceptionSpec()) {
3378223017Sdim    if (CheckEquivalentExceptionSpec(
3379223017Sdim          PDiag(diag::err_incorrect_defaulted_exception_spec)
3380223017Sdim            << CXXDestructor,
3381223017Sdim          PDiag(),
3382223017Sdim          ExceptionType, SourceLocation(),
3383223017Sdim          DtorType, DD->getLocation())) {
3384223017Sdim      DD->setInvalidDecl();
3385223017Sdim      return;
3386223017Sdim    }
3387223017Sdim  } else if (First) {
3388223017Sdim    // We set the declaration to have the computed exception spec here.
3389223017Sdim    // There are no parameters.
3390223017Sdim    EPI.ExtInfo = DtorType->getExtInfo();
3391223017Sdim    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3392223017Sdim  }
3393223017Sdim
3394223017Sdim  if (ShouldDeleteDestructor(DD)) {
3395223017Sdim    if (First) {
3396223017Sdim      DD->setDeletedAsWritten();
3397223017Sdim    } else {
3398223017Sdim      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3399223017Sdim        << CXXDestructor;
3400223017Sdim      DD->setInvalidDecl();
3401223017Sdim    }
3402223017Sdim  }
3403223017Sdim}
3404223017Sdim
3405223017Sdimbool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3406223017Sdim  CXXRecordDecl *RD = CD->getParent();
3407223017Sdim  assert(!RD->isDependentType() && "do deletion after instantiation");
3408223017Sdim  if (!LangOpts.CPlusPlus0x)
3409223017Sdim    return false;
3410223017Sdim
3411223017Sdim  SourceLocation Loc = CD->getLocation();
3412223017Sdim
3413223017Sdim  // Do access control from the constructor
3414223017Sdim  ContextRAII CtorContext(*this, CD);
3415223017Sdim
3416223017Sdim  bool Union = RD->isUnion();
3417223017Sdim  bool AllConst = true;
3418223017Sdim
3419223017Sdim  // We do this because we should never actually use an anonymous
3420223017Sdim  // union's constructor.
3421223017Sdim  if (Union && RD->isAnonymousStructOrUnion())
3422223017Sdim    return false;
3423223017Sdim
3424223017Sdim  // FIXME: We should put some diagnostic logic right into this function.
3425223017Sdim
3426223017Sdim  // C++0x [class.ctor]/5
3427223017Sdim  //    A defaulted default constructor for class X is defined as deleted if:
3428223017Sdim
3429223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3430223017Sdim                                          BE = RD->bases_end();
3431223017Sdim       BI != BE; ++BI) {
3432223017Sdim    // We'll handle this one later
3433223017Sdim    if (BI->isVirtual())
3434223017Sdim      continue;
3435223017Sdim
3436223017Sdim    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3437223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3438223017Sdim
3439223017Sdim    // -- any [direct base class] has a type with a destructor that is
3440223017Sdim    //    deleted or inaccessible from the defaulted default constructor
3441223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3442223017Sdim    if (BaseDtor->isDeleted())
3443223017Sdim      return true;
3444223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3445223017Sdim        AR_accessible)
3446223017Sdim      return true;
3447223017Sdim
3448223017Sdim    // -- any [direct base class either] has no default constructor or
3449223017Sdim    //    overload resolution as applied to [its] default constructor
3450223017Sdim    //    results in an ambiguity or in a function that is deleted or
3451223017Sdim    //    inaccessible from the defaulted default constructor
3452223017Sdim    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3453223017Sdim    if (!BaseDefault || BaseDefault->isDeleted())
3454223017Sdim      return true;
3455223017Sdim
3456223017Sdim    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3457223017Sdim                               PDiag()) != AR_accessible)
3458223017Sdim      return true;
3459223017Sdim  }
3460223017Sdim
3461223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3462223017Sdim                                          BE = RD->vbases_end();
3463223017Sdim       BI != BE; ++BI) {
3464223017Sdim    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3465223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3466223017Sdim
3467223017Sdim    // -- any [virtual base class] has a type with a destructor that is
3468223017Sdim    //    delete or inaccessible from the defaulted default constructor
3469223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3470223017Sdim    if (BaseDtor->isDeleted())
3471223017Sdim      return true;
3472223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3473223017Sdim        AR_accessible)
3474223017Sdim      return true;
3475223017Sdim
3476223017Sdim    // -- any [virtual base class either] has no default constructor or
3477223017Sdim    //    overload resolution as applied to [its] default constructor
3478223017Sdim    //    results in an ambiguity or in a function that is deleted or
3479223017Sdim    //    inaccessible from the defaulted default constructor
3480223017Sdim    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3481223017Sdim    if (!BaseDefault || BaseDefault->isDeleted())
3482223017Sdim      return true;
3483223017Sdim
3484223017Sdim    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3485223017Sdim                               PDiag()) != AR_accessible)
3486223017Sdim      return true;
3487223017Sdim  }
3488223017Sdim
3489223017Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3490223017Sdim                                     FE = RD->field_end();
3491223017Sdim       FI != FE; ++FI) {
3492223017Sdim    if (FI->isInvalidDecl())
3493223017Sdim      continue;
3494223017Sdim
3495223017Sdim    QualType FieldType = Context.getBaseElementType(FI->getType());
3496223017Sdim    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3497223017Sdim
3498223017Sdim    // -- any non-static data member with no brace-or-equal-initializer is of
3499223017Sdim    //    reference type
3500223017Sdim    if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3501223017Sdim      return true;
3502223017Sdim
3503223017Sdim    // -- X is a union and all its variant members are of const-qualified type
3504223017Sdim    //    (or array thereof)
3505223017Sdim    if (Union && !FieldType.isConstQualified())
3506223017Sdim      AllConst = false;
3507223017Sdim
3508223017Sdim    if (FieldRecord) {
3509223017Sdim      // -- X is a union-like class that has a variant member with a non-trivial
3510223017Sdim      //    default constructor
3511223017Sdim      if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3512223017Sdim        return true;
3513223017Sdim
3514223017Sdim      CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3515223017Sdim      if (FieldDtor->isDeleted())
3516223017Sdim        return true;
3517223017Sdim      if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3518223017Sdim          AR_accessible)
3519223017Sdim        return true;
3520223017Sdim
3521223017Sdim      // -- any non-variant non-static data member of const-qualified type (or
3522223017Sdim      //    array thereof) with no brace-or-equal-initializer does not have a
3523223017Sdim      //    user-provided default constructor
3524223017Sdim      if (FieldType.isConstQualified() &&
3525223017Sdim          !FI->hasInClassInitializer() &&
3526223017Sdim          !FieldRecord->hasUserProvidedDefaultConstructor())
3527223017Sdim        return true;
3528223017Sdim
3529223017Sdim      if (!Union && FieldRecord->isUnion() &&
3530223017Sdim          FieldRecord->isAnonymousStructOrUnion()) {
3531223017Sdim        // We're okay to reuse AllConst here since we only care about the
3532223017Sdim        // value otherwise if we're in a union.
3533223017Sdim        AllConst = true;
3534223017Sdim
3535223017Sdim        for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3536223017Sdim                                           UE = FieldRecord->field_end();
3537223017Sdim             UI != UE; ++UI) {
3538223017Sdim          QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3539223017Sdim          CXXRecordDecl *UnionFieldRecord =
3540223017Sdim            UnionFieldType->getAsCXXRecordDecl();
3541223017Sdim
3542223017Sdim          if (!UnionFieldType.isConstQualified())
3543223017Sdim            AllConst = false;
3544223017Sdim
3545223017Sdim          if (UnionFieldRecord &&
3546223017Sdim              !UnionFieldRecord->hasTrivialDefaultConstructor())
3547223017Sdim            return true;
3548223017Sdim        }
3549223017Sdim
3550223017Sdim        if (AllConst)
3551223017Sdim          return true;
3552223017Sdim
3553223017Sdim        // Don't try to initialize the anonymous union
3554223017Sdim        // This is technically non-conformant, but sanity demands it.
3555223017Sdim        continue;
3556223017Sdim      }
3557223017Sdim
3558223017Sdim      // -- any non-static data member with no brace-or-equal-initializer has
3559223017Sdim      //    class type M (or array thereof) and either M has no default
3560223017Sdim      //    constructor or overload resolution as applied to M's default
3561223017Sdim      //    constructor results in an ambiguity or in a function that is deleted
3562223017Sdim      //    or inaccessible from the defaulted default constructor.
3563223017Sdim      if (!FI->hasInClassInitializer()) {
3564223017Sdim        CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3565223017Sdim        if (!FieldDefault || FieldDefault->isDeleted())
3566223017Sdim          return true;
3567223017Sdim        if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3568223017Sdim                                   PDiag()) != AR_accessible)
3569223017Sdim          return true;
3570223017Sdim      }
3571223017Sdim    } else if (!Union && FieldType.isConstQualified() &&
3572223017Sdim               !FI->hasInClassInitializer()) {
3573223017Sdim      // -- any non-variant non-static data member of const-qualified type (or
3574223017Sdim      //    array thereof) with no brace-or-equal-initializer does not have a
3575223017Sdim      //    user-provided default constructor
3576223017Sdim      return true;
3577223017Sdim    }
3578223017Sdim  }
3579223017Sdim
3580223017Sdim  if (Union && AllConst)
3581223017Sdim    return true;
3582223017Sdim
3583223017Sdim  return false;
3584223017Sdim}
3585223017Sdim
3586223017Sdimbool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3587223017Sdim  CXXRecordDecl *RD = CD->getParent();
3588223017Sdim  assert(!RD->isDependentType() && "do deletion after instantiation");
3589223017Sdim  if (!LangOpts.CPlusPlus0x)
3590223017Sdim    return false;
3591223017Sdim
3592223017Sdim  SourceLocation Loc = CD->getLocation();
3593223017Sdim
3594223017Sdim  // Do access control from the constructor
3595223017Sdim  ContextRAII CtorContext(*this, CD);
3596223017Sdim
3597223017Sdim  bool Union = RD->isUnion();
3598223017Sdim
3599223017Sdim  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3600223017Sdim         "copy assignment arg has no pointee type");
3601223017Sdim  unsigned ArgQuals =
3602223017Sdim    CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3603223017Sdim      Qualifiers::Const : 0;
3604223017Sdim
3605223017Sdim  // We do this because we should never actually use an anonymous
3606223017Sdim  // union's constructor.
3607223017Sdim  if (Union && RD->isAnonymousStructOrUnion())
3608223017Sdim    return false;
3609223017Sdim
3610223017Sdim  // FIXME: We should put some diagnostic logic right into this function.
3611223017Sdim
3612223017Sdim  // C++0x [class.copy]/11
3613223017Sdim  //    A defaulted [copy] constructor for class X is defined as delete if X has:
3614223017Sdim
3615223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3616223017Sdim                                          BE = RD->bases_end();
3617223017Sdim       BI != BE; ++BI) {
3618223017Sdim    // We'll handle this one later
3619223017Sdim    if (BI->isVirtual())
3620223017Sdim      continue;
3621223017Sdim
3622223017Sdim    QualType BaseType = BI->getType();
3623223017Sdim    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3624223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3625223017Sdim
3626223017Sdim    // -- any [direct base class] of a type with a destructor that is deleted or
3627223017Sdim    //    inaccessible from the defaulted constructor
3628223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3629223017Sdim    if (BaseDtor->isDeleted())
3630223017Sdim      return true;
3631223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3632223017Sdim        AR_accessible)
3633223017Sdim      return true;
3634223017Sdim
3635223017Sdim    // -- a [direct base class] B that cannot be [copied] because overload
3636223017Sdim    //    resolution, as applied to B's [copy] constructor, results in an
3637223017Sdim    //    ambiguity or a function that is deleted or inaccessible from the
3638223017Sdim    //    defaulted constructor
3639223017Sdim    CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3640223017Sdim    if (!BaseCtor || BaseCtor->isDeleted())
3641223017Sdim      return true;
3642223017Sdim    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3643223017Sdim        AR_accessible)
3644223017Sdim      return true;
3645223017Sdim  }
3646223017Sdim
3647223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3648223017Sdim                                          BE = RD->vbases_end();
3649223017Sdim       BI != BE; ++BI) {
3650223017Sdim    QualType BaseType = BI->getType();
3651223017Sdim    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3652223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3653223017Sdim
3654223017Sdim    // -- any [virtual base class] of a type with a destructor that is deleted or
3655223017Sdim    //    inaccessible from the defaulted constructor
3656223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3657223017Sdim    if (BaseDtor->isDeleted())
3658223017Sdim      return true;
3659223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3660223017Sdim        AR_accessible)
3661223017Sdim      return true;
3662223017Sdim
3663223017Sdim    // -- a [virtual base class] B that cannot be [copied] because overload
3664223017Sdim    //    resolution, as applied to B's [copy] constructor, results in an
3665223017Sdim    //    ambiguity or a function that is deleted or inaccessible from the
3666223017Sdim    //    defaulted constructor
3667223017Sdim    CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3668223017Sdim    if (!BaseCtor || BaseCtor->isDeleted())
3669223017Sdim      return true;
3670223017Sdim    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3671223017Sdim        AR_accessible)
3672223017Sdim      return true;
3673223017Sdim  }
3674223017Sdim
3675223017Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3676223017Sdim                                     FE = RD->field_end();
3677223017Sdim       FI != FE; ++FI) {
3678223017Sdim    QualType FieldType = Context.getBaseElementType(FI->getType());
3679223017Sdim
3680223017Sdim    // -- for a copy constructor, a non-static data member of rvalue reference
3681223017Sdim    //    type
3682223017Sdim    if (FieldType->isRValueReferenceType())
3683223017Sdim      return true;
3684223017Sdim
3685223017Sdim    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3686223017Sdim
3687223017Sdim    if (FieldRecord) {
3688223017Sdim      // This is an anonymous union
3689223017Sdim      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3690223017Sdim        // Anonymous unions inside unions do not variant members create
3691223017Sdim        if (!Union) {
3692223017Sdim          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3693223017Sdim                                             UE = FieldRecord->field_end();
3694223017Sdim               UI != UE; ++UI) {
3695223017Sdim            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3696223017Sdim            CXXRecordDecl *UnionFieldRecord =
3697223017Sdim              UnionFieldType->getAsCXXRecordDecl();
3698223017Sdim
3699223017Sdim            // -- a variant member with a non-trivial [copy] constructor and X
3700223017Sdim            //    is a union-like class
3701223017Sdim            if (UnionFieldRecord &&
3702223017Sdim                !UnionFieldRecord->hasTrivialCopyConstructor())
3703223017Sdim              return true;
3704223017Sdim          }
3705223017Sdim        }
3706223017Sdim
3707223017Sdim        // Don't try to initalize an anonymous union
3708223017Sdim        continue;
3709223017Sdim      } else {
3710223017Sdim         // -- a variant member with a non-trivial [copy] constructor and X is a
3711223017Sdim         //    union-like class
3712223017Sdim        if (Union && !FieldRecord->hasTrivialCopyConstructor())
3713223017Sdim          return true;
3714223017Sdim
3715223017Sdim        // -- any [non-static data member] of a type with a destructor that is
3716223017Sdim        //    deleted or inaccessible from the defaulted constructor
3717223017Sdim        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3718223017Sdim        if (FieldDtor->isDeleted())
3719223017Sdim          return true;
3720223017Sdim        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3721223017Sdim            AR_accessible)
3722223017Sdim          return true;
3723223017Sdim      }
3724223017Sdim
3725223017Sdim    // -- a [non-static data member of class type (or array thereof)] B that
3726223017Sdim    //    cannot be [copied] because overload resolution, as applied to B's
3727223017Sdim    //    [copy] constructor, results in an ambiguity or a function that is
3728223017Sdim    //    deleted or inaccessible from the defaulted constructor
3729223017Sdim      CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3730223017Sdim                                                            ArgQuals);
3731223017Sdim      if (!FieldCtor || FieldCtor->isDeleted())
3732223017Sdim        return true;
3733223017Sdim      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3734223017Sdim                                 PDiag()) != AR_accessible)
3735223017Sdim        return true;
3736223017Sdim    }
3737223017Sdim  }
3738223017Sdim
3739223017Sdim  return false;
3740223017Sdim}
3741223017Sdim
3742223017Sdimbool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3743223017Sdim  CXXRecordDecl *RD = MD->getParent();
3744223017Sdim  assert(!RD->isDependentType() && "do deletion after instantiation");
3745223017Sdim  if (!LangOpts.CPlusPlus0x)
3746223017Sdim    return false;
3747223017Sdim
3748223017Sdim  SourceLocation Loc = MD->getLocation();
3749223017Sdim
3750223017Sdim  // Do access control from the constructor
3751223017Sdim  ContextRAII MethodContext(*this, MD);
3752223017Sdim
3753223017Sdim  bool Union = RD->isUnion();
3754223017Sdim
3755223017Sdim  bool ConstArg =
3756223017Sdim    MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
3757223017Sdim
3758223017Sdim  // We do this because we should never actually use an anonymous
3759223017Sdim  // union's constructor.
3760223017Sdim  if (Union && RD->isAnonymousStructOrUnion())
3761223017Sdim    return false;
3762223017Sdim
3763223017Sdim  DeclarationName OperatorName =
3764223017Sdim    Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3765223017Sdim  LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3766223017Sdim  R.suppressDiagnostics();
3767223017Sdim
3768223017Sdim  // FIXME: We should put some diagnostic logic right into this function.
3769223017Sdim
3770223017Sdim  // C++0x [class.copy]/11
3771223017Sdim  //    A defaulted [copy] assignment operator for class X is defined as deleted
3772223017Sdim  //    if X has:
3773223017Sdim
3774223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3775223017Sdim                                          BE = RD->bases_end();
3776223017Sdim       BI != BE; ++BI) {
3777223017Sdim    // We'll handle this one later
3778223017Sdim    if (BI->isVirtual())
3779223017Sdim      continue;
3780223017Sdim
3781223017Sdim    QualType BaseType = BI->getType();
3782223017Sdim    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3783223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3784223017Sdim
3785223017Sdim    // -- a [direct base class] B that cannot be [copied] because overload
3786223017Sdim    //    resolution, as applied to B's [copy] assignment operator, results in
3787223017Sdim    //    an ambiguity or a function that is deleted or inaccessible from the
3788223017Sdim    //    assignment operator
3789223017Sdim
3790223017Sdim    LookupQualifiedName(R, BaseDecl, false);
3791223017Sdim
3792223017Sdim    // Filter out any result that isn't a copy-assignment operator.
3793223017Sdim    LookupResult::Filter F = R.makeFilter();
3794223017Sdim    while (F.hasNext()) {
3795223017Sdim      NamedDecl *D = F.next();
3796223017Sdim      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3797223017Sdim        if (Method->isCopyAssignmentOperator())
3798223017Sdim          continue;
3799223017Sdim
3800223017Sdim      F.erase();
3801223017Sdim    }
3802223017Sdim    F.done();
3803223017Sdim
3804223017Sdim    // Build a fake argument expression
3805223017Sdim    QualType ArgType = BaseType;
3806223017Sdim    QualType ThisType = BaseType;
3807223017Sdim    if (ConstArg)
3808223017Sdim      ArgType.addConst();
3809223017Sdim    Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3810223017Sdim                   , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3811223017Sdim                   };
3812223017Sdim
3813223017Sdim    OverloadCandidateSet OCS((Loc));
3814223017Sdim    OverloadCandidateSet::iterator Best;
3815223017Sdim
3816223017Sdim    AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3817223017Sdim
3818223017Sdim    if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3819223017Sdim        OR_Success)
3820223017Sdim      return true;
3821223017Sdim  }
3822223017Sdim
3823223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3824223017Sdim                                          BE = RD->vbases_end();
3825223017Sdim       BI != BE; ++BI) {
3826223017Sdim    QualType BaseType = BI->getType();
3827223017Sdim    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3828223017Sdim    assert(BaseDecl && "base isn't a CXXRecordDecl");
3829223017Sdim
3830223017Sdim    // -- a [virtual base class] B that cannot be [copied] because overload
3831223017Sdim    //    resolution, as applied to B's [copy] assignment operator, results in
3832223017Sdim    //    an ambiguity or a function that is deleted or inaccessible from the
3833223017Sdim    //    assignment operator
3834223017Sdim
3835223017Sdim    LookupQualifiedName(R, BaseDecl, false);
3836223017Sdim
3837223017Sdim    // Filter out any result that isn't a copy-assignment operator.
3838223017Sdim    LookupResult::Filter F = R.makeFilter();
3839223017Sdim    while (F.hasNext()) {
3840223017Sdim      NamedDecl *D = F.next();
3841223017Sdim      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3842223017Sdim        if (Method->isCopyAssignmentOperator())
3843223017Sdim          continue;
3844223017Sdim
3845223017Sdim      F.erase();
3846223017Sdim    }
3847223017Sdim    F.done();
3848223017Sdim
3849223017Sdim    // Build a fake argument expression
3850223017Sdim    QualType ArgType = BaseType;
3851223017Sdim    QualType ThisType = BaseType;
3852223017Sdim    if (ConstArg)
3853223017Sdim      ArgType.addConst();
3854223017Sdim    Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3855223017Sdim                   , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3856223017Sdim                   };
3857223017Sdim
3858223017Sdim    OverloadCandidateSet OCS((Loc));
3859223017Sdim    OverloadCandidateSet::iterator Best;
3860223017Sdim
3861223017Sdim    AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3862223017Sdim
3863223017Sdim    if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3864223017Sdim        OR_Success)
3865223017Sdim      return true;
3866223017Sdim  }
3867223017Sdim
3868223017Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3869223017Sdim                                     FE = RD->field_end();
3870223017Sdim       FI != FE; ++FI) {
3871223017Sdim    QualType FieldType = Context.getBaseElementType(FI->getType());
3872223017Sdim
3873223017Sdim    // -- a non-static data member of reference type
3874223017Sdim    if (FieldType->isReferenceType())
3875223017Sdim      return true;
3876223017Sdim
3877223017Sdim    // -- a non-static data member of const non-class type (or array thereof)
3878223017Sdim    if (FieldType.isConstQualified() && !FieldType->isRecordType())
3879223017Sdim      return true;
3880223017Sdim
3881223017Sdim    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3882223017Sdim
3883223017Sdim    if (FieldRecord) {
3884223017Sdim      // This is an anonymous union
3885223017Sdim      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3886223017Sdim        // Anonymous unions inside unions do not variant members create
3887223017Sdim        if (!Union) {
3888223017Sdim          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3889223017Sdim                                             UE = FieldRecord->field_end();
3890223017Sdim               UI != UE; ++UI) {
3891223017Sdim            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3892223017Sdim            CXXRecordDecl *UnionFieldRecord =
3893223017Sdim              UnionFieldType->getAsCXXRecordDecl();
3894223017Sdim
3895223017Sdim            // -- a variant member with a non-trivial [copy] assignment operator
3896223017Sdim            //    and X is a union-like class
3897223017Sdim            if (UnionFieldRecord &&
3898223017Sdim                !UnionFieldRecord->hasTrivialCopyAssignment())
3899223017Sdim              return true;
3900223017Sdim          }
3901223017Sdim        }
3902223017Sdim
3903223017Sdim        // Don't try to initalize an anonymous union
3904223017Sdim        continue;
3905223017Sdim      // -- a variant member with a non-trivial [copy] assignment operator
3906223017Sdim      //    and X is a union-like class
3907223017Sdim      } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3908223017Sdim          return true;
3909223017Sdim      }
3910223017Sdim
3911223017Sdim      LookupQualifiedName(R, FieldRecord, false);
3912223017Sdim
3913223017Sdim      // Filter out any result that isn't a copy-assignment operator.
3914223017Sdim      LookupResult::Filter F = R.makeFilter();
3915223017Sdim      while (F.hasNext()) {
3916223017Sdim        NamedDecl *D = F.next();
3917223017Sdim        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3918223017Sdim          if (Method->isCopyAssignmentOperator())
3919223017Sdim            continue;
3920223017Sdim
3921223017Sdim        F.erase();
3922223017Sdim      }
3923223017Sdim      F.done();
3924223017Sdim
3925223017Sdim      // Build a fake argument expression
3926223017Sdim      QualType ArgType = FieldType;
3927223017Sdim      QualType ThisType = FieldType;
3928223017Sdim      if (ConstArg)
3929223017Sdim        ArgType.addConst();
3930223017Sdim      Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3931223017Sdim                     , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3932223017Sdim                     };
3933223017Sdim
3934223017Sdim      OverloadCandidateSet OCS((Loc));
3935223017Sdim      OverloadCandidateSet::iterator Best;
3936223017Sdim
3937223017Sdim      AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3938223017Sdim
3939223017Sdim      if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3940223017Sdim          OR_Success)
3941223017Sdim        return true;
3942223017Sdim    }
3943223017Sdim  }
3944223017Sdim
3945223017Sdim  return false;
3946223017Sdim}
3947223017Sdim
3948223017Sdimbool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3949223017Sdim  CXXRecordDecl *RD = DD->getParent();
3950223017Sdim  assert(!RD->isDependentType() && "do deletion after instantiation");
3951223017Sdim  if (!LangOpts.CPlusPlus0x)
3952223017Sdim    return false;
3953223017Sdim
3954223017Sdim  SourceLocation Loc = DD->getLocation();
3955223017Sdim
3956223017Sdim  // Do access control from the destructor
3957223017Sdim  ContextRAII CtorContext(*this, DD);
3958223017Sdim
3959223017Sdim  bool Union = RD->isUnion();
3960223017Sdim
3961223017Sdim  // We do this because we should never actually use an anonymous
3962223017Sdim  // union's destructor.
3963223017Sdim  if (Union && RD->isAnonymousStructOrUnion())
3964223017Sdim    return false;
3965223017Sdim
3966223017Sdim  // C++0x [class.dtor]p5
3967223017Sdim  //    A defaulted destructor for a class X is defined as deleted if:
3968223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3969223017Sdim                                          BE = RD->bases_end();
3970223017Sdim       BI != BE; ++BI) {
3971223017Sdim    // We'll handle this one later
3972223017Sdim    if (BI->isVirtual())
3973223017Sdim      continue;
3974223017Sdim
3975223017Sdim    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3976223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3977223017Sdim    assert(BaseDtor && "base has no destructor");
3978223017Sdim
3979223017Sdim    // -- any direct or virtual base class has a deleted destructor or
3980223017Sdim    //    a destructor that is inaccessible from the defaulted destructor
3981223017Sdim    if (BaseDtor->isDeleted())
3982223017Sdim      return true;
3983223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3984223017Sdim        AR_accessible)
3985223017Sdim      return true;
3986223017Sdim  }
3987223017Sdim
3988223017Sdim  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3989223017Sdim                                          BE = RD->vbases_end();
3990223017Sdim       BI != BE; ++BI) {
3991223017Sdim    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3992223017Sdim    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3993223017Sdim    assert(BaseDtor && "base has no destructor");
3994223017Sdim
3995223017Sdim    // -- any direct or virtual base class has a deleted destructor or
3996223017Sdim    //    a destructor that is inaccessible from the defaulted destructor
3997223017Sdim    if (BaseDtor->isDeleted())
3998223017Sdim      return true;
3999223017Sdim    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4000223017Sdim        AR_accessible)
4001223017Sdim      return true;
4002223017Sdim  }
4003223017Sdim
4004223017Sdim  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4005223017Sdim                                     FE = RD->field_end();
4006223017Sdim       FI != FE; ++FI) {
4007223017Sdim    QualType FieldType = Context.getBaseElementType(FI->getType());
4008223017Sdim    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4009223017Sdim    if (FieldRecord) {
4010223017Sdim      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4011223017Sdim         for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4012223017Sdim                                            UE = FieldRecord->field_end();
4013223017Sdim              UI != UE; ++UI) {
4014223017Sdim           QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4015223017Sdim           CXXRecordDecl *UnionFieldRecord =
4016223017Sdim             UnionFieldType->getAsCXXRecordDecl();
4017223017Sdim
4018223017Sdim           // -- X is a union-like class that has a variant member with a non-
4019223017Sdim           //    trivial destructor.
4020223017Sdim           if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4021223017Sdim             return true;
4022223017Sdim         }
4023223017Sdim      // Technically we are supposed to do this next check unconditionally.
4024223017Sdim      // But that makes absolutely no sense.
4025223017Sdim      } else {
4026223017Sdim        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4027223017Sdim
4028223017Sdim        // -- any of the non-static data members has class type M (or array
4029223017Sdim        //    thereof) and M has a deleted destructor or a destructor that is
4030223017Sdim        //    inaccessible from the defaulted destructor
4031223017Sdim        if (FieldDtor->isDeleted())
4032223017Sdim          return true;
4033223017Sdim        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4034223017Sdim          AR_accessible)
4035223017Sdim        return true;
4036223017Sdim
4037223017Sdim        // -- X is a union-like class that has a variant member with a non-
4038223017Sdim        //    trivial destructor.
4039223017Sdim        if (Union && !FieldDtor->isTrivial())
4040223017Sdim          return true;
4041223017Sdim      }
4042223017Sdim    }
4043223017Sdim  }
4044223017Sdim
4045223017Sdim  if (DD->isVirtual()) {
4046223017Sdim    FunctionDecl *OperatorDelete = 0;
4047223017Sdim    DeclarationName Name =
4048223017Sdim      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4049223017Sdim    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4050223017Sdim          false))
4051223017Sdim      return true;
4052223017Sdim  }
4053223017Sdim
4054223017Sdim
4055223017Sdim  return false;
4056223017Sdim}
4057223017Sdim
4058218893Sdim/// \brief Data used with FindHiddenVirtualMethod
4059221345Sdimnamespace {
4060221345Sdim  struct FindHiddenVirtualMethodData {
4061221345Sdim    Sema *S;
4062221345Sdim    CXXMethodDecl *Method;
4063221345Sdim    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4064221345Sdim    llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4065221345Sdim  };
4066221345Sdim}
4067218893Sdim
4068218893Sdim/// \brief Member lookup function that determines whether a given C++
4069218893Sdim/// method overloads virtual methods in a base class without overriding any,
4070218893Sdim/// to be used with CXXRecordDecl::lookupInBases().
4071218893Sdimstatic bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4072218893Sdim                                    CXXBasePath &Path,
4073218893Sdim                                    void *UserData) {
4074218893Sdim  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4075218893Sdim
4076218893Sdim  FindHiddenVirtualMethodData &Data
4077218893Sdim    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4078218893Sdim
4079218893Sdim  DeclarationName Name = Data.Method->getDeclName();
4080218893Sdim  assert(Name.getNameKind() == DeclarationName::Identifier);
4081218893Sdim
4082218893Sdim  bool foundSameNameMethod = false;
4083218893Sdim  llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4084218893Sdim  for (Path.Decls = BaseRecord->lookup(Name);
4085218893Sdim       Path.Decls.first != Path.Decls.second;
4086218893Sdim       ++Path.Decls.first) {
4087218893Sdim    NamedDecl *D = *Path.Decls.first;
4088218893Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4089218893Sdim      MD = MD->getCanonicalDecl();
4090218893Sdim      foundSameNameMethod = true;
4091218893Sdim      // Interested only in hidden virtual methods.
4092218893Sdim      if (!MD->isVirtual())
4093218893Sdim        continue;
4094218893Sdim      // If the method we are checking overrides a method from its base
4095218893Sdim      // don't warn about the other overloaded methods.
4096218893Sdim      if (!Data.S->IsOverload(Data.Method, MD, false))
4097218893Sdim        return true;
4098218893Sdim      // Collect the overload only if its hidden.
4099218893Sdim      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4100218893Sdim        overloadedMethods.push_back(MD);
4101218893Sdim    }
4102218893Sdim  }
4103218893Sdim
4104218893Sdim  if (foundSameNameMethod)
4105218893Sdim    Data.OverloadedMethods.append(overloadedMethods.begin(),
4106218893Sdim                                   overloadedMethods.end());
4107218893Sdim  return foundSameNameMethod;
4108218893Sdim}
4109218893Sdim
4110218893Sdim/// \brief See if a method overloads virtual methods in a base class without
4111218893Sdim/// overriding any.
4112218893Sdimvoid Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4113218893Sdim  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4114218893Sdim                               MD->getLocation()) == Diagnostic::Ignored)
4115218893Sdim    return;
4116218893Sdim  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4117218893Sdim    return;
4118218893Sdim
4119218893Sdim  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4120218893Sdim                     /*bool RecordPaths=*/false,
4121218893Sdim                     /*bool DetectVirtual=*/false);
4122218893Sdim  FindHiddenVirtualMethodData Data;
4123218893Sdim  Data.Method = MD;
4124218893Sdim  Data.S = this;
4125218893Sdim
4126218893Sdim  // Keep the base methods that were overriden or introduced in the subclass
4127218893Sdim  // by 'using' in a set. A base method not in this set is hidden.
4128218893Sdim  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4129218893Sdim       res.first != res.second; ++res.first) {
4130218893Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4131218893Sdim      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4132218893Sdim                                          E = MD->end_overridden_methods();
4133218893Sdim           I != E; ++I)
4134218893Sdim        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4135218893Sdim    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4136218893Sdim      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4137218893Sdim        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4138218893Sdim  }
4139218893Sdim
4140218893Sdim  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4141218893Sdim      !Data.OverloadedMethods.empty()) {
4142218893Sdim    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4143218893Sdim      << MD << (Data.OverloadedMethods.size() > 1);
4144218893Sdim
4145218893Sdim    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4146218893Sdim      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4147218893Sdim      Diag(overloadedMD->getLocation(),
4148218893Sdim           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4149218893Sdim    }
4150218893Sdim  }
4151218893Sdim}
4152218893Sdim
4153193326Sedvoid Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4154212904Sdim                                             Decl *TagDecl,
4155193326Sed                                             SourceLocation LBrac,
4156206084Srdivacky                                             SourceLocation RBrac,
4157206084Srdivacky                                             AttributeList *AttrList) {
4158194711Sed  if (!TagDecl)
4159194711Sed    return;
4160198092Srdivacky
4161193326Sed  AdjustDeclIfTemplate(TagDecl);
4162200583Srdivacky
4163193326Sed  ActOnFields(S, RLoc, TagDecl,
4164212904Sdim              // strict aliasing violation!
4165212904Sdim              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4166206084Srdivacky              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4167193326Sed
4168210299Sed  CheckCompletedCXXClass(
4169212904Sdim                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4170193326Sed}
4171193326Sed
4172193326Sed/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4173193326Sed/// special functions, such as the default constructor, copy
4174193326Sed/// constructor, or destructor, to the given C++ class (C++
4175193326Sed/// [special]p1).  This routine can only be executed just before the
4176193326Sed/// definition of the class is complete.
4177210299Sedvoid Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4178210299Sed  if (!ClassDecl->hasUserDeclaredConstructor())
4179210299Sed    ++ASTContext::NumImplicitDefaultConstructors;
4180193326Sed
4181210299Sed  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4182210299Sed    ++ASTContext::NumImplicitCopyConstructors;
4183193326Sed
4184193326Sed  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4185210299Sed    ++ASTContext::NumImplicitCopyAssignmentOperators;
4186210299Sed
4187210299Sed    // If we have a dynamic class, then the copy assignment operator may be
4188210299Sed    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4189210299Sed    // it shows up in the right place in the vtable and that we diagnose
4190210299Sed    // problems with the implicit exception specification.
4191210299Sed    if (ClassDecl->isDynamicClass())
4192210299Sed      DeclareImplicitCopyAssignment(ClassDecl);
4193193326Sed  }
4194193326Sed
4195193326Sed  if (!ClassDecl->hasUserDeclaredDestructor()) {
4196210299Sed    ++ASTContext::NumImplicitDestructors;
4197199990Srdivacky
4198210299Sed    // If we have a dynamic class, then the destructor may be virtual, so we
4199210299Sed    // have to declare the destructor immediately. This ensures that, e.g., it
4200210299Sed    // shows up in the right place in the vtable and that we diagnose problems
4201210299Sed    // with the implicit exception specification.
4202210299Sed    if (ClassDecl->isDynamicClass())
4203210299Sed      DeclareImplicitDestructor(ClassDecl);
4204193326Sed  }
4205193326Sed}
4206193326Sed
4207221345Sdimvoid Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4208221345Sdim  if (!D)
4209221345Sdim    return;
4210221345Sdim
4211221345Sdim  int NumParamList = D->getNumTemplateParameterLists();
4212221345Sdim  for (int i = 0; i < NumParamList; i++) {
4213221345Sdim    TemplateParameterList* Params = D->getTemplateParameterList(i);
4214221345Sdim    for (TemplateParameterList::iterator Param = Params->begin(),
4215221345Sdim                                      ParamEnd = Params->end();
4216221345Sdim          Param != ParamEnd; ++Param) {
4217221345Sdim      NamedDecl *Named = cast<NamedDecl>(*Param);
4218221345Sdim      if (Named->getDeclName()) {
4219221345Sdim        S->AddDecl(Named);
4220221345Sdim        IdResolver.AddDecl(Named);
4221221345Sdim      }
4222221345Sdim    }
4223221345Sdim  }
4224221345Sdim}
4225221345Sdim
4226212904Sdimvoid Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4227198092Srdivacky  if (!D)
4228193326Sed    return;
4229198092Srdivacky
4230198092Srdivacky  TemplateParameterList *Params = 0;
4231198092Srdivacky  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4232198092Srdivacky    Params = Template->getTemplateParameters();
4233198092Srdivacky  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4234198092Srdivacky           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4235198092Srdivacky    Params = PartialSpec->getTemplateParameters();
4236198092Srdivacky  else
4237198092Srdivacky    return;
4238193326Sed
4239193326Sed  for (TemplateParameterList::iterator Param = Params->begin(),
4240193326Sed                                    ParamEnd = Params->end();
4241193326Sed       Param != ParamEnd; ++Param) {
4242193326Sed    NamedDecl *Named = cast<NamedDecl>(*Param);
4243193326Sed    if (Named->getDeclName()) {
4244212904Sdim      S->AddDecl(Named);
4245193326Sed      IdResolver.AddDecl(Named);
4246193326Sed    }
4247193326Sed  }
4248193326Sed}
4249193326Sed
4250212904Sdimvoid Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4251201361Srdivacky  if (!RecordD) return;
4252201361Srdivacky  AdjustDeclIfTemplate(RecordD);
4253212904Sdim  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4254201361Srdivacky  PushDeclContext(S, Record);
4255201361Srdivacky}
4256201361Srdivacky
4257212904Sdimvoid Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4258201361Srdivacky  if (!RecordD) return;
4259201361Srdivacky  PopDeclContext();
4260201361Srdivacky}
4261201361Srdivacky
4262193326Sed/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4263193326Sed/// parsing a top-level (non-nested) C++ class, and we are now
4264193326Sed/// parsing those parts of the given Method declaration that could
4265193326Sed/// not be parsed earlier (C++ [class.mem]p2), such as default
4266193326Sed/// arguments. This action should enter the scope of the given
4267193326Sed/// Method declaration as if we had just parsed the qualified method
4268193326Sed/// name. However, it should not bring the parameters into scope;
4269193326Sed/// that will be performed by ActOnDelayedCXXMethodParameter.
4270212904Sdimvoid Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4271193326Sed}
4272193326Sed
4273193326Sed/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4274193326Sed/// C++ method declaration. We're (re-)introducing the given
4275193326Sed/// function parameter into scope for use in parsing later parts of
4276193326Sed/// the method declaration. For example, we could see an
4277193326Sed/// ActOnParamDefaultArgument event for this parameter.
4278212904Sdimvoid Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4279194711Sed  if (!ParamD)
4280194711Sed    return;
4281198092Srdivacky
4282212904Sdim  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4283193326Sed
4284193326Sed  // If this parameter has an unparsed default argument, clear it out
4285193326Sed  // to make way for the parsed default argument.
4286193326Sed  if (Param->hasUnparsedDefaultArg())
4287193326Sed    Param->setDefaultArg(0);
4288193326Sed
4289212904Sdim  S->AddDecl(Param);
4290193326Sed  if (Param->getDeclName())
4291193326Sed    IdResolver.AddDecl(Param);
4292193326Sed}
4293193326Sed
4294193326Sed/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4295193326Sed/// processing the delayed method declaration for Method. The method
4296193326Sed/// declaration is now considered finished. There may be a separate
4297193326Sed/// ActOnStartOfFunctionDef action later (not necessarily
4298193326Sed/// immediately!) for this method, if it was also defined inside the
4299193326Sed/// class body.
4300212904Sdimvoid Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4301194711Sed  if (!MethodD)
4302194711Sed    return;
4303198092Srdivacky
4304198092Srdivacky  AdjustDeclIfTemplate(MethodD);
4305198092Srdivacky
4306212904Sdim  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4307193326Sed
4308193326Sed  // Now that we have our default arguments, check the constructor
4309193326Sed  // again. It could produce additional diagnostics or affect whether
4310193326Sed  // the class has implicitly-declared destructors, among other
4311193326Sed  // things.
4312193326Sed  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4313193326Sed    CheckConstructor(Constructor);
4314193326Sed
4315193326Sed  // Check the default arguments, which we may have added.
4316193326Sed  if (!Method->isInvalidDecl())
4317193326Sed    CheckCXXDefaultArguments(Method);
4318193326Sed}
4319193326Sed
4320193326Sed/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4321193326Sed/// the well-formedness of the constructor declarator @p D with type @p
4322193326Sed/// R. If there are any errors in the declarator, this routine will
4323193326Sed/// emit diagnostics and set the invalid bit to true.  In any case, the type
4324193326Sed/// will be updated to reflect a well-formed type for the constructor and
4325193326Sed/// returned.
4326193326SedQualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4327212904Sdim                                          StorageClass &SC) {
4328193326Sed  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4329193326Sed
4330193326Sed  // C++ [class.ctor]p3:
4331193326Sed  //   A constructor shall not be virtual (10.3) or static (9.4). A
4332193326Sed  //   constructor can be invoked for a const, volatile or const
4333193326Sed  //   volatile object. A constructor shall not be declared const,
4334193326Sed  //   volatile, or const volatile (9.3.2).
4335193326Sed  if (isVirtual) {
4336193326Sed    if (!D.isInvalidType())
4337193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4338193326Sed        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4339193326Sed        << SourceRange(D.getIdentifierLoc());
4340193326Sed    D.setInvalidType();
4341193326Sed  }
4342212904Sdim  if (SC == SC_Static) {
4343193326Sed    if (!D.isInvalidType())
4344193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4345193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4346193326Sed        << SourceRange(D.getIdentifierLoc());
4347193326Sed    D.setInvalidType();
4348212904Sdim    SC = SC_None;
4349193326Sed  }
4350198092Srdivacky
4351218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4352193326Sed  if (FTI.TypeQuals != 0) {
4353198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Const)
4354193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4355193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
4356198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Volatile)
4357193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4358193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
4359198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Restrict)
4360193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4361193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
4362218893Sdim    D.setInvalidType();
4363193326Sed  }
4364198092Srdivacky
4365218893Sdim  // C++0x [class.ctor]p4:
4366218893Sdim  //   A constructor shall not be declared with a ref-qualifier.
4367218893Sdim  if (FTI.hasRefQualifier()) {
4368218893Sdim    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4369218893Sdim      << FTI.RefQualifierIsLValueRef
4370218893Sdim      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4371218893Sdim    D.setInvalidType();
4372218893Sdim  }
4373218893Sdim
4374193326Sed  // Rebuild the function type "R" without any type qualifiers (in
4375193326Sed  // case any of the errors above fired) and with "void" as the
4376210299Sed  // return type, since constructors don't have return types.
4377198092Srdivacky  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4378218893Sdim  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4379218893Sdim    return R;
4380218893Sdim
4381218893Sdim  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4382218893Sdim  EPI.TypeQuals = 0;
4383218893Sdim  EPI.RefQualifier = RQ_None;
4384218893Sdim
4385193326Sed  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4386218893Sdim                                 Proto->getNumArgs(), EPI);
4387193326Sed}
4388193326Sed
4389193326Sed/// CheckConstructor - Checks a fully-formed constructor for
4390193326Sed/// well-formedness, issuing any diagnostics required. Returns true if
4391193326Sed/// the constructor declarator is invalid.
4392193326Sedvoid Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4393198092Srdivacky  CXXRecordDecl *ClassDecl
4394193326Sed    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4395193326Sed  if (!ClassDecl)
4396193326Sed    return Constructor->setInvalidDecl();
4397193326Sed
4398193326Sed  // C++ [class.copy]p3:
4399193326Sed  //   A declaration of a constructor for a class X is ill-formed if
4400193326Sed  //   its first parameter is of type (optionally cv-qualified) X and
4401193326Sed  //   either there are no other parameters or else all other
4402193326Sed  //   parameters have default arguments.
4403193326Sed  if (!Constructor->isInvalidDecl() &&
4404198092Srdivacky      ((Constructor->getNumParams() == 1) ||
4405198092Srdivacky       (Constructor->getNumParams() > 1 &&
4406199482Srdivacky        Constructor->getParamDecl(1)->hasDefaultArg())) &&
4407199482Srdivacky      Constructor->getTemplateSpecializationKind()
4408199482Srdivacky                                              != TSK_ImplicitInstantiation) {
4409193326Sed    QualType ParamType = Constructor->getParamDecl(0)->getType();
4410193326Sed    QualType ClassTy = Context.getTagDeclType(ClassDecl);
4411193326Sed    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4412193326Sed      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4413210299Sed      const char *ConstRef
4414210299Sed        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4415210299Sed                                                        : " const &";
4416193326Sed      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4417210299Sed        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4418199482Srdivacky
4419199482Srdivacky      // FIXME: Rather that making the constructor invalid, we should endeavor
4420199482Srdivacky      // to fix the type.
4421193326Sed      Constructor->setInvalidDecl();
4422193326Sed    }
4423193326Sed  }
4424193326Sed}
4425193326Sed
4426212904Sdim/// CheckDestructor - Checks a fully-formed destructor definition for
4427212904Sdim/// well-formedness, issuing any diagnostics required.  Returns true
4428212904Sdim/// on error.
4429199990Srdivackybool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4430199482Srdivacky  CXXRecordDecl *RD = Destructor->getParent();
4431199482Srdivacky
4432199482Srdivacky  if (Destructor->isVirtual()) {
4433199482Srdivacky    SourceLocation Loc;
4434199482Srdivacky
4435199482Srdivacky    if (!Destructor->isImplicit())
4436199482Srdivacky      Loc = Destructor->getLocation();
4437199482Srdivacky    else
4438199482Srdivacky      Loc = RD->getLocation();
4439199482Srdivacky
4440199482Srdivacky    // If we have a virtual destructor, look up the deallocation function
4441199482Srdivacky    FunctionDecl *OperatorDelete = 0;
4442199482Srdivacky    DeclarationName Name =
4443199482Srdivacky    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4444199990Srdivacky    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4445199990Srdivacky      return true;
4446210299Sed
4447210299Sed    MarkDeclarationReferenced(Loc, OperatorDelete);
4448199990Srdivacky
4449199990Srdivacky    Destructor->setOperatorDelete(OperatorDelete);
4450199482Srdivacky  }
4451199990Srdivacky
4452199990Srdivacky  return false;
4453199482Srdivacky}
4454199482Srdivacky
4455198092Srdivackystatic inline bool
4456193326SedFTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4457193326Sed  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4458193326Sed          FTI.ArgInfo[0].Param &&
4459212904Sdim          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4460193326Sed}
4461193326Sed
4462193326Sed/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4463193326Sed/// the well-formednes of the destructor declarator @p D with type @p
4464193326Sed/// R. If there are any errors in the declarator, this routine will
4465193326Sed/// emit diagnostics and set the declarator to invalid.  Even if this happens,
4466193326Sed/// will be updated to reflect a well-formed type for the destructor and
4467193326Sed/// returned.
4468210299SedQualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4469212904Sdim                                         StorageClass& SC) {
4470193326Sed  // C++ [class.dtor]p1:
4471193326Sed  //   [...] A typedef-name that names a class is a class-name
4472193326Sed  //   (7.1.3); however, a typedef-name that names a class shall not
4473193326Sed  //   be used as the identifier in the declarator for a destructor
4474193326Sed  //   declaration.
4475198893Srdivacky  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4476221345Sdim  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4477193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4478221345Sdim      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4479223017Sdim  else if (const TemplateSpecializationType *TST =
4480223017Sdim             DeclaratorType->getAs<TemplateSpecializationType>())
4481223017Sdim    if (TST->isTypeAlias())
4482223017Sdim      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4483223017Sdim        << DeclaratorType << 1;
4484193326Sed
4485193326Sed  // C++ [class.dtor]p2:
4486193326Sed  //   A destructor is used to destroy objects of its class type. A
4487193326Sed  //   destructor takes no parameters, and no return type can be
4488193326Sed  //   specified for it (not even void). The address of a destructor
4489193326Sed  //   shall not be taken. A destructor shall not be static. A
4490193326Sed  //   destructor can be invoked for a const, volatile or const
4491193326Sed  //   volatile object. A destructor shall not be declared const,
4492193326Sed  //   volatile or const volatile (9.3.2).
4493212904Sdim  if (SC == SC_Static) {
4494193326Sed    if (!D.isInvalidType())
4495193326Sed      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4496193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4497210299Sed        << SourceRange(D.getIdentifierLoc())
4498210299Sed        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4499210299Sed
4500212904Sdim    SC = SC_None;
4501193326Sed  }
4502193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4503193326Sed    // Destructors don't have return types, but the parser will
4504193326Sed    // happily parse something like:
4505193326Sed    //
4506193326Sed    //   class X {
4507193326Sed    //     float ~X();
4508193326Sed    //   };
4509193326Sed    //
4510193326Sed    // The return type will be eliminated later.
4511193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4512193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4513193326Sed      << SourceRange(D.getIdentifierLoc());
4514193326Sed  }
4515198092Srdivacky
4516218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4517193326Sed  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4518198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Const)
4519193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4520193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
4521198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Volatile)
4522193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4523193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
4524198092Srdivacky    if (FTI.TypeQuals & Qualifiers::Restrict)
4525193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4526193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
4527193326Sed    D.setInvalidType();
4528193326Sed  }
4529193326Sed
4530218893Sdim  // C++0x [class.dtor]p2:
4531218893Sdim  //   A destructor shall not be declared with a ref-qualifier.
4532218893Sdim  if (FTI.hasRefQualifier()) {
4533218893Sdim    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4534218893Sdim      << FTI.RefQualifierIsLValueRef
4535218893Sdim      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4536218893Sdim    D.setInvalidType();
4537218893Sdim  }
4538218893Sdim
4539193326Sed  // Make sure we don't have any parameters.
4540193326Sed  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4541193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4542193326Sed
4543193326Sed    // Delete the parameters.
4544193326Sed    FTI.freeArgs();
4545193326Sed    D.setInvalidType();
4546193326Sed  }
4547193326Sed
4548198092Srdivacky  // Make sure the destructor isn't variadic.
4549193326Sed  if (FTI.isVariadic) {
4550193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
4551193326Sed    D.setInvalidType();
4552193326Sed  }
4553193326Sed
4554193326Sed  // Rebuild the function type "R" without any type qualifiers or
4555193326Sed  // parameters (in case any of the errors above fired) and with
4556193326Sed  // "void" as the return type, since destructors don't have return
4557210299Sed  // types.
4558218893Sdim  if (!D.isInvalidType())
4559218893Sdim    return R;
4560218893Sdim
4561210299Sed  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4562218893Sdim  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4563218893Sdim  EPI.Variadic = false;
4564218893Sdim  EPI.TypeQuals = 0;
4565218893Sdim  EPI.RefQualifier = RQ_None;
4566218893Sdim  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
4567193326Sed}
4568193326Sed
4569193326Sed/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4570193326Sed/// well-formednes of the conversion function declarator @p D with
4571193326Sed/// type @p R. If there are any errors in the declarator, this routine
4572193326Sed/// will emit diagnostics and return true. Otherwise, it will return
4573193326Sed/// false. Either way, the type @p R will be updated to reflect a
4574193326Sed/// well-formed type for the conversion operator.
4575193326Sedvoid Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
4576212904Sdim                                     StorageClass& SC) {
4577193326Sed  // C++ [class.conv.fct]p1:
4578193326Sed  //   Neither parameter types nor return type can be specified. The
4579198092Srdivacky  //   type of a conversion function (8.3.5) is "function taking no
4580198092Srdivacky  //   parameter returning conversion-type-id."
4581212904Sdim  if (SC == SC_Static) {
4582193326Sed    if (!D.isInvalidType())
4583193326Sed      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4584193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4585193326Sed        << SourceRange(D.getIdentifierLoc());
4586193326Sed    D.setInvalidType();
4587212904Sdim    SC = SC_None;
4588193326Sed  }
4589207619Srdivacky
4590207619Srdivacky  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4591207619Srdivacky
4592193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4593193326Sed    // Conversion functions don't have return types, but the parser will
4594193326Sed    // happily parse something like:
4595193326Sed    //
4596193326Sed    //   class X {
4597193326Sed    //     float operator bool();
4598193326Sed    //   };
4599193326Sed    //
4600193326Sed    // The return type will be changed later anyway.
4601193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4602193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4603193326Sed      << SourceRange(D.getIdentifierLoc());
4604207619Srdivacky    D.setInvalidType();
4605193326Sed  }
4606193326Sed
4607207619Srdivacky  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4608207619Srdivacky
4609193326Sed  // Make sure we don't have any parameters.
4610207619Srdivacky  if (Proto->getNumArgs() > 0) {
4611193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4612193326Sed
4613193326Sed    // Delete the parameters.
4614218893Sdim    D.getFunctionTypeInfo().freeArgs();
4615193326Sed    D.setInvalidType();
4616207619Srdivacky  } else if (Proto->isVariadic()) {
4617207619Srdivacky    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
4618207619Srdivacky    D.setInvalidType();
4619193326Sed  }
4620193326Sed
4621207619Srdivacky  // Diagnose "&operator bool()" and other such nonsense.  This
4622207619Srdivacky  // is actually a gcc extension which we don't support.
4623207619Srdivacky  if (Proto->getResultType() != ConvType) {
4624207619Srdivacky    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4625207619Srdivacky      << Proto->getResultType();
4626193326Sed    D.setInvalidType();
4627207619Srdivacky    ConvType = Proto->getResultType();
4628193326Sed  }
4629193326Sed
4630193326Sed  // C++ [class.conv.fct]p4:
4631193326Sed  //   The conversion-type-id shall not represent a function type nor
4632193326Sed  //   an array type.
4633193326Sed  if (ConvType->isArrayType()) {
4634193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4635193326Sed    ConvType = Context.getPointerType(ConvType);
4636193326Sed    D.setInvalidType();
4637193326Sed  } else if (ConvType->isFunctionType()) {
4638193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4639193326Sed    ConvType = Context.getPointerType(ConvType);
4640193326Sed    D.setInvalidType();
4641193326Sed  }
4642193326Sed
4643193326Sed  // Rebuild the function type "R" without any parameters (in case any
4644193326Sed  // of the errors above fired) and with the conversion type as the
4645198092Srdivacky  // return type.
4646218893Sdim  if (D.isInvalidType())
4647218893Sdim    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
4648193326Sed
4649193326Sed  // C++0x explicit conversion operators.
4650193326Sed  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
4651198092Srdivacky    Diag(D.getDeclSpec().getExplicitSpecLoc(),
4652193326Sed         diag::warn_explicit_conversion_functions)
4653193326Sed      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
4654193326Sed}
4655193326Sed
4656193326Sed/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4657193326Sed/// the declaration of the given C++ conversion function. This routine
4658193326Sed/// is responsible for recording the conversion function in the C++
4659193326Sed/// class, if possible.
4660212904SdimDecl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
4661193326Sed  assert(Conversion && "Expected to receive a conversion function declaration");
4662193326Sed
4663193326Sed  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
4664193326Sed
4665193326Sed  // Make sure we aren't redeclaring the conversion function.
4666193326Sed  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
4667193326Sed
4668193326Sed  // C++ [class.conv.fct]p1:
4669193326Sed  //   [...] A conversion function is never used to convert a
4670193326Sed  //   (possibly cv-qualified) object to the (possibly cv-qualified)
4671193326Sed  //   same object type (or a reference to it), to a (possibly
4672193326Sed  //   cv-qualified) base class of that type (or a reference to it),
4673193326Sed  //   or to (possibly cv-qualified) void.
4674193326Sed  // FIXME: Suppress this warning if the conversion function ends up being a
4675193326Sed  // virtual function that overrides a virtual function in a base class.
4676198092Srdivacky  QualType ClassType
4677193326Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4678198092Srdivacky  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
4679193326Sed    ConvType = ConvTypeRef->getPointeeType();
4680218893Sdim  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4681218893Sdim      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4682218893Sdim    /* Suppress diagnostics for instantiations. */;
4683218893Sdim  else if (ConvType->isRecordType()) {
4684193326Sed    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4685193326Sed    if (ConvType == ClassType)
4686193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
4687193326Sed        << ClassType;
4688193326Sed    else if (IsDerivedFrom(ClassType, ConvType))
4689193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
4690193326Sed        <<  ClassType << ConvType;
4691193326Sed  } else if (ConvType->isVoidType()) {
4692193326Sed    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
4693193326Sed      << ClassType << ConvType;
4694193326Sed  }
4695193326Sed
4696218893Sdim  if (FunctionTemplateDecl *ConversionTemplate
4697218893Sdim                                = Conversion->getDescribedFunctionTemplate())
4698218893Sdim    return ConversionTemplate;
4699218893Sdim
4700212904Sdim  return Conversion;
4701193326Sed}
4702193326Sed
4703193326Sed//===----------------------------------------------------------------------===//
4704193326Sed// Namespace Handling
4705193326Sed//===----------------------------------------------------------------------===//
4706193326Sed
4707212904Sdim
4708212904Sdim
4709193326Sed/// ActOnStartNamespaceDef - This is called at the start of a namespace
4710193326Sed/// definition.
4711212904SdimDecl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
4712212904Sdim                                   SourceLocation InlineLoc,
4713221345Sdim                                   SourceLocation NamespaceLoc,
4714212904Sdim                                   SourceLocation IdentLoc,
4715212904Sdim                                   IdentifierInfo *II,
4716212904Sdim                                   SourceLocation LBrace,
4717212904Sdim                                   AttributeList *AttrList) {
4718221345Sdim  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4719221345Sdim  // For anonymous namespace, take the location of the left brace.
4720221345Sdim  SourceLocation Loc = II ? IdentLoc : LBrace;
4721212904Sdim  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
4722221345Sdim                                                 StartLoc, Loc, II);
4723212904Sdim  Namespc->setInline(InlineLoc.isValid());
4724193326Sed
4725193326Sed  Scope *DeclRegionScope = NamespcScope->getParent();
4726193326Sed
4727203955Srdivacky  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4728203955Srdivacky
4729218893Sdim  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4730218893Sdim    PushNamespaceVisibilityAttr(Attr);
4731212904Sdim
4732193326Sed  if (II) {
4733193326Sed    // C++ [namespace.def]p2:
4734218893Sdim    //   The identifier in an original-namespace-definition shall not
4735218893Sdim    //   have been previously defined in the declarative region in
4736218893Sdim    //   which the original-namespace-definition appears. The
4737218893Sdim    //   identifier in an original-namespace-definition is the name of
4738218893Sdim    //   the namespace. Subsequently in that declarative region, it is
4739218893Sdim    //   treated as an original-namespace-name.
4740218893Sdim    //
4741218893Sdim    // Since namespace names are unique in their scope, and we don't
4742223017Sdim    // look through using directives, just look for any ordinary names.
4743223017Sdim
4744223017Sdim    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4745223017Sdim      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4746223017Sdim      Decl::IDNS_Namespace;
4747223017Sdim    NamedDecl *PrevDecl = 0;
4748223017Sdim    for (DeclContext::lookup_result R
4749223017Sdim            = CurContext->getRedeclContext()->lookup(II);
4750223017Sdim         R.first != R.second; ++R.first) {
4751223017Sdim      if ((*R.first)->getIdentifierNamespace() & IDNS) {
4752223017Sdim        PrevDecl = *R.first;
4753223017Sdim        break;
4754223017Sdim      }
4755223017Sdim    }
4756223017Sdim
4757193326Sed    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4758193326Sed      // This is an extended namespace definition.
4759212904Sdim      if (Namespc->isInline() != OrigNS->isInline()) {
4760212904Sdim        // inline-ness must match
4761223017Sdim        if (OrigNS->isInline()) {
4762223017Sdim          // The user probably just forgot the 'inline', so suggest that it
4763223017Sdim          // be added back.
4764223017Sdim          Diag(Namespc->getLocation(),
4765223017Sdim               diag::warn_inline_namespace_reopened_noninline)
4766223017Sdim            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4767223017Sdim        } else {
4768223017Sdim          Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4769223017Sdim            << Namespc->isInline();
4770223017Sdim        }
4771212904Sdim        Diag(OrigNS->getLocation(), diag::note_previous_definition);
4772223017Sdim
4773212904Sdim        // Recover by ignoring the new namespace's inline status.
4774212904Sdim        Namespc->setInline(OrigNS->isInline());
4775212904Sdim      }
4776212904Sdim
4777193326Sed      // Attach this namespace decl to the chain of extended namespace
4778193326Sed      // definitions.
4779193326Sed      OrigNS->setNextNamespace(Namespc);
4780193326Sed      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
4781193326Sed
4782198092Srdivacky      // Remove the previous declaration from the scope.
4783212904Sdim      if (DeclRegionScope->isDeclScope(OrigNS)) {
4784193326Sed        IdResolver.RemoveDecl(OrigNS);
4785212904Sdim        DeclRegionScope->RemoveDecl(OrigNS);
4786193326Sed      }
4787193326Sed    } else if (PrevDecl) {
4788193326Sed      // This is an invalid name redefinition.
4789193326Sed      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4790193326Sed       << Namespc->getDeclName();
4791193326Sed      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4792193326Sed      Namespc->setInvalidDecl();
4793193326Sed      // Continue on to push Namespc as current DeclContext and return it.
4794198092Srdivacky    } else if (II->isStr("std") &&
4795212904Sdim               CurContext->getRedeclContext()->isTranslationUnit()) {
4796198092Srdivacky      // This is the first "real" definition of the namespace "std", so update
4797198092Srdivacky      // our cache of the "std" namespace to point at this definition.
4798212904Sdim      if (NamespaceDecl *StdNS = getStdNamespace()) {
4799198092Srdivacky        // We had already defined a dummy namespace "std". Link this new
4800198092Srdivacky        // namespace definition to the dummy namespace "std".
4801212904Sdim        StdNS->setNextNamespace(Namespc);
4802212904Sdim        StdNS->setLocation(IdentLoc);
4803212904Sdim        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
4804198092Srdivacky      }
4805198092Srdivacky
4806198092Srdivacky      // Make our StdNamespace cache point at the first real definition of the
4807198092Srdivacky      // "std" namespace.
4808198092Srdivacky      StdNamespace = Namespc;
4809198092Srdivacky    }
4810193326Sed
4811193326Sed    PushOnScopeChains(Namespc, DeclRegionScope);
4812193326Sed  } else {
4813198092Srdivacky    // Anonymous namespaces.
4814201361Srdivacky    assert(Namespc->isAnonymousNamespace());
4815198092Srdivacky
4816201361Srdivacky    // Link the anonymous namespace into its parent.
4817201361Srdivacky    NamespaceDecl *PrevDecl;
4818212904Sdim    DeclContext *Parent = CurContext->getRedeclContext();
4819201361Srdivacky    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4820201361Srdivacky      PrevDecl = TU->getAnonymousNamespace();
4821201361Srdivacky      TU->setAnonymousNamespace(Namespc);
4822201361Srdivacky    } else {
4823201361Srdivacky      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4824201361Srdivacky      PrevDecl = ND->getAnonymousNamespace();
4825201361Srdivacky      ND->setAnonymousNamespace(Namespc);
4826201361Srdivacky    }
4827201361Srdivacky
4828201361Srdivacky    // Link the anonymous namespace with its previous declaration.
4829201361Srdivacky    if (PrevDecl) {
4830201361Srdivacky      assert(PrevDecl->isAnonymousNamespace());
4831201361Srdivacky      assert(!PrevDecl->getNextNamespace());
4832201361Srdivacky      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4833201361Srdivacky      PrevDecl->setNextNamespace(Namespc);
4834212904Sdim
4835212904Sdim      if (Namespc->isInline() != PrevDecl->isInline()) {
4836212904Sdim        // inline-ness must match
4837212904Sdim        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4838212904Sdim          << Namespc->isInline();
4839212904Sdim        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4840212904Sdim        Namespc->setInvalidDecl();
4841212904Sdim        // Recover by ignoring the new namespace's inline status.
4842212904Sdim        Namespc->setInline(PrevDecl->isInline());
4843212904Sdim      }
4844201361Srdivacky    }
4845201361Srdivacky
4846206084Srdivacky    CurContext->addDecl(Namespc);
4847206084Srdivacky
4848198092Srdivacky    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
4849198092Srdivacky    //   behaves as if it were replaced by
4850198092Srdivacky    //     namespace unique { /* empty body */ }
4851198092Srdivacky    //     using namespace unique;
4852198092Srdivacky    //     namespace unique { namespace-body }
4853198092Srdivacky    //   where all occurrences of 'unique' in a translation unit are
4854198092Srdivacky    //   replaced by the same identifier and this identifier differs
4855198092Srdivacky    //   from all other identifiers in the entire program.
4856198092Srdivacky
4857198092Srdivacky    // We just create the namespace with an empty name and then add an
4858198092Srdivacky    // implicit using declaration, just like the standard suggests.
4859198092Srdivacky    //
4860198092Srdivacky    // CodeGen enforces the "universally unique" aspect by giving all
4861198092Srdivacky    // declarations semantically contained within an anonymous
4862198092Srdivacky    // namespace internal linkage.
4863198092Srdivacky
4864201361Srdivacky    if (!PrevDecl) {
4865201361Srdivacky      UsingDirectiveDecl* UD
4866201361Srdivacky        = UsingDirectiveDecl::Create(Context, CurContext,
4867201361Srdivacky                                     /* 'using' */ LBrace,
4868201361Srdivacky                                     /* 'namespace' */ SourceLocation(),
4869219077Sdim                                     /* qualifier */ NestedNameSpecifierLoc(),
4870201361Srdivacky                                     /* identifier */ SourceLocation(),
4871201361Srdivacky                                     Namespc,
4872201361Srdivacky                                     /* Ancestor */ CurContext);
4873201361Srdivacky      UD->setImplicit();
4874201361Srdivacky      CurContext->addDecl(UD);
4875201361Srdivacky    }
4876193326Sed  }
4877193326Sed
4878193326Sed  // Although we could have an invalid decl (i.e. the namespace name is a
4879193326Sed  // redefinition), push it as current DeclContext and try to continue parsing.
4880193326Sed  // FIXME: We should be able to push Namespc here, so that the each DeclContext
4881193326Sed  // for the namespace has the declarations that showed up in that particular
4882193326Sed  // namespace definition.
4883193326Sed  PushDeclContext(NamespcScope, Namespc);
4884212904Sdim  return Namespc;
4885193326Sed}
4886193326Sed
4887199990Srdivacky/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4888199990Srdivacky/// is a namespace alias, returns the namespace it points to.
4889199990Srdivackystatic inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4890199990Srdivacky  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4891199990Srdivacky    return AD->getNamespace();
4892199990Srdivacky  return dyn_cast_or_null<NamespaceDecl>(D);
4893199990Srdivacky}
4894199990Srdivacky
4895193326Sed/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4896193326Sed/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
4897212904Sdimvoid Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
4898193326Sed  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4899193326Sed  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
4900221345Sdim  Namespc->setRBraceLoc(RBrace);
4901193326Sed  PopDeclContext();
4902212904Sdim  if (Namespc->hasAttr<VisibilityAttr>())
4903212904Sdim    PopPragmaVisibility();
4904193326Sed}
4905193326Sed
4906212904SdimCXXRecordDecl *Sema::getStdBadAlloc() const {
4907212904Sdim  return cast_or_null<CXXRecordDecl>(
4908212904Sdim                                  StdBadAlloc.get(Context.getExternalSource()));
4909212904Sdim}
4910212904Sdim
4911212904SdimNamespaceDecl *Sema::getStdNamespace() const {
4912212904Sdim  return cast_or_null<NamespaceDecl>(
4913212904Sdim                                 StdNamespace.get(Context.getExternalSource()));
4914212904Sdim}
4915212904Sdim
4916210299Sed/// \brief Retrieve the special "std" namespace, which may require us to
4917210299Sed/// implicitly define the namespace.
4918212904SdimNamespaceDecl *Sema::getOrCreateStdNamespace() {
4919210299Sed  if (!StdNamespace) {
4920210299Sed    // The "std" namespace has not yet been defined, so build one implicitly.
4921210299Sed    StdNamespace = NamespaceDecl::Create(Context,
4922210299Sed                                         Context.getTranslationUnitDecl(),
4923221345Sdim                                         SourceLocation(), SourceLocation(),
4924210299Sed                                         &PP.getIdentifierTable().get("std"));
4925212904Sdim    getStdNamespace()->setImplicit(true);
4926210299Sed  }
4927210299Sed
4928212904Sdim  return getStdNamespace();
4929210299Sed}
4930210299Sed
4931221345Sdim/// \brief Determine whether a using statement is in a context where it will be
4932221345Sdim/// apply in all contexts.
4933221345Sdimstatic bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4934221345Sdim  switch (CurContext->getDeclKind()) {
4935221345Sdim    case Decl::TranslationUnit:
4936221345Sdim      return true;
4937221345Sdim    case Decl::LinkageSpec:
4938221345Sdim      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4939221345Sdim    default:
4940221345Sdim      return false;
4941221345Sdim  }
4942221345Sdim}
4943221345Sdim
4944212904SdimDecl *Sema::ActOnUsingDirective(Scope *S,
4945193326Sed                                          SourceLocation UsingLoc,
4946193326Sed                                          SourceLocation NamespcLoc,
4947207619Srdivacky                                          CXXScopeSpec &SS,
4948193326Sed                                          SourceLocation IdentLoc,
4949193326Sed                                          IdentifierInfo *NamespcName,
4950193326Sed                                          AttributeList *AttrList) {
4951193326Sed  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4952193326Sed  assert(NamespcName && "Invalid NamespcName.");
4953193326Sed  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
4954218893Sdim
4955218893Sdim  // This can only happen along a recovery path.
4956218893Sdim  while (S->getFlags() & Scope::TemplateParamScope)
4957218893Sdim    S = S->getParent();
4958193326Sed  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4959193326Sed
4960193326Sed  UsingDirectiveDecl *UDir = 0;
4961210299Sed  NestedNameSpecifier *Qualifier = 0;
4962210299Sed  if (SS.isSet())
4963210299Sed    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4964210299Sed
4965193326Sed  // Lookup namespace name.
4966199482Srdivacky  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4967199482Srdivacky  LookupParsedName(R, S, &SS);
4968199482Srdivacky  if (R.isAmbiguous())
4969212904Sdim    return 0;
4970199482Srdivacky
4971210299Sed  if (R.empty()) {
4972210299Sed    // Allow "using namespace std;" or "using namespace ::std;" even if
4973210299Sed    // "std" hasn't been defined yet, for GCC compatibility.
4974210299Sed    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4975210299Sed        NamespcName->isStr("std")) {
4976210299Sed      Diag(IdentLoc, diag::ext_using_undefined_std);
4977212904Sdim      R.addDecl(getOrCreateStdNamespace());
4978210299Sed      R.resolveKind();
4979210299Sed    }
4980210299Sed    // Otherwise, attempt typo correction.
4981210299Sed    else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4982210299Sed                                                       CTC_NoKeywords, 0)) {
4983210299Sed      if (R.getAsSingle<NamespaceDecl>() ||
4984210299Sed          R.getAsSingle<NamespaceAliasDecl>()) {
4985210299Sed        if (DeclContext *DC = computeDeclContext(SS, false))
4986210299Sed          Diag(IdentLoc, diag::err_using_directive_member_suggest)
4987210299Sed            << NamespcName << DC << Corrected << SS.getRange()
4988210299Sed            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4989210299Sed        else
4990210299Sed          Diag(IdentLoc, diag::err_using_directive_suggest)
4991210299Sed            << NamespcName << Corrected
4992210299Sed            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4993210299Sed        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4994210299Sed          << Corrected;
4995210299Sed
4996210299Sed        NamespcName = Corrected.getAsIdentifierInfo();
4997210299Sed      } else {
4998210299Sed        R.clear();
4999210299Sed        R.setLookupName(NamespcName);
5000210299Sed      }
5001210299Sed    }
5002210299Sed  }
5003210299Sed
5004198092Srdivacky  if (!R.empty()) {
5005199990Srdivacky    NamedDecl *Named = R.getFoundDecl();
5006199990Srdivacky    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5007199990Srdivacky        && "expected namespace decl");
5008193326Sed    // C++ [namespace.udir]p1:
5009193326Sed    //   A using-directive specifies that the names in the nominated
5010193326Sed    //   namespace can be used in the scope in which the
5011193326Sed    //   using-directive appears after the using-directive. During
5012193326Sed    //   unqualified name lookup (3.4.1), the names appear as if they
5013193326Sed    //   were declared in the nearest enclosing namespace which
5014193326Sed    //   contains both the using-directive and the nominated
5015198092Srdivacky    //   namespace. [Note: in this context, "contains" means "contains
5016198092Srdivacky    //   directly or indirectly". ]
5017193326Sed
5018193326Sed    // Find enclosing context containing both using-directive and
5019193326Sed    // nominated namespace.
5020199990Srdivacky    NamespaceDecl *NS = getNamespaceDecl(Named);
5021193326Sed    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5022193326Sed    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5023193326Sed      CommonAncestor = CommonAncestor->getParent();
5024193326Sed
5025199990Srdivacky    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5026219077Sdim                                      SS.getWithLocInContext(Context),
5027199990Srdivacky                                      IdentLoc, Named, CommonAncestor);
5028221345Sdim
5029221345Sdim    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5030221345Sdim        !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
5031221345Sdim      Diag(IdentLoc, diag::warn_using_directive_in_header);
5032221345Sdim    }
5033221345Sdim
5034193326Sed    PushUsingDirective(S, UDir);
5035193326Sed  } else {
5036193326Sed    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5037193326Sed  }
5038193326Sed
5039193326Sed  // FIXME: We ignore attributes for now.
5040212904Sdim  return UDir;
5041193326Sed}
5042193326Sed
5043193326Sedvoid Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5044193326Sed  // If scope has associated entity, then using directive is at namespace
5045193326Sed  // or translation unit scope. We add UsingDirectiveDecls, into
5046193326Sed  // it's lookup structure.
5047193326Sed  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5048195341Sed    Ctx->addDecl(UDir);
5049193326Sed  else
5050193326Sed    // Otherwise it is block-sope. using-directives will affect lookup
5051193326Sed    // only to the end of scope.
5052212904Sdim    S->PushUsingDirective(UDir);
5053193326Sed}
5054193326Sed
5055194613Sed
5056212904SdimDecl *Sema::ActOnUsingDeclaration(Scope *S,
5057218893Sdim                                  AccessSpecifier AS,
5058218893Sdim                                  bool HasUsingKeyword,
5059218893Sdim                                  SourceLocation UsingLoc,
5060218893Sdim                                  CXXScopeSpec &SS,
5061218893Sdim                                  UnqualifiedId &Name,
5062218893Sdim                                  AttributeList *AttrList,
5063218893Sdim                                  bool IsTypeName,
5064218893Sdim                                  SourceLocation TypenameLoc) {
5065194613Sed  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5066194613Sed
5067198954Srdivacky  switch (Name.getKind()) {
5068198954Srdivacky  case UnqualifiedId::IK_Identifier:
5069198954Srdivacky  case UnqualifiedId::IK_OperatorFunctionId:
5070199990Srdivacky  case UnqualifiedId::IK_LiteralOperatorId:
5071198954Srdivacky  case UnqualifiedId::IK_ConversionFunctionId:
5072198954Srdivacky    break;
5073198954Srdivacky
5074198954Srdivacky  case UnqualifiedId::IK_ConstructorName:
5075202379Srdivacky  case UnqualifiedId::IK_ConstructorTemplateId:
5076200583Srdivacky    // C++0x inherited constructors.
5077200583Srdivacky    if (getLangOptions().CPlusPlus0x) break;
5078200583Srdivacky
5079198954Srdivacky    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5080198954Srdivacky      << SS.getRange();
5081212904Sdim    return 0;
5082198954Srdivacky
5083198954Srdivacky  case UnqualifiedId::IK_DestructorName:
5084198954Srdivacky    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5085198954Srdivacky      << SS.getRange();
5086212904Sdim    return 0;
5087198954Srdivacky
5088198954Srdivacky  case UnqualifiedId::IK_TemplateId:
5089198954Srdivacky    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5090198954Srdivacky      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5091212904Sdim    return 0;
5092198954Srdivacky  }
5093212904Sdim
5094212904Sdim  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5095212904Sdim  DeclarationName TargetName = TargetNameInfo.getName();
5096200583Srdivacky  if (!TargetName)
5097212904Sdim    return 0;
5098200583Srdivacky
5099200583Srdivacky  // Warn about using declarations.
5100200583Srdivacky  // TODO: store that the declaration was written without 'using' and
5101200583Srdivacky  // talk about access decls instead of using decls in the
5102200583Srdivacky  // diagnostics.
5103200583Srdivacky  if (!HasUsingKeyword) {
5104200583Srdivacky    UsingLoc = Name.getSourceRange().getBegin();
5105200583Srdivacky
5106200583Srdivacky    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5107206084Srdivacky      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5108200583Srdivacky  }
5109200583Srdivacky
5110218893Sdim  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5111218893Sdim      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5112218893Sdim    return 0;
5113218893Sdim
5114199482Srdivacky  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5115212904Sdim                                        TargetNameInfo, AttrList,
5116199482Srdivacky                                        /* IsInstantiation */ false,
5117199482Srdivacky                                        IsTypeName, TypenameLoc);
5118200583Srdivacky  if (UD)
5119200583Srdivacky    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5120198092Srdivacky
5121212904Sdim  return UD;
5122198092Srdivacky}
5123198092Srdivacky
5124210299Sed/// \brief Determine whether a using declaration considers the given
5125210299Sed/// declarations as "equivalent", e.g., if they are redeclarations of
5126210299Sed/// the same entity or are both typedefs of the same type.
5127210299Sedstatic bool
5128210299SedIsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5129210299Sed                         bool &SuppressRedeclaration) {
5130210299Sed  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5131210299Sed    SuppressRedeclaration = false;
5132210299Sed    return true;
5133210299Sed  }
5134210299Sed
5135221345Sdim  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5136221345Sdim    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5137210299Sed      SuppressRedeclaration = true;
5138210299Sed      return Context.hasSameType(TD1->getUnderlyingType(),
5139210299Sed                                 TD2->getUnderlyingType());
5140210299Sed    }
5141210299Sed
5142210299Sed  return false;
5143210299Sed}
5144210299Sed
5145210299Sed
5146200583Srdivacky/// Determines whether to create a using shadow decl for a particular
5147200583Srdivacky/// decl, given the set of decls existing prior to this using lookup.
5148200583Srdivackybool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5149200583Srdivacky                                const LookupResult &Previous) {
5150200583Srdivacky  // Diagnose finding a decl which is not from a base class of the
5151200583Srdivacky  // current class.  We do this now because there are cases where this
5152200583Srdivacky  // function will silently decide not to build a shadow decl, which
5153200583Srdivacky  // will pre-empt further diagnostics.
5154200583Srdivacky  //
5155200583Srdivacky  // We don't need to do this in C++0x because we do the check once on
5156200583Srdivacky  // the qualifier.
5157200583Srdivacky  //
5158200583Srdivacky  // FIXME: diagnose the following if we care enough:
5159200583Srdivacky  //   struct A { int foo; };
5160200583Srdivacky  //   struct B : A { using A::foo; };
5161200583Srdivacky  //   template <class T> struct C : A {};
5162200583Srdivacky  //   template <class T> struct D : C<T> { using B::foo; } // <---
5163200583Srdivacky  // This is invalid (during instantiation) in C++03 because B::foo
5164200583Srdivacky  // resolves to the using decl in B, which is not a base class of D<T>.
5165200583Srdivacky  // We can't diagnose it immediately because C<T> is an unknown
5166200583Srdivacky  // specialization.  The UsingShadowDecl in D<T> then points directly
5167200583Srdivacky  // to A::foo, which will look well-formed when we instantiate.
5168200583Srdivacky  // The right solution is to not collapse the shadow-decl chain.
5169200583Srdivacky  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5170200583Srdivacky    DeclContext *OrigDC = Orig->getDeclContext();
5171200583Srdivacky
5172200583Srdivacky    // Handle enums and anonymous structs.
5173200583Srdivacky    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5174200583Srdivacky    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5175200583Srdivacky    while (OrigRec->isAnonymousStructOrUnion())
5176200583Srdivacky      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5177200583Srdivacky
5178200583Srdivacky    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5179200583Srdivacky      if (OrigDC == CurContext) {
5180200583Srdivacky        Diag(Using->getLocation(),
5181200583Srdivacky             diag::err_using_decl_nested_name_specifier_is_current_class)
5182219077Sdim          << Using->getQualifierLoc().getSourceRange();
5183200583Srdivacky        Diag(Orig->getLocation(), diag::note_using_decl_target);
5184200583Srdivacky        return true;
5185200583Srdivacky      }
5186200583Srdivacky
5187219077Sdim      Diag(Using->getQualifierLoc().getBeginLoc(),
5188200583Srdivacky           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5189219077Sdim        << Using->getQualifier()
5190200583Srdivacky        << cast<CXXRecordDecl>(CurContext)
5191219077Sdim        << Using->getQualifierLoc().getSourceRange();
5192200583Srdivacky      Diag(Orig->getLocation(), diag::note_using_decl_target);
5193200583Srdivacky      return true;
5194200583Srdivacky    }
5195200583Srdivacky  }
5196200583Srdivacky
5197200583Srdivacky  if (Previous.empty()) return false;
5198200583Srdivacky
5199200583Srdivacky  NamedDecl *Target = Orig;
5200200583Srdivacky  if (isa<UsingShadowDecl>(Target))
5201200583Srdivacky    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5202200583Srdivacky
5203200583Srdivacky  // If the target happens to be one of the previous declarations, we
5204200583Srdivacky  // don't have a conflict.
5205200583Srdivacky  //
5206200583Srdivacky  // FIXME: but we might be increasing its access, in which case we
5207200583Srdivacky  // should redeclare it.
5208200583Srdivacky  NamedDecl *NonTag = 0, *Tag = 0;
5209200583Srdivacky  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5210200583Srdivacky         I != E; ++I) {
5211200583Srdivacky    NamedDecl *D = (*I)->getUnderlyingDecl();
5212210299Sed    bool Result;
5213210299Sed    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5214210299Sed      return Result;
5215200583Srdivacky
5216200583Srdivacky    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5217200583Srdivacky  }
5218200583Srdivacky
5219200583Srdivacky  if (Target->isFunctionOrFunctionTemplate()) {
5220200583Srdivacky    FunctionDecl *FD;
5221200583Srdivacky    if (isa<FunctionTemplateDecl>(Target))
5222200583Srdivacky      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5223200583Srdivacky    else
5224200583Srdivacky      FD = cast<FunctionDecl>(Target);
5225200583Srdivacky
5226200583Srdivacky    NamedDecl *OldDecl = 0;
5227210299Sed    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5228200583Srdivacky    case Ovl_Overload:
5229200583Srdivacky      return false;
5230200583Srdivacky
5231200583Srdivacky    case Ovl_NonFunction:
5232200583Srdivacky      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5233200583Srdivacky      break;
5234200583Srdivacky
5235200583Srdivacky    // We found a decl with the exact signature.
5236200583Srdivacky    case Ovl_Match:
5237200583Srdivacky      // If we're in a record, we want to hide the target, so we
5238200583Srdivacky      // return true (without a diagnostic) to tell the caller not to
5239200583Srdivacky      // build a shadow decl.
5240200583Srdivacky      if (CurContext->isRecord())
5241200583Srdivacky        return true;
5242200583Srdivacky
5243200583Srdivacky      // If we're not in a record, this is an error.
5244200583Srdivacky      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5245200583Srdivacky      break;
5246200583Srdivacky    }
5247200583Srdivacky
5248200583Srdivacky    Diag(Target->getLocation(), diag::note_using_decl_target);
5249200583Srdivacky    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5250200583Srdivacky    return true;
5251200583Srdivacky  }
5252200583Srdivacky
5253200583Srdivacky  // Target is not a function.
5254200583Srdivacky
5255200583Srdivacky  if (isa<TagDecl>(Target)) {
5256200583Srdivacky    // No conflict between a tag and a non-tag.
5257200583Srdivacky    if (!Tag) return false;
5258200583Srdivacky
5259200583Srdivacky    Diag(Using->getLocation(), diag::err_using_decl_conflict);
5260200583Srdivacky    Diag(Target->getLocation(), diag::note_using_decl_target);
5261200583Srdivacky    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5262200583Srdivacky    return true;
5263200583Srdivacky  }
5264200583Srdivacky
5265200583Srdivacky  // No conflict between a tag and a non-tag.
5266200583Srdivacky  if (!NonTag) return false;
5267200583Srdivacky
5268200583Srdivacky  Diag(Using->getLocation(), diag::err_using_decl_conflict);
5269200583Srdivacky  Diag(Target->getLocation(), diag::note_using_decl_target);
5270200583Srdivacky  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5271200583Srdivacky  return true;
5272200583Srdivacky}
5273200583Srdivacky
5274199482Srdivacky/// Builds a shadow declaration corresponding to a 'using' declaration.
5275200583SrdivackyUsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5276200583Srdivacky                                            UsingDecl *UD,
5277200583Srdivacky                                            NamedDecl *Orig) {
5278199482Srdivacky
5279199482Srdivacky  // If we resolved to another shadow declaration, just coalesce them.
5280200583Srdivacky  NamedDecl *Target = Orig;
5281200583Srdivacky  if (isa<UsingShadowDecl>(Target)) {
5282200583Srdivacky    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5283200583Srdivacky    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5284199482Srdivacky  }
5285199482Srdivacky
5286199482Srdivacky  UsingShadowDecl *Shadow
5287200583Srdivacky    = UsingShadowDecl::Create(Context, CurContext,
5288200583Srdivacky                              UD->getLocation(), UD, Target);
5289199482Srdivacky  UD->addShadowDecl(Shadow);
5290218893Sdim
5291218893Sdim  Shadow->setAccess(UD->getAccess());
5292218893Sdim  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5293218893Sdim    Shadow->setInvalidDecl();
5294218893Sdim
5295199482Srdivacky  if (S)
5296200583Srdivacky    PushOnScopeChains(Shadow, S);
5297199482Srdivacky  else
5298200583Srdivacky    CurContext->addDecl(Shadow);
5299199482Srdivacky
5300206084Srdivacky
5301199482Srdivacky  return Shadow;
5302199482Srdivacky}
5303199482Srdivacky
5304200583Srdivacky/// Hides a using shadow declaration.  This is required by the current
5305200583Srdivacky/// using-decl implementation when a resolvable using declaration in a
5306200583Srdivacky/// class is followed by a declaration which would hide or override
5307200583Srdivacky/// one or more of the using decl's targets; for example:
5308200583Srdivacky///
5309200583Srdivacky///   struct Base { void foo(int); };
5310200583Srdivacky///   struct Derived : Base {
5311200583Srdivacky///     using Base::foo;
5312200583Srdivacky///     void foo(int);
5313200583Srdivacky///   };
5314200583Srdivacky///
5315200583Srdivacky/// The governing language is C++03 [namespace.udecl]p12:
5316200583Srdivacky///
5317200583Srdivacky///   When a using-declaration brings names from a base class into a
5318200583Srdivacky///   derived class scope, member functions in the derived class
5319200583Srdivacky///   override and/or hide member functions with the same name and
5320200583Srdivacky///   parameter types in a base class (rather than conflicting).
5321200583Srdivacky///
5322200583Srdivacky/// There are two ways to implement this:
5323200583Srdivacky///   (1) optimistically create shadow decls when they're not hidden
5324200583Srdivacky///       by existing declarations, or
5325200583Srdivacky///   (2) don't create any shadow decls (or at least don't make them
5326200583Srdivacky///       visible) until we've fully parsed/instantiated the class.
5327200583Srdivacky/// The problem with (1) is that we might have to retroactively remove
5328200583Srdivacky/// a shadow decl, which requires several O(n) operations because the
5329200583Srdivacky/// decl structures are (very reasonably) not designed for removal.
5330200583Srdivacky/// (2) avoids this but is very fiddly and phase-dependent.
5331200583Srdivackyvoid Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5332206084Srdivacky  if (Shadow->getDeclName().getNameKind() ==
5333206084Srdivacky        DeclarationName::CXXConversionFunctionName)
5334206084Srdivacky    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5335206084Srdivacky
5336200583Srdivacky  // Remove it from the DeclContext...
5337200583Srdivacky  Shadow->getDeclContext()->removeDecl(Shadow);
5338200583Srdivacky
5339200583Srdivacky  // ...and the scope, if applicable...
5340200583Srdivacky  if (S) {
5341212904Sdim    S->RemoveDecl(Shadow);
5342200583Srdivacky    IdResolver.RemoveDecl(Shadow);
5343200583Srdivacky  }
5344200583Srdivacky
5345200583Srdivacky  // ...and the using decl.
5346200583Srdivacky  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5347200583Srdivacky
5348200583Srdivacky  // TODO: complain somehow if Shadow was used.  It shouldn't
5349206084Srdivacky  // be possible for this to happen, because...?
5350200583Srdivacky}
5351200583Srdivacky
5352199482Srdivacky/// Builds a using declaration.
5353199482Srdivacky///
5354199482Srdivacky/// \param IsInstantiation - Whether this call arises from an
5355199482Srdivacky///   instantiation of an unresolved using declaration.  We treat
5356199482Srdivacky///   the lookup differently for these declarations.
5357199482SrdivackyNamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5358199482Srdivacky                                       SourceLocation UsingLoc,
5359207619Srdivacky                                       CXXScopeSpec &SS,
5360212904Sdim                                       const DeclarationNameInfo &NameInfo,
5361198092Srdivacky                                       AttributeList *AttrList,
5362199482Srdivacky                                       bool IsInstantiation,
5363199482Srdivacky                                       bool IsTypeName,
5364199482Srdivacky                                       SourceLocation TypenameLoc) {
5365198092Srdivacky  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5366212904Sdim  SourceLocation IdentLoc = NameInfo.getLoc();
5367198092Srdivacky  assert(IdentLoc.isValid() && "Invalid TargetName location.");
5368198092Srdivacky
5369198092Srdivacky  // FIXME: We ignore attributes for now.
5370198092Srdivacky
5371198092Srdivacky  if (SS.isEmpty()) {
5372198092Srdivacky    Diag(IdentLoc, diag::err_using_requires_qualname);
5373198092Srdivacky    return 0;
5374198092Srdivacky  }
5375198092Srdivacky
5376200583Srdivacky  // Do the redeclaration lookup in the current scope.
5377212904Sdim  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5378200583Srdivacky                        ForRedeclaration);
5379200583Srdivacky  Previous.setHideTags(false);
5380200583Srdivacky  if (S) {
5381200583Srdivacky    LookupName(Previous, S);
5382200583Srdivacky
5383200583Srdivacky    // It is really dumb that we have to do this.
5384200583Srdivacky    LookupResult::Filter F = Previous.makeFilter();
5385200583Srdivacky    while (F.hasNext()) {
5386200583Srdivacky      NamedDecl *D = F.next();
5387200583Srdivacky      if (!isDeclInScope(D, CurContext, S))
5388200583Srdivacky        F.erase();
5389200583Srdivacky    }
5390200583Srdivacky    F.done();
5391200583Srdivacky  } else {
5392200583Srdivacky    assert(IsInstantiation && "no scope in non-instantiation");
5393200583Srdivacky    assert(CurContext->isRecord() && "scope not record in instantiation");
5394200583Srdivacky    LookupQualifiedName(Previous, CurContext);
5395200583Srdivacky  }
5396200583Srdivacky
5397200583Srdivacky  // Check for invalid redeclarations.
5398200583Srdivacky  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5399200583Srdivacky    return 0;
5400200583Srdivacky
5401200583Srdivacky  // Check for bad qualifiers.
5402200583Srdivacky  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5403200583Srdivacky    return 0;
5404200583Srdivacky
5405199482Srdivacky  DeclContext *LookupContext = computeDeclContext(SS);
5406200583Srdivacky  NamedDecl *D;
5407219077Sdim  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5408199482Srdivacky  if (!LookupContext) {
5409199482Srdivacky    if (IsTypeName) {
5410200583Srdivacky      // FIXME: not all declaration name kinds are legal here
5411200583Srdivacky      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5412200583Srdivacky                                              UsingLoc, TypenameLoc,
5413219077Sdim                                              QualifierLoc,
5414212904Sdim                                              IdentLoc, NameInfo.getName());
5415199482Srdivacky    } else {
5416219077Sdim      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5417219077Sdim                                           QualifierLoc, NameInfo);
5418199482Srdivacky    }
5419200583Srdivacky  } else {
5420219077Sdim    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5421219077Sdim                          NameInfo, IsTypeName);
5422198092Srdivacky  }
5423200583Srdivacky  D->setAccess(AS);
5424200583Srdivacky  CurContext->addDecl(D);
5425198092Srdivacky
5426200583Srdivacky  if (!LookupContext) return D;
5427200583Srdivacky  UsingDecl *UD = cast<UsingDecl>(D);
5428200583Srdivacky
5429207619Srdivacky  if (RequireCompleteDeclContext(SS, LookupContext)) {
5430200583Srdivacky    UD->setInvalidDecl();
5431200583Srdivacky    return UD;
5432194613Sed  }
5433194613Sed
5434218893Sdim  // Constructor inheriting using decls get special treatment.
5435218893Sdim  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5436218893Sdim    if (CheckInheritedConstructorUsingDecl(UD))
5437218893Sdim      UD->setInvalidDecl();
5438218893Sdim    return UD;
5439218893Sdim  }
5440200583Srdivacky
5441218893Sdim  // Otherwise, look up the target name.
5442218893Sdim
5443212904Sdim  LookupResult R(*this, NameInfo, LookupOrdinaryName);
5444223017Sdim  R.setUsingDeclaration(true);
5445198092Srdivacky
5446200583Srdivacky  // Unlike most lookups, we don't always want to hide tag
5447200583Srdivacky  // declarations: tag names are visible through the using declaration
5448200583Srdivacky  // even if hidden by ordinary names, *except* in a dependent context
5449200583Srdivacky  // where it's important for the sanity of two-phase lookup.
5450199482Srdivacky  if (!IsInstantiation)
5451199482Srdivacky    R.setHideTags(false);
5452198092Srdivacky
5453199482Srdivacky  LookupQualifiedName(R, LookupContext);
5454199482Srdivacky
5455198092Srdivacky  if (R.empty()) {
5456198092Srdivacky    Diag(IdentLoc, diag::err_no_member)
5457212904Sdim      << NameInfo.getName() << LookupContext << SS.getRange();
5458200583Srdivacky    UD->setInvalidDecl();
5459200583Srdivacky    return UD;
5460198092Srdivacky  }
5461198092Srdivacky
5462200583Srdivacky  if (R.isAmbiguous()) {
5463200583Srdivacky    UD->setInvalidDecl();
5464200583Srdivacky    return UD;
5465200583Srdivacky  }
5466198092Srdivacky
5467199482Srdivacky  if (IsTypeName) {
5468199482Srdivacky    // If we asked for a typename and got a non-type decl, error out.
5469200583Srdivacky    if (!R.getAsSingle<TypeDecl>()) {
5470199482Srdivacky      Diag(IdentLoc, diag::err_using_typename_non_type);
5471199482Srdivacky      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5472199482Srdivacky        Diag((*I)->getUnderlyingDecl()->getLocation(),
5473199482Srdivacky             diag::note_using_decl_target);
5474200583Srdivacky      UD->setInvalidDecl();
5475200583Srdivacky      return UD;
5476199482Srdivacky    }
5477199482Srdivacky  } else {
5478199482Srdivacky    // If we asked for a non-typename and we got a type, error out,
5479199482Srdivacky    // but only if this is an instantiation of an unresolved using
5480199482Srdivacky    // decl.  Otherwise just silently find the type name.
5481200583Srdivacky    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5482199482Srdivacky      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5483199482Srdivacky      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5484200583Srdivacky      UD->setInvalidDecl();
5485200583Srdivacky      return UD;
5486199482Srdivacky    }
5487198092Srdivacky  }
5488198092Srdivacky
5489198092Srdivacky  // C++0x N2914 [namespace.udecl]p6:
5490198092Srdivacky  // A using-declaration shall not name a namespace.
5491200583Srdivacky  if (R.getAsSingle<NamespaceDecl>()) {
5492198092Srdivacky    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5493198092Srdivacky      << SS.getRange();
5494200583Srdivacky    UD->setInvalidDecl();
5495200583Srdivacky    return UD;
5496198092Srdivacky  }
5497198092Srdivacky
5498200583Srdivacky  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5499200583Srdivacky    if (!CheckUsingShadowDecl(UD, *I, Previous))
5500200583Srdivacky      BuildUsingShadowDecl(S, UD, *I);
5501200583Srdivacky  }
5502199482Srdivacky
5503199482Srdivacky  return UD;
5504194613Sed}
5505194613Sed
5506218893Sdim/// Additional checks for a using declaration referring to a constructor name.
5507218893Sdimbool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5508218893Sdim  if (UD->isTypeName()) {
5509218893Sdim    // FIXME: Cannot specify typename when specifying constructor
5510218893Sdim    return true;
5511218893Sdim  }
5512218893Sdim
5513219077Sdim  const Type *SourceType = UD->getQualifier()->getAsType();
5514218893Sdim  assert(SourceType &&
5515218893Sdim         "Using decl naming constructor doesn't have type in scope spec.");
5516218893Sdim  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5517218893Sdim
5518218893Sdim  // Check whether the named type is a direct base class.
5519218893Sdim  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5520218893Sdim  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5521218893Sdim  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5522218893Sdim       BaseIt != BaseE; ++BaseIt) {
5523218893Sdim    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5524218893Sdim    if (CanonicalSourceType == BaseType)
5525218893Sdim      break;
5526218893Sdim  }
5527218893Sdim
5528218893Sdim  if (BaseIt == BaseE) {
5529218893Sdim    // Did not find SourceType in the bases.
5530218893Sdim    Diag(UD->getUsingLocation(),
5531218893Sdim         diag::err_using_decl_constructor_not_in_direct_base)
5532218893Sdim      << UD->getNameInfo().getSourceRange()
5533218893Sdim      << QualType(SourceType, 0) << TargetClass;
5534218893Sdim    return true;
5535218893Sdim  }
5536218893Sdim
5537218893Sdim  BaseIt->setInheritConstructors();
5538218893Sdim
5539218893Sdim  return false;
5540218893Sdim}
5541218893Sdim
5542200583Srdivacky/// Checks that the given using declaration is not an invalid
5543200583Srdivacky/// redeclaration.  Note that this is checking only for the using decl
5544200583Srdivacky/// itself, not for any ill-formedness among the UsingShadowDecls.
5545200583Srdivackybool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5546200583Srdivacky                                       bool isTypeName,
5547200583Srdivacky                                       const CXXScopeSpec &SS,
5548200583Srdivacky                                       SourceLocation NameLoc,
5549200583Srdivacky                                       const LookupResult &Prev) {
5550200583Srdivacky  // C++03 [namespace.udecl]p8:
5551200583Srdivacky  // C++0x [namespace.udecl]p10:
5552200583Srdivacky  //   A using-declaration is a declaration and can therefore be used
5553200583Srdivacky  //   repeatedly where (and only where) multiple declarations are
5554200583Srdivacky  //   allowed.
5555208600Srdivacky  //
5556208600Srdivacky  // That's in non-member contexts.
5557212904Sdim  if (!CurContext->getRedeclContext()->isRecord())
5558200583Srdivacky    return false;
5559200583Srdivacky
5560200583Srdivacky  NestedNameSpecifier *Qual
5561200583Srdivacky    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5562200583Srdivacky
5563200583Srdivacky  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5564200583Srdivacky    NamedDecl *D = *I;
5565200583Srdivacky
5566200583Srdivacky    bool DTypename;
5567200583Srdivacky    NestedNameSpecifier *DQual;
5568200583Srdivacky    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5569200583Srdivacky      DTypename = UD->isTypeName();
5570219077Sdim      DQual = UD->getQualifier();
5571200583Srdivacky    } else if (UnresolvedUsingValueDecl *UD
5572200583Srdivacky                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5573200583Srdivacky      DTypename = false;
5574219077Sdim      DQual = UD->getQualifier();
5575200583Srdivacky    } else if (UnresolvedUsingTypenameDecl *UD
5576200583Srdivacky                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5577200583Srdivacky      DTypename = true;
5578219077Sdim      DQual = UD->getQualifier();
5579200583Srdivacky    } else continue;
5580200583Srdivacky
5581200583Srdivacky    // using decls differ if one says 'typename' and the other doesn't.
5582200583Srdivacky    // FIXME: non-dependent using decls?
5583200583Srdivacky    if (isTypeName != DTypename) continue;
5584200583Srdivacky
5585200583Srdivacky    // using decls differ if they name different scopes (but note that
5586200583Srdivacky    // template instantiation can cause this check to trigger when it
5587200583Srdivacky    // didn't before instantiation).
5588200583Srdivacky    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5589200583Srdivacky        Context.getCanonicalNestedNameSpecifier(DQual))
5590200583Srdivacky      continue;
5591200583Srdivacky
5592200583Srdivacky    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
5593200583Srdivacky    Diag(D->getLocation(), diag::note_using_decl) << 1;
5594200583Srdivacky    return true;
5595200583Srdivacky  }
5596200583Srdivacky
5597200583Srdivacky  return false;
5598200583Srdivacky}
5599200583Srdivacky
5600200583Srdivacky
5601200583Srdivacky/// Checks that the given nested-name qualifier used in a using decl
5602200583Srdivacky/// in the current context is appropriately related to the current
5603200583Srdivacky/// scope.  If an error is found, diagnoses it and returns true.
5604200583Srdivackybool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5605200583Srdivacky                                   const CXXScopeSpec &SS,
5606200583Srdivacky                                   SourceLocation NameLoc) {
5607200583Srdivacky  DeclContext *NamedContext = computeDeclContext(SS);
5608200583Srdivacky
5609200583Srdivacky  if (!CurContext->isRecord()) {
5610200583Srdivacky    // C++03 [namespace.udecl]p3:
5611200583Srdivacky    // C++0x [namespace.udecl]p8:
5612200583Srdivacky    //   A using-declaration for a class member shall be a member-declaration.
5613200583Srdivacky
5614200583Srdivacky    // If we weren't able to compute a valid scope, it must be a
5615200583Srdivacky    // dependent class scope.
5616200583Srdivacky    if (!NamedContext || NamedContext->isRecord()) {
5617200583Srdivacky      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5618200583Srdivacky        << SS.getRange();
5619200583Srdivacky      return true;
5620200583Srdivacky    }
5621200583Srdivacky
5622200583Srdivacky    // Otherwise, everything is known to be fine.
5623200583Srdivacky    return false;
5624200583Srdivacky  }
5625200583Srdivacky
5626200583Srdivacky  // The current scope is a record.
5627200583Srdivacky
5628200583Srdivacky  // If the named context is dependent, we can't decide much.
5629200583Srdivacky  if (!NamedContext) {
5630200583Srdivacky    // FIXME: in C++0x, we can diagnose if we can prove that the
5631200583Srdivacky    // nested-name-specifier does not refer to a base class, which is
5632200583Srdivacky    // still possible in some cases.
5633200583Srdivacky
5634200583Srdivacky    // Otherwise we have to conservatively report that things might be
5635200583Srdivacky    // okay.
5636200583Srdivacky    return false;
5637200583Srdivacky  }
5638200583Srdivacky
5639200583Srdivacky  if (!NamedContext->isRecord()) {
5640200583Srdivacky    // Ideally this would point at the last name in the specifier,
5641200583Srdivacky    // but we don't have that level of source info.
5642200583Srdivacky    Diag(SS.getRange().getBegin(),
5643200583Srdivacky         diag::err_using_decl_nested_name_specifier_is_not_class)
5644200583Srdivacky      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5645200583Srdivacky    return true;
5646200583Srdivacky  }
5647200583Srdivacky
5648218893Sdim  if (!NamedContext->isDependentContext() &&
5649218893Sdim      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5650218893Sdim    return true;
5651218893Sdim
5652200583Srdivacky  if (getLangOptions().CPlusPlus0x) {
5653200583Srdivacky    // C++0x [namespace.udecl]p3:
5654200583Srdivacky    //   In a using-declaration used as a member-declaration, the
5655200583Srdivacky    //   nested-name-specifier shall name a base class of the class
5656200583Srdivacky    //   being defined.
5657200583Srdivacky
5658200583Srdivacky    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5659200583Srdivacky                                 cast<CXXRecordDecl>(NamedContext))) {
5660200583Srdivacky      if (CurContext == NamedContext) {
5661200583Srdivacky        Diag(NameLoc,
5662200583Srdivacky             diag::err_using_decl_nested_name_specifier_is_current_class)
5663200583Srdivacky          << SS.getRange();
5664200583Srdivacky        return true;
5665200583Srdivacky      }
5666200583Srdivacky
5667200583Srdivacky      Diag(SS.getRange().getBegin(),
5668200583Srdivacky           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5669200583Srdivacky        << (NestedNameSpecifier*) SS.getScopeRep()
5670200583Srdivacky        << cast<CXXRecordDecl>(CurContext)
5671200583Srdivacky        << SS.getRange();
5672200583Srdivacky      return true;
5673200583Srdivacky    }
5674200583Srdivacky
5675200583Srdivacky    return false;
5676200583Srdivacky  }
5677200583Srdivacky
5678200583Srdivacky  // C++03 [namespace.udecl]p4:
5679200583Srdivacky  //   A using-declaration used as a member-declaration shall refer
5680200583Srdivacky  //   to a member of a base class of the class being defined [etc.].
5681200583Srdivacky
5682200583Srdivacky  // Salient point: SS doesn't have to name a base class as long as
5683200583Srdivacky  // lookup only finds members from base classes.  Therefore we can
5684200583Srdivacky  // diagnose here only if we can prove that that can't happen,
5685200583Srdivacky  // i.e. if the class hierarchies provably don't intersect.
5686200583Srdivacky
5687200583Srdivacky  // TODO: it would be nice if "definitely valid" results were cached
5688200583Srdivacky  // in the UsingDecl and UsingShadowDecl so that these checks didn't
5689200583Srdivacky  // need to be repeated.
5690200583Srdivacky
5691200583Srdivacky  struct UserData {
5692200583Srdivacky    llvm::DenseSet<const CXXRecordDecl*> Bases;
5693200583Srdivacky
5694200583Srdivacky    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5695200583Srdivacky      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5696200583Srdivacky      Data->Bases.insert(Base);
5697200583Srdivacky      return true;
5698200583Srdivacky    }
5699200583Srdivacky
5700200583Srdivacky    bool hasDependentBases(const CXXRecordDecl *Class) {
5701200583Srdivacky      return !Class->forallBases(collect, this);
5702200583Srdivacky    }
5703200583Srdivacky
5704200583Srdivacky    /// Returns true if the base is dependent or is one of the
5705200583Srdivacky    /// accumulated base classes.
5706200583Srdivacky    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5707200583Srdivacky      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5708200583Srdivacky      return !Data->Bases.count(Base);
5709200583Srdivacky    }
5710200583Srdivacky
5711200583Srdivacky    bool mightShareBases(const CXXRecordDecl *Class) {
5712200583Srdivacky      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5713200583Srdivacky    }
5714200583Srdivacky  };
5715200583Srdivacky
5716200583Srdivacky  UserData Data;
5717200583Srdivacky
5718200583Srdivacky  // Returns false if we find a dependent base.
5719200583Srdivacky  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5720200583Srdivacky    return false;
5721200583Srdivacky
5722200583Srdivacky  // Returns false if the class has a dependent base or if it or one
5723200583Srdivacky  // of its bases is present in the base set of the current context.
5724200583Srdivacky  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5725200583Srdivacky    return false;
5726200583Srdivacky
5727200583Srdivacky  Diag(SS.getRange().getBegin(),
5728200583Srdivacky       diag::err_using_decl_nested_name_specifier_is_not_base_class)
5729200583Srdivacky    << (NestedNameSpecifier*) SS.getScopeRep()
5730200583Srdivacky    << cast<CXXRecordDecl>(CurContext)
5731200583Srdivacky    << SS.getRange();
5732200583Srdivacky
5733200583Srdivacky  return true;
5734200583Srdivacky}
5735200583Srdivacky
5736221345SdimDecl *Sema::ActOnAliasDeclaration(Scope *S,
5737221345Sdim                                  AccessSpecifier AS,
5738223017Sdim                                  MultiTemplateParamsArg TemplateParamLists,
5739221345Sdim                                  SourceLocation UsingLoc,
5740221345Sdim                                  UnqualifiedId &Name,
5741221345Sdim                                  TypeResult Type) {
5742223017Sdim  // Skip up to the relevant declaration scope.
5743223017Sdim  while (S->getFlags() & Scope::TemplateParamScope)
5744223017Sdim    S = S->getParent();
5745221345Sdim  assert((S->getFlags() & Scope::DeclScope) &&
5746221345Sdim         "got alias-declaration outside of declaration scope");
5747221345Sdim
5748221345Sdim  if (Type.isInvalid())
5749221345Sdim    return 0;
5750221345Sdim
5751221345Sdim  bool Invalid = false;
5752221345Sdim  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5753221345Sdim  TypeSourceInfo *TInfo = 0;
5754221345Sdim  GetTypeFromParser(Type.get(), &TInfo);
5755221345Sdim
5756221345Sdim  if (DiagnoseClassNameShadow(CurContext, NameInfo))
5757221345Sdim    return 0;
5758221345Sdim
5759221345Sdim  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
5760223017Sdim                                      UPPC_DeclarationType)) {
5761221345Sdim    Invalid = true;
5762223017Sdim    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5763223017Sdim                                             TInfo->getTypeLoc().getBeginLoc());
5764223017Sdim  }
5765221345Sdim
5766221345Sdim  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5767221345Sdim  LookupName(Previous, S);
5768221345Sdim
5769221345Sdim  // Warn about shadowing the name of a template parameter.
5770221345Sdim  if (Previous.isSingleResult() &&
5771221345Sdim      Previous.getFoundDecl()->isTemplateParameter()) {
5772221345Sdim    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5773221345Sdim                                        Previous.getFoundDecl()))
5774221345Sdim      Invalid = true;
5775221345Sdim    Previous.clear();
5776221345Sdim  }
5777221345Sdim
5778221345Sdim  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5779221345Sdim         "name in alias declaration must be an identifier");
5780221345Sdim  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5781221345Sdim                                               Name.StartLocation,
5782221345Sdim                                               Name.Identifier, TInfo);
5783221345Sdim
5784221345Sdim  NewTD->setAccess(AS);
5785221345Sdim
5786221345Sdim  if (Invalid)
5787221345Sdim    NewTD->setInvalidDecl();
5788221345Sdim
5789223017Sdim  CheckTypedefForVariablyModifiedType(S, NewTD);
5790223017Sdim  Invalid |= NewTD->isInvalidDecl();
5791223017Sdim
5792221345Sdim  bool Redeclaration = false;
5793221345Sdim
5794223017Sdim  NamedDecl *NewND;
5795223017Sdim  if (TemplateParamLists.size()) {
5796223017Sdim    TypeAliasTemplateDecl *OldDecl = 0;
5797223017Sdim    TemplateParameterList *OldTemplateParams = 0;
5798223017Sdim
5799223017Sdim    if (TemplateParamLists.size() != 1) {
5800223017Sdim      Diag(UsingLoc, diag::err_alias_template_extra_headers)
5801223017Sdim        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5802223017Sdim         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5803223017Sdim    }
5804223017Sdim    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5805223017Sdim
5806223017Sdim    // Only consider previous declarations in the same scope.
5807223017Sdim    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5808223017Sdim                         /*ExplicitInstantiationOrSpecialization*/false);
5809223017Sdim    if (!Previous.empty()) {
5810223017Sdim      Redeclaration = true;
5811223017Sdim
5812223017Sdim      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5813223017Sdim      if (!OldDecl && !Invalid) {
5814223017Sdim        Diag(UsingLoc, diag::err_redefinition_different_kind)
5815223017Sdim          << Name.Identifier;
5816223017Sdim
5817223017Sdim        NamedDecl *OldD = Previous.getRepresentativeDecl();
5818223017Sdim        if (OldD->getLocation().isValid())
5819223017Sdim          Diag(OldD->getLocation(), diag::note_previous_definition);
5820223017Sdim
5821223017Sdim        Invalid = true;
5822223017Sdim      }
5823223017Sdim
5824223017Sdim      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5825223017Sdim        if (TemplateParameterListsAreEqual(TemplateParams,
5826223017Sdim                                           OldDecl->getTemplateParameters(),
5827223017Sdim                                           /*Complain=*/true,
5828223017Sdim                                           TPL_TemplateMatch))
5829223017Sdim          OldTemplateParams = OldDecl->getTemplateParameters();
5830223017Sdim        else
5831223017Sdim          Invalid = true;
5832223017Sdim
5833223017Sdim        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5834223017Sdim        if (!Invalid &&
5835223017Sdim            !Context.hasSameType(OldTD->getUnderlyingType(),
5836223017Sdim                                 NewTD->getUnderlyingType())) {
5837223017Sdim          // FIXME: The C++0x standard does not clearly say this is ill-formed,
5838223017Sdim          // but we can't reasonably accept it.
5839223017Sdim          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5840223017Sdim            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5841223017Sdim          if (OldTD->getLocation().isValid())
5842223017Sdim            Diag(OldTD->getLocation(), diag::note_previous_definition);
5843223017Sdim          Invalid = true;
5844223017Sdim        }
5845223017Sdim      }
5846223017Sdim    }
5847223017Sdim
5848223017Sdim    // Merge any previous default template arguments into our parameters,
5849223017Sdim    // and check the parameter list.
5850223017Sdim    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5851223017Sdim                                   TPC_TypeAliasTemplate))
5852223017Sdim      return 0;
5853223017Sdim
5854223017Sdim    TypeAliasTemplateDecl *NewDecl =
5855223017Sdim      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5856223017Sdim                                    Name.Identifier, TemplateParams,
5857223017Sdim                                    NewTD);
5858223017Sdim
5859223017Sdim    NewDecl->setAccess(AS);
5860223017Sdim
5861223017Sdim    if (Invalid)
5862223017Sdim      NewDecl->setInvalidDecl();
5863223017Sdim    else if (OldDecl)
5864223017Sdim      NewDecl->setPreviousDeclaration(OldDecl);
5865223017Sdim
5866223017Sdim    NewND = NewDecl;
5867223017Sdim  } else {
5868223017Sdim    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5869223017Sdim    NewND = NewTD;
5870223017Sdim  }
5871223017Sdim
5872221345Sdim  if (!Redeclaration)
5873223017Sdim    PushOnScopeChains(NewND, S);
5874221345Sdim
5875223017Sdim  return NewND;
5876221345Sdim}
5877221345Sdim
5878212904SdimDecl *Sema::ActOnNamespaceAliasDef(Scope *S,
5879193326Sed                                             SourceLocation NamespaceLoc,
5880193326Sed                                             SourceLocation AliasLoc,
5881193326Sed                                             IdentifierInfo *Alias,
5882207619Srdivacky                                             CXXScopeSpec &SS,
5883193326Sed                                             SourceLocation IdentLoc,
5884193326Sed                                             IdentifierInfo *Ident) {
5885198092Srdivacky
5886193326Sed  // Lookup the namespace name.
5887199482Srdivacky  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5888199482Srdivacky  LookupParsedName(R, S, &SS);
5889193326Sed
5890193326Sed  // Check if we have a previous declaration with the same name.
5891207619Srdivacky  NamedDecl *PrevDecl
5892207619Srdivacky    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5893207619Srdivacky                       ForRedeclaration);
5894207619Srdivacky  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5895207619Srdivacky    PrevDecl = 0;
5896207619Srdivacky
5897207619Srdivacky  if (PrevDecl) {
5898193326Sed    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
5899198092Srdivacky      // We already have an alias with the same name that points to the same
5900193326Sed      // namespace, so don't create a new one.
5901206084Srdivacky      // FIXME: At some point, we'll want to create the (redundant)
5902206084Srdivacky      // declaration to maintain better source information.
5903198092Srdivacky      if (!R.isAmbiguous() && !R.empty() &&
5904206084Srdivacky          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
5905212904Sdim        return 0;
5906193326Sed    }
5907198092Srdivacky
5908193326Sed    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5909193326Sed      diag::err_redefinition_different_kind;
5910193326Sed    Diag(AliasLoc, DiagID) << Alias;
5911193326Sed    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5912212904Sdim    return 0;
5913193326Sed  }
5914193326Sed
5915199482Srdivacky  if (R.isAmbiguous())
5916212904Sdim    return 0;
5917198092Srdivacky
5918198092Srdivacky  if (R.empty()) {
5919210299Sed    if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5920210299Sed                                                CTC_NoKeywords, 0)) {
5921210299Sed      if (R.getAsSingle<NamespaceDecl>() ||
5922210299Sed          R.getAsSingle<NamespaceAliasDecl>()) {
5923210299Sed        if (DeclContext *DC = computeDeclContext(SS, false))
5924210299Sed          Diag(IdentLoc, diag::err_using_directive_member_suggest)
5925210299Sed            << Ident << DC << Corrected << SS.getRange()
5926210299Sed            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5927210299Sed        else
5928210299Sed          Diag(IdentLoc, diag::err_using_directive_suggest)
5929210299Sed            << Ident << Corrected
5930210299Sed            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5931210299Sed
5932210299Sed        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5933210299Sed          << Corrected;
5934210299Sed
5935210299Sed        Ident = Corrected.getAsIdentifierInfo();
5936210299Sed      } else {
5937210299Sed        R.clear();
5938210299Sed        R.setLookupName(Ident);
5939210299Sed      }
5940210299Sed    }
5941210299Sed
5942210299Sed    if (R.empty()) {
5943210299Sed      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
5944212904Sdim      return 0;
5945210299Sed    }
5946193326Sed  }
5947198092Srdivacky
5948194613Sed  NamespaceAliasDecl *AliasDecl =
5949198092Srdivacky    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
5950219077Sdim                               Alias, SS.getWithLocInContext(Context),
5951198092Srdivacky                               IdentLoc, R.getFoundDecl());
5952198092Srdivacky
5953203955Srdivacky  PushOnScopeChains(AliasDecl, S);
5954212904Sdim  return AliasDecl;
5955193326Sed}
5956193326Sed
5957207619Srdivackynamespace {
5958207619Srdivacky  /// \brief Scoped object used to handle the state changes required in Sema
5959207619Srdivacky  /// to implicitly define the body of a C++ member function;
5960207619Srdivacky  class ImplicitlyDefinedFunctionScope {
5961207619Srdivacky    Sema &S;
5962218893Sdim    Sema::ContextRAII SavedContext;
5963207619Srdivacky
5964207619Srdivacky  public:
5965207619Srdivacky    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
5966218893Sdim      : S(S), SavedContext(S, Method)
5967207619Srdivacky    {
5968207619Srdivacky      S.PushFunctionScope();
5969207619Srdivacky      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5970207619Srdivacky    }
5971207619Srdivacky
5972207619Srdivacky    ~ImplicitlyDefinedFunctionScope() {
5973207619Srdivacky      S.PopExpressionEvaluationContext();
5974207619Srdivacky      S.PopFunctionOrBlockScope();
5975207619Srdivacky    }
5976207619Srdivacky  };
5977207619Srdivacky}
5978207619Srdivacky
5979223017SdimSema::ImplicitExceptionSpecification
5980223017SdimSema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
5981210299Sed  // C++ [except.spec]p14:
5982210299Sed  //   An implicitly declared special member function (Clause 12) shall have an
5983210299Sed  //   exception-specification. [...]
5984210299Sed  ImplicitExceptionSpecification ExceptSpec(Context);
5985210299Sed
5986221345Sdim  // Direct base-class constructors.
5987210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5988210299Sed                                       BEnd = ClassDecl->bases_end();
5989210299Sed       B != BEnd; ++B) {
5990210299Sed    if (B->isVirtual()) // Handled below.
5991210299Sed      continue;
5992210299Sed
5993210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5994210299Sed      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5995223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5996223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
5997223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
5998223017Sdim      if (Constructor)
5999210299Sed        ExceptSpec.CalledDecl(Constructor);
6000210299Sed    }
6001210299Sed  }
6002221345Sdim
6003221345Sdim  // Virtual base-class constructors.
6004210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6005210299Sed                                       BEnd = ClassDecl->vbases_end();
6006210299Sed       B != BEnd; ++B) {
6007210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6008210299Sed      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6009223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6010223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
6011223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
6012223017Sdim      if (Constructor)
6013210299Sed        ExceptSpec.CalledDecl(Constructor);
6014210299Sed    }
6015210299Sed  }
6016221345Sdim
6017221345Sdim  // Field constructors.
6018210299Sed  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6019210299Sed                               FEnd = ClassDecl->field_end();
6020210299Sed       F != FEnd; ++F) {
6021223017Sdim    if (F->hasInClassInitializer()) {
6022223017Sdim      if (Expr *E = F->getInClassInitializer())
6023223017Sdim        ExceptSpec.CalledExpr(E);
6024223017Sdim      else if (!F->isInvalidDecl())
6025223017Sdim        ExceptSpec.SetDelayed();
6026223017Sdim    } else if (const RecordType *RecordTy
6027210299Sed              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6028223017Sdim      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6029223017Sdim      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6030223017Sdim      // If this is a deleted function, add it anyway. This might be conformant
6031223017Sdim      // with the standard. This might not. I'm not sure. It might not matter.
6032223017Sdim      // In particular, the problem is that this function never gets called. It
6033223017Sdim      // might just be ill-formed because this function attempts to refer to
6034223017Sdim      // a deleted function here.
6035223017Sdim      if (Constructor)
6036210299Sed        ExceptSpec.CalledDecl(Constructor);
6037210299Sed    }
6038210299Sed  }
6039218893Sdim
6040223017Sdim  return ExceptSpec;
6041223017Sdim}
6042221345Sdim
6043223017SdimCXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6044223017Sdim                                                     CXXRecordDecl *ClassDecl) {
6045223017Sdim  // C++ [class.ctor]p5:
6046223017Sdim  //   A default constructor for a class X is a constructor of class X
6047223017Sdim  //   that can be called without an argument. If there is no
6048223017Sdim  //   user-declared constructor for class X, a default constructor is
6049223017Sdim  //   implicitly declared. An implicitly-declared default constructor
6050223017Sdim  //   is an inline public member of its class.
6051223017Sdim  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6052223017Sdim         "Should not build implicit default constructor!");
6053223017Sdim
6054223017Sdim  ImplicitExceptionSpecification Spec =
6055223017Sdim    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6056223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6057223017Sdim
6058210299Sed  // Create the actual constructor declaration.
6059210299Sed  CanQualType ClassType
6060210299Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6061221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
6062210299Sed  DeclarationName Name
6063210299Sed    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6064221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
6065210299Sed  CXXConstructorDecl *DefaultCon
6066221345Sdim    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6067210299Sed                                 Context.getFunctionType(Context.VoidTy,
6068218893Sdim                                                         0, 0, EPI),
6069210299Sed                                 /*TInfo=*/0,
6070210299Sed                                 /*isExplicit=*/false,
6071210299Sed                                 /*isInline=*/true,
6072210299Sed                                 /*isImplicitlyDeclared=*/true);
6073210299Sed  DefaultCon->setAccess(AS_public);
6074223017Sdim  DefaultCon->setDefaulted();
6075210299Sed  DefaultCon->setImplicit();
6076223017Sdim  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6077210299Sed
6078210299Sed  // Note that we have declared this constructor.
6079210299Sed  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6080210299Sed
6081210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
6082210299Sed    PushOnScopeChains(DefaultCon, S, false);
6083210299Sed  ClassDecl->addDecl(DefaultCon);
6084223017Sdim
6085223017Sdim  if (ShouldDeleteDefaultConstructor(DefaultCon))
6086223017Sdim    DefaultCon->setDeletedAsWritten();
6087210299Sed
6088210299Sed  return DefaultCon;
6089210299Sed}
6090210299Sed
6091194613Sedvoid Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6092194613Sed                                            CXXConstructorDecl *Constructor) {
6093223017Sdim  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6094223017Sdim          !Constructor->doesThisDeclarationHaveABody() &&
6095223017Sdim          !Constructor->isDeleted()) &&
6096194711Sed    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6097198092Srdivacky
6098207619Srdivacky  CXXRecordDecl *ClassDecl = Constructor->getParent();
6099194711Sed  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6100199482Srdivacky
6101207619Srdivacky  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6102218893Sdim  DiagnosticErrorTrap Trap(Diags);
6103218893Sdim  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6104208600Srdivacky      Trap.hasErrorOccurred()) {
6105199990Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
6106223017Sdim      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6107199482Srdivacky    Constructor->setInvalidDecl();
6108218893Sdim    return;
6109194613Sed  }
6110218893Sdim
6111218893Sdim  SourceLocation Loc = Constructor->getLocation();
6112218893Sdim  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6113218893Sdim
6114218893Sdim  Constructor->setUsed();
6115218893Sdim  MarkVTableUsed(CurrentLocation, ClassDecl);
6116221345Sdim
6117221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
6118221345Sdim    L->CompletedImplicitDefinition(Constructor);
6119221345Sdim  }
6120194613Sed}
6121194613Sed
6122223017Sdim/// Get any existing defaulted default constructor for the given class. Do not
6123223017Sdim/// implicitly define one if it does not exist.
6124223017Sdimstatic CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6125223017Sdim                                                             CXXRecordDecl *D) {
6126223017Sdim  ASTContext &Context = Self.Context;
6127223017Sdim  QualType ClassType = Context.getTypeDeclType(D);
6128223017Sdim  DeclarationName ConstructorName
6129223017Sdim    = Context.DeclarationNames.getCXXConstructorName(
6130223017Sdim                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6131223017Sdim
6132223017Sdim  DeclContext::lookup_const_iterator Con, ConEnd;
6133223017Sdim  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6134223017Sdim       Con != ConEnd; ++Con) {
6135223017Sdim    // A function template cannot be defaulted.
6136223017Sdim    if (isa<FunctionTemplateDecl>(*Con))
6137223017Sdim      continue;
6138223017Sdim
6139223017Sdim    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6140223017Sdim    if (Constructor->isDefaultConstructor())
6141223017Sdim      return Constructor->isDefaulted() ? Constructor : 0;
6142223017Sdim  }
6143223017Sdim  return 0;
6144223017Sdim}
6145223017Sdim
6146223017Sdimvoid Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6147223017Sdim  if (!D) return;
6148223017Sdim  AdjustDeclIfTemplate(D);
6149223017Sdim
6150223017Sdim  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6151223017Sdim  CXXConstructorDecl *CtorDecl
6152223017Sdim    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6153223017Sdim
6154223017Sdim  if (!CtorDecl) return;
6155223017Sdim
6156223017Sdim  // Compute the exception specification for the default constructor.
6157223017Sdim  const FunctionProtoType *CtorTy =
6158223017Sdim    CtorDecl->getType()->castAs<FunctionProtoType>();
6159223017Sdim  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6160223017Sdim    ImplicitExceptionSpecification Spec =
6161223017Sdim      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6162223017Sdim    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6163223017Sdim    assert(EPI.ExceptionSpecType != EST_Delayed);
6164223017Sdim
6165223017Sdim    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6166223017Sdim  }
6167223017Sdim
6168223017Sdim  // If the default constructor is explicitly defaulted, checking the exception
6169223017Sdim  // specification is deferred until now.
6170223017Sdim  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6171223017Sdim      !ClassDecl->isDependentType())
6172223017Sdim    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6173223017Sdim}
6174223017Sdim
6175218893Sdimvoid Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6176218893Sdim  // We start with an initial pass over the base classes to collect those that
6177218893Sdim  // inherit constructors from. If there are none, we can forgo all further
6178218893Sdim  // processing.
6179218893Sdim  typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6180218893Sdim  BasesVector BasesToInheritFrom;
6181218893Sdim  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6182218893Sdim                                          BaseE = ClassDecl->bases_end();
6183218893Sdim         BaseIt != BaseE; ++BaseIt) {
6184218893Sdim    if (BaseIt->getInheritConstructors()) {
6185218893Sdim      QualType Base = BaseIt->getType();
6186218893Sdim      if (Base->isDependentType()) {
6187218893Sdim        // If we inherit constructors from anything that is dependent, just
6188218893Sdim        // abort processing altogether. We'll get another chance for the
6189218893Sdim        // instantiations.
6190218893Sdim        return;
6191218893Sdim      }
6192218893Sdim      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6193218893Sdim    }
6194218893Sdim  }
6195218893Sdim  if (BasesToInheritFrom.empty())
6196218893Sdim    return;
6197218893Sdim
6198218893Sdim  // Now collect the constructors that we already have in the current class.
6199218893Sdim  // Those take precedence over inherited constructors.
6200218893Sdim  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6201218893Sdim  //   unless there is a user-declared constructor with the same signature in
6202218893Sdim  //   the class where the using-declaration appears.
6203218893Sdim  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6204218893Sdim  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6205218893Sdim                                    CtorE = ClassDecl->ctor_end();
6206218893Sdim       CtorIt != CtorE; ++CtorIt) {
6207218893Sdim    ExistingConstructors.insert(
6208218893Sdim        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6209218893Sdim  }
6210218893Sdim
6211218893Sdim  Scope *S = getScopeForContext(ClassDecl);
6212218893Sdim  DeclarationName CreatedCtorName =
6213218893Sdim      Context.DeclarationNames.getCXXConstructorName(
6214218893Sdim          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6215218893Sdim
6216218893Sdim  // Now comes the true work.
6217218893Sdim  // First, we keep a map from constructor types to the base that introduced
6218218893Sdim  // them. Needed for finding conflicting constructors. We also keep the
6219218893Sdim  // actually inserted declarations in there, for pretty diagnostics.
6220218893Sdim  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6221218893Sdim  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6222218893Sdim  ConstructorToSourceMap InheritedConstructors;
6223218893Sdim  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6224218893Sdim                             BaseE = BasesToInheritFrom.end();
6225218893Sdim       BaseIt != BaseE; ++BaseIt) {
6226218893Sdim    const RecordType *Base = *BaseIt;
6227218893Sdim    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6228218893Sdim    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6229218893Sdim    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6230218893Sdim                                      CtorE = BaseDecl->ctor_end();
6231218893Sdim         CtorIt != CtorE; ++CtorIt) {
6232218893Sdim      // Find the using declaration for inheriting this base's constructors.
6233218893Sdim      DeclarationName Name =
6234218893Sdim          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6235218893Sdim      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6236218893Sdim          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6237218893Sdim      SourceLocation UsingLoc = UD ? UD->getLocation() :
6238218893Sdim                                     ClassDecl->getLocation();
6239218893Sdim
6240218893Sdim      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6241218893Sdim      //   from the class X named in the using-declaration consists of actual
6242218893Sdim      //   constructors and notional constructors that result from the
6243218893Sdim      //   transformation of defaulted parameters as follows:
6244218893Sdim      //   - all non-template default constructors of X, and
6245218893Sdim      //   - for each non-template constructor of X that has at least one
6246218893Sdim      //     parameter with a default argument, the set of constructors that
6247218893Sdim      //     results from omitting any ellipsis parameter specification and
6248218893Sdim      //     successively omitting parameters with a default argument from the
6249218893Sdim      //     end of the parameter-type-list.
6250218893Sdim      CXXConstructorDecl *BaseCtor = *CtorIt;
6251218893Sdim      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6252218893Sdim      const FunctionProtoType *BaseCtorType =
6253218893Sdim          BaseCtor->getType()->getAs<FunctionProtoType>();
6254218893Sdim
6255218893Sdim      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6256218893Sdim                    maxParams = BaseCtor->getNumParams();
6257218893Sdim           params <= maxParams; ++params) {
6258218893Sdim        // Skip default constructors. They're never inherited.
6259218893Sdim        if (params == 0)
6260218893Sdim          continue;
6261218893Sdim        // Skip copy and move constructors for the same reason.
6262218893Sdim        if (CanBeCopyOrMove && params == 1)
6263218893Sdim          continue;
6264218893Sdim
6265218893Sdim        // Build up a function type for this particular constructor.
6266218893Sdim        // FIXME: The working paper does not consider that the exception spec
6267218893Sdim        // for the inheriting constructor might be larger than that of the
6268223017Sdim        // source. This code doesn't yet, either. When it does, this code will
6269223017Sdim        // need to be delayed until after exception specifications and in-class
6270223017Sdim        // member initializers are attached.
6271218893Sdim        const Type *NewCtorType;
6272218893Sdim        if (params == maxParams)
6273218893Sdim          NewCtorType = BaseCtorType;
6274218893Sdim        else {
6275218893Sdim          llvm::SmallVector<QualType, 16> Args;
6276218893Sdim          for (unsigned i = 0; i < params; ++i) {
6277218893Sdim            Args.push_back(BaseCtorType->getArgType(i));
6278218893Sdim          }
6279218893Sdim          FunctionProtoType::ExtProtoInfo ExtInfo =
6280218893Sdim              BaseCtorType->getExtProtoInfo();
6281218893Sdim          ExtInfo.Variadic = false;
6282218893Sdim          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6283218893Sdim                                                Args.data(), params, ExtInfo)
6284218893Sdim                       .getTypePtr();
6285218893Sdim        }
6286218893Sdim        const Type *CanonicalNewCtorType =
6287218893Sdim            Context.getCanonicalType(NewCtorType);
6288218893Sdim
6289218893Sdim        // Now that we have the type, first check if the class already has a
6290218893Sdim        // constructor with this signature.
6291218893Sdim        if (ExistingConstructors.count(CanonicalNewCtorType))
6292218893Sdim          continue;
6293218893Sdim
6294218893Sdim        // Then we check if we have already declared an inherited constructor
6295218893Sdim        // with this signature.
6296218893Sdim        std::pair<ConstructorToSourceMap::iterator, bool> result =
6297218893Sdim            InheritedConstructors.insert(std::make_pair(
6298218893Sdim                CanonicalNewCtorType,
6299218893Sdim                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6300218893Sdim        if (!result.second) {
6301218893Sdim          // Already in the map. If it came from a different class, that's an
6302218893Sdim          // error. Not if it's from the same.
6303218893Sdim          CanQualType PreviousBase = result.first->second.first;
6304218893Sdim          if (CanonicalBase != PreviousBase) {
6305218893Sdim            const CXXConstructorDecl *PrevCtor = result.first->second.second;
6306218893Sdim            const CXXConstructorDecl *PrevBaseCtor =
6307218893Sdim                PrevCtor->getInheritedConstructor();
6308218893Sdim            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6309218893Sdim
6310218893Sdim            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6311218893Sdim            Diag(BaseCtor->getLocation(),
6312218893Sdim                 diag::note_using_decl_constructor_conflict_current_ctor);
6313218893Sdim            Diag(PrevBaseCtor->getLocation(),
6314218893Sdim                 diag::note_using_decl_constructor_conflict_previous_ctor);
6315218893Sdim            Diag(PrevCtor->getLocation(),
6316218893Sdim                 diag::note_using_decl_constructor_conflict_previous_using);
6317218893Sdim          }
6318218893Sdim          continue;
6319218893Sdim        }
6320218893Sdim
6321218893Sdim        // OK, we're there, now add the constructor.
6322218893Sdim        // C++0x [class.inhctor]p8: [...] that would be performed by a
6323218893Sdim        //   user-writtern inline constructor [...]
6324218893Sdim        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6325218893Sdim        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6326221345Sdim            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6327221345Sdim            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6328218893Sdim            /*ImplicitlyDeclared=*/true);
6329218893Sdim        NewCtor->setAccess(BaseCtor->getAccess());
6330218893Sdim
6331218893Sdim        // Build up the parameter decls and add them.
6332218893Sdim        llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6333218893Sdim        for (unsigned i = 0; i < params; ++i) {
6334221345Sdim          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6335221345Sdim                                                   UsingLoc, UsingLoc,
6336218893Sdim                                                   /*IdentifierInfo=*/0,
6337218893Sdim                                                   BaseCtorType->getArgType(i),
6338218893Sdim                                                   /*TInfo=*/0, SC_None,
6339218893Sdim                                                   SC_None, /*DefaultArg=*/0));
6340218893Sdim        }
6341218893Sdim        NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6342218893Sdim        NewCtor->setInheritedConstructor(BaseCtor);
6343218893Sdim
6344218893Sdim        PushOnScopeChains(NewCtor, S, false);
6345218893Sdim        ClassDecl->addDecl(NewCtor);
6346218893Sdim        result.first->second.second = NewCtor;
6347218893Sdim      }
6348218893Sdim    }
6349218893Sdim  }
6350218893Sdim}
6351218893Sdim
6352223017SdimSema::ImplicitExceptionSpecification
6353223017SdimSema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6354210299Sed  // C++ [except.spec]p14:
6355210299Sed  //   An implicitly declared special member function (Clause 12) shall have
6356210299Sed  //   an exception-specification.
6357210299Sed  ImplicitExceptionSpecification ExceptSpec(Context);
6358210299Sed
6359210299Sed  // Direct base-class destructors.
6360210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6361210299Sed                                       BEnd = ClassDecl->bases_end();
6362210299Sed       B != BEnd; ++B) {
6363210299Sed    if (B->isVirtual()) // Handled below.
6364210299Sed      continue;
6365210299Sed
6366210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6367210299Sed      ExceptSpec.CalledDecl(
6368223017Sdim                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6369210299Sed  }
6370223017Sdim
6371210299Sed  // Virtual base-class destructors.
6372210299Sed  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6373210299Sed                                       BEnd = ClassDecl->vbases_end();
6374210299Sed       B != BEnd; ++B) {
6375210299Sed    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6376210299Sed      ExceptSpec.CalledDecl(
6377223017Sdim                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6378210299Sed  }
6379223017Sdim
6380210299Sed  // Field destructors.
6381210299Sed  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6382210299Sed                               FEnd = ClassDecl->field_end();
6383210299Sed       F != FEnd; ++F) {
6384210299Sed    if (const RecordType *RecordTy
6385210299Sed        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6386210299Sed      ExceptSpec.CalledDecl(
6387223017Sdim                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6388210299Sed  }
6389221345Sdim
6390223017Sdim  return ExceptSpec;
6391223017Sdim}
6392223017Sdim
6393223017SdimCXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6394223017Sdim  // C++ [class.dtor]p2:
6395223017Sdim  //   If a class has no user-declared destructor, a destructor is
6396223017Sdim  //   declared implicitly. An implicitly-declared destructor is an
6397223017Sdim  //   inline public member of its class.
6398223017Sdim
6399223017Sdim  ImplicitExceptionSpecification Spec =
6400223017Sdim      ComputeDefaultedDtorExceptionSpec(ClassDecl);
6401223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6402223017Sdim
6403210299Sed  // Create the actual destructor declaration.
6404218893Sdim  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6405221345Sdim
6406210299Sed  CanQualType ClassType
6407210299Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6408221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
6409210299Sed  DeclarationName Name
6410210299Sed    = Context.DeclarationNames.getCXXDestructorName(ClassType);
6411221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
6412210299Sed  CXXDestructorDecl *Destructor
6413221345Sdim      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6414221345Sdim                                  /*isInline=*/true,
6415221345Sdim                                  /*isImplicitlyDeclared=*/true);
6416210299Sed  Destructor->setAccess(AS_public);
6417223017Sdim  Destructor->setDefaulted();
6418210299Sed  Destructor->setImplicit();
6419210299Sed  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6420210299Sed
6421210299Sed  // Note that we have declared this destructor.
6422210299Sed  ++ASTContext::NumImplicitDestructorsDeclared;
6423210299Sed
6424210299Sed  // Introduce this destructor into its scope.
6425210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
6426210299Sed    PushOnScopeChains(Destructor, S, false);
6427210299Sed  ClassDecl->addDecl(Destructor);
6428210299Sed
6429210299Sed  // This could be uniqued if it ever proves significant.
6430210299Sed  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6431223017Sdim
6432223017Sdim  if (ShouldDeleteDestructor(Destructor))
6433223017Sdim    Destructor->setDeletedAsWritten();
6434210299Sed
6435210299Sed  AddOverriddenMethods(ClassDecl, Destructor);
6436210299Sed
6437210299Sed  return Destructor;
6438210299Sed}
6439210299Sed
6440195099Sedvoid Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6441198092Srdivacky                                    CXXDestructorDecl *Destructor) {
6442223017Sdim  assert((Destructor->isDefaulted() &&
6443223017Sdim          !Destructor->doesThisDeclarationHaveABody()) &&
6444195099Sed         "DefineImplicitDestructor - call it for implicit default dtor");
6445199482Srdivacky  CXXRecordDecl *ClassDecl = Destructor->getParent();
6446195099Sed  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6447203955Srdivacky
6448208600Srdivacky  if (Destructor->isInvalidDecl())
6449208600Srdivacky    return;
6450208600Srdivacky
6451207619Srdivacky  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6452203955Srdivacky
6453218893Sdim  DiagnosticErrorTrap Trap(Diags);
6454205408Srdivacky  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6455205408Srdivacky                                         Destructor->getParent());
6456198092Srdivacky
6457208600Srdivacky  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6458199990Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
6459199990Srdivacky      << CXXDestructor << Context.getTagDeclType(ClassDecl);
6460199990Srdivacky
6461199990Srdivacky    Destructor->setInvalidDecl();
6462199990Srdivacky    return;
6463199990Srdivacky  }
6464199990Srdivacky
6465218893Sdim  SourceLocation Loc = Destructor->getLocation();
6466218893Sdim  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6467218893Sdim
6468195099Sed  Destructor->setUsed();
6469208600Srdivacky  MarkVTableUsed(CurrentLocation, ClassDecl);
6470221345Sdim
6471221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
6472221345Sdim    L->CompletedImplicitDefinition(Destructor);
6473221345Sdim  }
6474195099Sed}
6475195099Sed
6476223017Sdimvoid Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6477223017Sdim                                         CXXDestructorDecl *destructor) {
6478223017Sdim  // C++11 [class.dtor]p3:
6479223017Sdim  //   A declaration of a destructor that does not have an exception-
6480223017Sdim  //   specification is implicitly considered to have the same exception-
6481223017Sdim  //   specification as an implicit declaration.
6482223017Sdim  const FunctionProtoType *dtorType = destructor->getType()->
6483223017Sdim                                        getAs<FunctionProtoType>();
6484223017Sdim  if (dtorType->hasExceptionSpec())
6485223017Sdim    return;
6486223017Sdim
6487223017Sdim  ImplicitExceptionSpecification exceptSpec =
6488223017Sdim      ComputeDefaultedDtorExceptionSpec(classDecl);
6489223017Sdim
6490223017Sdim  // Replace the destructor's type.
6491223017Sdim  FunctionProtoType::ExtProtoInfo epi;
6492223017Sdim  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6493223017Sdim  epi.NumExceptions = exceptSpec.size();
6494223017Sdim  epi.Exceptions = exceptSpec.data();
6495223017Sdim  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6496223017Sdim
6497223017Sdim  destructor->setType(ty);
6498223017Sdim
6499223017Sdim  // FIXME: If the destructor has a body that could throw, and the newly created
6500223017Sdim  // spec doesn't allow exceptions, we should emit a warning, because this
6501223017Sdim  // change in behavior can break conforming C++03 programs at runtime.
6502223017Sdim  // However, we don't have a body yet, so it needs to be done somewhere else.
6503223017Sdim}
6504223017Sdim
6505207619Srdivacky/// \brief Builds a statement that copies the given entity from \p From to
6506207619Srdivacky/// \c To.
6507207619Srdivacky///
6508207619Srdivacky/// This routine is used to copy the members of a class with an
6509207619Srdivacky/// implicitly-declared copy assignment operator. When the entities being
6510207619Srdivacky/// copied are arrays, this routine builds for loops to copy them.
6511207619Srdivacky///
6512207619Srdivacky/// \param S The Sema object used for type-checking.
6513207619Srdivacky///
6514207619Srdivacky/// \param Loc The location where the implicit copy is being generated.
6515207619Srdivacky///
6516207619Srdivacky/// \param T The type of the expressions being copied. Both expressions must
6517207619Srdivacky/// have this type.
6518207619Srdivacky///
6519207619Srdivacky/// \param To The expression we are copying to.
6520207619Srdivacky///
6521207619Srdivacky/// \param From The expression we are copying from.
6522207619Srdivacky///
6523207632Srdivacky/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6524207632Srdivacky/// Otherwise, it's a non-static member subobject.
6525207632Srdivacky///
6526207619Srdivacky/// \param Depth Internal parameter recording the depth of the recursion.
6527207619Srdivacky///
6528207619Srdivacky/// \returns A statement or a loop that copies the expressions.
6529212904Sdimstatic StmtResult
6530207619SrdivackyBuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
6531212904Sdim                      Expr *To, Expr *From,
6532207632Srdivacky                      bool CopyingBaseSubobject, unsigned Depth = 0) {
6533207619Srdivacky  // C++0x [class.copy]p30:
6534207619Srdivacky  //   Each subobject is assigned in the manner appropriate to its type:
6535207619Srdivacky  //
6536207619Srdivacky  //     - if the subobject is of class type, the copy assignment operator
6537207619Srdivacky  //       for the class is used (as if by explicit qualification; that is,
6538207619Srdivacky  //       ignoring any possible virtual overriding functions in more derived
6539207619Srdivacky  //       classes);
6540207619Srdivacky  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6541207619Srdivacky    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6542207619Srdivacky
6543207619Srdivacky    // Look for operator=.
6544207619Srdivacky    DeclarationName Name
6545207619Srdivacky      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6546207619Srdivacky    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6547207619Srdivacky    S.LookupQualifiedName(OpLookup, ClassDecl, false);
6548207619Srdivacky
6549207619Srdivacky    // Filter out any result that isn't a copy-assignment operator.
6550207619Srdivacky    LookupResult::Filter F = OpLookup.makeFilter();
6551207619Srdivacky    while (F.hasNext()) {
6552207619Srdivacky      NamedDecl *D = F.next();
6553207619Srdivacky      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6554207619Srdivacky        if (Method->isCopyAssignmentOperator())
6555207619Srdivacky          continue;
6556207619Srdivacky
6557207619Srdivacky      F.erase();
6558207619Srdivacky    }
6559207619Srdivacky    F.done();
6560207619Srdivacky
6561207632Srdivacky    // Suppress the protected check (C++ [class.protected]) for each of the
6562207632Srdivacky    // assignment operators we found. This strange dance is required when
6563207632Srdivacky    // we're assigning via a base classes's copy-assignment operator. To
6564207632Srdivacky    // ensure that we're getting the right base class subobject (without
6565207632Srdivacky    // ambiguities), we need to cast "this" to that subobject type; to
6566207632Srdivacky    // ensure that we don't go through the virtual call mechanism, we need
6567207632Srdivacky    // to qualify the operator= name with the base class (see below). However,
6568207632Srdivacky    // this means that if the base class has a protected copy assignment
6569207632Srdivacky    // operator, the protected member access check will fail. So, we
6570207632Srdivacky    // rewrite "protected" access to "public" access in this case, since we
6571207632Srdivacky    // know by construction that we're calling from a derived class.
6572207632Srdivacky    if (CopyingBaseSubobject) {
6573207632Srdivacky      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6574207632Srdivacky           L != LEnd; ++L) {
6575207632Srdivacky        if (L.getAccess() == AS_protected)
6576207632Srdivacky          L.setAccess(AS_public);
6577207632Srdivacky      }
6578207632Srdivacky    }
6579207632Srdivacky
6580207619Srdivacky    // Create the nested-name-specifier that will be used to qualify the
6581207619Srdivacky    // reference to operator=; this is required to suppress the virtual
6582207619Srdivacky    // call mechanism.
6583207619Srdivacky    CXXScopeSpec SS;
6584219077Sdim    SS.MakeTrivial(S.Context,
6585219077Sdim                   NestedNameSpecifier::Create(S.Context, 0, false,
6586219077Sdim                                               T.getTypePtr()),
6587219077Sdim                   Loc);
6588207619Srdivacky
6589207619Srdivacky    // Create the reference to operator=.
6590212904Sdim    ExprResult OpEqualRef
6591212904Sdim      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
6592207619Srdivacky                                   /*FirstQualifierInScope=*/0, OpLookup,
6593207619Srdivacky                                   /*TemplateArgs=*/0,
6594207619Srdivacky                                   /*SuppressQualifierCheck=*/true);
6595207619Srdivacky    if (OpEqualRef.isInvalid())
6596212904Sdim      return StmtError();
6597207619Srdivacky
6598207619Srdivacky    // Build the call to the assignment operator.
6599212904Sdim
6600212904Sdim    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
6601218893Sdim                                                  OpEqualRef.takeAs<Expr>(),
6602218893Sdim                                                  Loc, &From, 1, Loc);
6603207619Srdivacky    if (Call.isInvalid())
6604212904Sdim      return StmtError();
6605207619Srdivacky
6606207619Srdivacky    return S.Owned(Call.takeAs<Stmt>());
6607207619Srdivacky  }
6608198092Srdivacky
6609207619Srdivacky  //     - if the subobject is of scalar type, the built-in assignment
6610207619Srdivacky  //       operator is used.
6611207619Srdivacky  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6612207619Srdivacky  if (!ArrayTy) {
6613212904Sdim    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
6614207619Srdivacky    if (Assignment.isInvalid())
6615212904Sdim      return StmtError();
6616207619Srdivacky
6617207619Srdivacky    return S.Owned(Assignment.takeAs<Stmt>());
6618207619Srdivacky  }
6619207619Srdivacky
6620207619Srdivacky  //     - if the subobject is an array, each element is assigned, in the
6621207619Srdivacky  //       manner appropriate to the element type;
6622207619Srdivacky
6623207619Srdivacky  // Construct a loop over the array bounds, e.g.,
6624207619Srdivacky  //
6625207619Srdivacky  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6626207619Srdivacky  //
6627207619Srdivacky  // that will copy each of the array elements.
6628207619Srdivacky  QualType SizeType = S.Context.getSizeType();
6629207619Srdivacky
6630207619Srdivacky  // Create the iteration variable.
6631207619Srdivacky  IdentifierInfo *IterationVarName = 0;
6632207619Srdivacky  {
6633207619Srdivacky    llvm::SmallString<8> Str;
6634207619Srdivacky    llvm::raw_svector_ostream OS(Str);
6635207619Srdivacky    OS << "__i" << Depth;
6636207619Srdivacky    IterationVarName = &S.Context.Idents.get(OS.str());
6637207619Srdivacky  }
6638221345Sdim  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
6639207619Srdivacky                                          IterationVarName, SizeType,
6640207619Srdivacky                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
6641212904Sdim                                          SC_None, SC_None);
6642207619Srdivacky
6643207619Srdivacky  // Initialize the iteration variable to zero.
6644207619Srdivacky  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
6645212904Sdim  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
6646198092Srdivacky
6647207619Srdivacky  // Create a reference to the iteration variable; we'll use this several
6648207619Srdivacky  // times throughout.
6649207619Srdivacky  Expr *IterationVarRef
6650218893Sdim    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
6651207619Srdivacky  assert(IterationVarRef && "Reference to invented variable cannot fail!");
6652207619Srdivacky
6653207619Srdivacky  // Create the DeclStmt that holds the iteration variable.
6654207619Srdivacky  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6655207619Srdivacky
6656207619Srdivacky  // Create the comparison against the array bound.
6657218893Sdim  llvm::APInt Upper
6658218893Sdim    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
6659212904Sdim  Expr *Comparison
6660218893Sdim    = new (S.Context) BinaryOperator(IterationVarRef,
6661218893Sdim                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6662218893Sdim                                     BO_NE, S.Context.BoolTy,
6663218893Sdim                                     VK_RValue, OK_Ordinary, Loc);
6664207619Srdivacky
6665207619Srdivacky  // Create the pre-increment of the iteration variable.
6666212904Sdim  Expr *Increment
6667218893Sdim    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6668218893Sdim                                    VK_LValue, OK_Ordinary, Loc);
6669207619Srdivacky
6670207619Srdivacky  // Subscript the "from" and "to" expressions with the iteration variable.
6671212904Sdim  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6672212904Sdim                                                         IterationVarRef, Loc));
6673212904Sdim  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6674212904Sdim                                                       IterationVarRef, Loc));
6675207619Srdivacky
6676207619Srdivacky  // Build the copy for an individual element of the array.
6677218893Sdim  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6678218893Sdim                                          To, From, CopyingBaseSubobject,
6679218893Sdim                                          Depth + 1);
6680212904Sdim  if (Copy.isInvalid())
6681212904Sdim    return StmtError();
6682207619Srdivacky
6683207619Srdivacky  // Construct the loop that copies all elements of this array.
6684212904Sdim  return S.ActOnForStmt(Loc, Loc, InitStmt,
6685207619Srdivacky                        S.MakeFullExpr(Comparison),
6686212904Sdim                        0, S.MakeFullExpr(Increment),
6687212904Sdim                        Loc, Copy.take());
6688207619Srdivacky}
6689203955Srdivacky
6690210299Sed/// \brief Determine whether the given class has a copy assignment operator
6691210299Sed/// that accepts a const-qualified argument.
6692210299Sedstatic bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6693210299Sed  CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6694210299Sed
6695210299Sed  if (!Class->hasDeclaredCopyAssignment())
6696210299Sed    S.DeclareImplicitCopyAssignment(Class);
6697210299Sed
6698210299Sed  QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6699210299Sed  DeclarationName OpName
6700210299Sed    = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6701210299Sed
6702210299Sed  DeclContext::lookup_const_iterator Op, OpEnd;
6703210299Sed  for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6704210299Sed    // C++ [class.copy]p9:
6705210299Sed    //   A user-declared copy assignment operator is a non-static non-template
6706210299Sed    //   member function of class X with exactly one parameter of type X, X&,
6707210299Sed    //   const X&, volatile X& or const volatile X&.
6708210299Sed    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6709210299Sed    if (!Method)
6710210299Sed      continue;
6711210299Sed
6712210299Sed    if (Method->isStatic())
6713210299Sed      continue;
6714210299Sed    if (Method->getPrimaryTemplate())
6715210299Sed      continue;
6716210299Sed    const FunctionProtoType *FnType =
6717210299Sed    Method->getType()->getAs<FunctionProtoType>();
6718210299Sed    assert(FnType && "Overloaded operator has no prototype.");
6719210299Sed    // Don't assert on this; an invalid decl might have been left in the AST.
6720210299Sed    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6721210299Sed      continue;
6722210299Sed    bool AcceptsConst = true;
6723210299Sed    QualType ArgType = FnType->getArgType(0);
6724210299Sed    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6725210299Sed      ArgType = Ref->getPointeeType();
6726210299Sed      // Is it a non-const lvalue reference?
6727210299Sed      if (!ArgType.isConstQualified())
6728210299Sed        AcceptsConst = false;
6729210299Sed    }
6730210299Sed    if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6731210299Sed      continue;
6732210299Sed
6733210299Sed    // We have a single argument of type cv X or cv X&, i.e. we've found the
6734210299Sed    // copy assignment operator. Return whether it accepts const arguments.
6735210299Sed    return AcceptsConst;
6736210299Sed  }
6737210299Sed  assert(Class->isInvalidDecl() &&
6738210299Sed         "No copy assignment operator declared in valid code.");
6739210299Sed  return false;
6740210299Sed}
6741210299Sed
6742223017Sdimstd::pair<Sema::ImplicitExceptionSpecification, bool>
6743223017SdimSema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6744223017Sdim                                                   CXXRecordDecl *ClassDecl) {
6745210299Sed  // C++ [class.copy]p10:
6746210299Sed  //   If the class definition does not explicitly declare a copy
6747210299Sed  //   assignment operator, one is declared implicitly.
6748210299Sed  //   The implicitly-defined copy assignment operator for a class X
6749210299Sed  //   will have the form
6750210299Sed  //
6751210299Sed  //       X& X::operator=(const X&)
6752210299Sed  //
6753210299Sed  //   if
6754210299Sed  bool HasConstCopyAssignment = true;
6755210299Sed
6756210299Sed  //       -- each direct base class B of X has a copy assignment operator
6757210299Sed  //          whose parameter is of type const B&, const volatile B& or B,
6758210299Sed  //          and
6759210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6760210299Sed                                       BaseEnd = ClassDecl->bases_end();
6761210299Sed       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6762210299Sed    assert(!Base->getType()->isDependentType() &&
6763210299Sed           "Cannot generate implicit members for class with dependent bases.");
6764210299Sed    const CXXRecordDecl *BaseClassDecl
6765210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6766210299Sed    HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
6767210299Sed  }
6768210299Sed
6769210299Sed  //       -- for all the nonstatic data members of X that are of a class
6770210299Sed  //          type M (or array thereof), each such class type has a copy
6771210299Sed  //          assignment operator whose parameter is of type const M&,
6772210299Sed  //          const volatile M& or M.
6773210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6774210299Sed                                  FieldEnd = ClassDecl->field_end();
6775210299Sed       HasConstCopyAssignment && Field != FieldEnd;
6776210299Sed       ++Field) {
6777210299Sed    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6778210299Sed    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6779210299Sed      const CXXRecordDecl *FieldClassDecl
6780210299Sed        = cast<CXXRecordDecl>(FieldClassType->getDecl());
6781210299Sed      HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
6782210299Sed    }
6783210299Sed  }
6784210299Sed
6785210299Sed  //   Otherwise, the implicitly declared copy assignment operator will
6786210299Sed  //   have the form
6787210299Sed  //
6788210299Sed  //       X& X::operator=(X&)
6789210299Sed
6790210299Sed  // C++ [except.spec]p14:
6791210299Sed  //   An implicitly declared special member function (Clause 12) shall have an
6792210299Sed  //   exception-specification. [...]
6793210299Sed  ImplicitExceptionSpecification ExceptSpec(Context);
6794210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6795210299Sed                                       BaseEnd = ClassDecl->bases_end();
6796210299Sed       Base != BaseEnd; ++Base) {
6797210299Sed    CXXRecordDecl *BaseClassDecl
6798210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6799210299Sed
6800210299Sed    if (!BaseClassDecl->hasDeclaredCopyAssignment())
6801210299Sed      DeclareImplicitCopyAssignment(BaseClassDecl);
6802210299Sed
6803210299Sed    if (CXXMethodDecl *CopyAssign
6804210299Sed           = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6805210299Sed      ExceptSpec.CalledDecl(CopyAssign);
6806210299Sed  }
6807210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6808210299Sed                                  FieldEnd = ClassDecl->field_end();
6809210299Sed       Field != FieldEnd;
6810210299Sed       ++Field) {
6811210299Sed    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6812210299Sed    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6813210299Sed      CXXRecordDecl *FieldClassDecl
6814210299Sed        = cast<CXXRecordDecl>(FieldClassType->getDecl());
6815210299Sed
6816210299Sed      if (!FieldClassDecl->hasDeclaredCopyAssignment())
6817210299Sed        DeclareImplicitCopyAssignment(FieldClassDecl);
6818210299Sed
6819210299Sed      if (CXXMethodDecl *CopyAssign
6820210299Sed            = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6821210299Sed        ExceptSpec.CalledDecl(CopyAssign);
6822210299Sed    }
6823210299Sed  }
6824221345Sdim
6825223017Sdim  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6826223017Sdim}
6827223017Sdim
6828223017SdimCXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6829223017Sdim  // Note: The following rules are largely analoguous to the copy
6830223017Sdim  // constructor rules. Note that virtual bases are not taken into account
6831223017Sdim  // for determining the argument type of the operator. Note also that
6832223017Sdim  // operators taking an object instead of a reference are allowed.
6833223017Sdim
6834223017Sdim  ImplicitExceptionSpecification Spec(Context);
6835223017Sdim  bool Const;
6836223017Sdim  llvm::tie(Spec, Const) =
6837223017Sdim    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6838223017Sdim
6839223017Sdim  QualType ArgType = Context.getTypeDeclType(ClassDecl);
6840223017Sdim  QualType RetType = Context.getLValueReferenceType(ArgType);
6841223017Sdim  if (Const)
6842223017Sdim    ArgType = ArgType.withConst();
6843223017Sdim  ArgType = Context.getLValueReferenceType(ArgType);
6844223017Sdim
6845210299Sed  //   An implicitly-declared copy assignment operator is an inline public
6846210299Sed  //   member of its class.
6847223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6848210299Sed  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6849221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
6850221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
6851210299Sed  CXXMethodDecl *CopyAssignment
6852221345Sdim    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6853218893Sdim                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
6854210299Sed                            /*TInfo=*/0, /*isStatic=*/false,
6855212904Sdim                            /*StorageClassAsWritten=*/SC_None,
6856221345Sdim                            /*isInline=*/true,
6857221345Sdim                            SourceLocation());
6858210299Sed  CopyAssignment->setAccess(AS_public);
6859223017Sdim  CopyAssignment->setDefaulted();
6860210299Sed  CopyAssignment->setImplicit();
6861210299Sed  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
6862210299Sed
6863210299Sed  // Add the parameter to the operator.
6864210299Sed  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
6865221345Sdim                                               ClassLoc, ClassLoc, /*Id=*/0,
6866210299Sed                                               ArgType, /*TInfo=*/0,
6867212904Sdim                                               SC_None,
6868212904Sdim                                               SC_None, 0);
6869210299Sed  CopyAssignment->setParams(&FromParam, 1);
6870210299Sed
6871210299Sed  // Note that we have added this copy-assignment operator.
6872210299Sed  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6873223017Sdim
6874210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
6875210299Sed    PushOnScopeChains(CopyAssignment, S, false);
6876210299Sed  ClassDecl->addDecl(CopyAssignment);
6877210299Sed
6878223017Sdim  if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6879223017Sdim    CopyAssignment->setDeletedAsWritten();
6880223017Sdim
6881210299Sed  AddOverriddenMethods(ClassDecl, CopyAssignment);
6882210299Sed  return CopyAssignment;
6883210299Sed}
6884210299Sed
6885207619Srdivackyvoid Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6886207619Srdivacky                                        CXXMethodDecl *CopyAssignOperator) {
6887223017Sdim  assert((CopyAssignOperator->isDefaulted() &&
6888207619Srdivacky          CopyAssignOperator->isOverloadedOperator() &&
6889207619Srdivacky          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
6890223017Sdim          !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
6891207619Srdivacky         "DefineImplicitCopyAssignment called for wrong function");
6892207619Srdivacky
6893207619Srdivacky  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6894207619Srdivacky
6895207619Srdivacky  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6896207619Srdivacky    CopyAssignOperator->setInvalidDecl();
6897207619Srdivacky    return;
6898207619Srdivacky  }
6899207619Srdivacky
6900207619Srdivacky  CopyAssignOperator->setUsed();
6901207619Srdivacky
6902207619Srdivacky  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
6903218893Sdim  DiagnosticErrorTrap Trap(Diags);
6904207619Srdivacky
6905207619Srdivacky  // C++0x [class.copy]p30:
6906207619Srdivacky  //   The implicitly-defined or explicitly-defaulted copy assignment operator
6907207619Srdivacky  //   for a non-union class X performs memberwise copy assignment of its
6908207619Srdivacky  //   subobjects. The direct base classes of X are assigned first, in the
6909207619Srdivacky  //   order of their declaration in the base-specifier-list, and then the
6910207619Srdivacky  //   immediate non-static data members of X are assigned, in the order in
6911207619Srdivacky  //   which they were declared in the class definition.
6912207619Srdivacky
6913207619Srdivacky  // The statements that form the synthesized function body.
6914212904Sdim  ASTOwningVector<Stmt*> Statements(*this);
6915207619Srdivacky
6916207619Srdivacky  // The parameter for the "other" object, which we are copying from.
6917207619Srdivacky  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6918207619Srdivacky  Qualifiers OtherQuals = Other->getType().getQualifiers();
6919207619Srdivacky  QualType OtherRefType = Other->getType();
6920207619Srdivacky  if (const LValueReferenceType *OtherRef
6921207619Srdivacky                                = OtherRefType->getAs<LValueReferenceType>()) {
6922207619Srdivacky    OtherRefType = OtherRef->getPointeeType();
6923207619Srdivacky    OtherQuals = OtherRefType.getQualifiers();
6924207619Srdivacky  }
6925207619Srdivacky
6926207619Srdivacky  // Our location for everything implicitly-generated.
6927207619Srdivacky  SourceLocation Loc = CopyAssignOperator->getLocation();
6928207619Srdivacky
6929207619Srdivacky  // Construct a reference to the "other" object. We'll be using this
6930207619Srdivacky  // throughout the generated ASTs.
6931218893Sdim  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
6932207619Srdivacky  assert(OtherRef && "Reference to parameter cannot fail!");
6933207619Srdivacky
6934207619Srdivacky  // Construct the "this" pointer. We'll be using this throughout the generated
6935207619Srdivacky  // ASTs.
6936207619Srdivacky  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6937207619Srdivacky  assert(This && "Reference to this cannot fail!");
6938207619Srdivacky
6939207619Srdivacky  // Assign base classes.
6940207619Srdivacky  bool Invalid = false;
6941195341Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6942195341Sed       E = ClassDecl->bases_end(); Base != E; ++Base) {
6943207619Srdivacky    // Form the assignment:
6944207619Srdivacky    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6945207619Srdivacky    QualType BaseType = Base->getType().getUnqualifiedType();
6946218893Sdim    if (!BaseType->isRecordType()) {
6947207619Srdivacky      Invalid = true;
6948207619Srdivacky      continue;
6949207619Srdivacky    }
6950205219Srdivacky
6951212904Sdim    CXXCastPath BasePath;
6952212904Sdim    BasePath.push_back(Base);
6953212904Sdim
6954207619Srdivacky    // Construct the "from" expression, which is an implicit cast to the
6955207619Srdivacky    // appropriately-qualified base type.
6956218893Sdim    Expr *From = OtherRef;
6957221345Sdim    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6958221345Sdim                             CK_UncheckedDerivedToBase,
6959221345Sdim                             VK_LValue, &BasePath).take();
6960207619Srdivacky
6961207619Srdivacky    // Dereference "this".
6962212904Sdim    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6963207619Srdivacky
6964207619Srdivacky    // Implicitly cast "this" to the appropriately-qualified base type.
6965221345Sdim    To = ImpCastExprToType(To.take(),
6966221345Sdim                           Context.getCVRQualifiedType(BaseType,
6967221345Sdim                                     CopyAssignOperator->getTypeQualifiers()),
6968221345Sdim                           CK_UncheckedDerivedToBase,
6969221345Sdim                           VK_LValue, &BasePath);
6970207619Srdivacky
6971207619Srdivacky    // Build the copy.
6972212904Sdim    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
6973212904Sdim                                            To.get(), From,
6974212904Sdim                                            /*CopyingBaseSubobject=*/true);
6975207619Srdivacky    if (Copy.isInvalid()) {
6976208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
6977208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6978208600Srdivacky      CopyAssignOperator->setInvalidDecl();
6979208600Srdivacky      return;
6980205219Srdivacky    }
6981207619Srdivacky
6982207619Srdivacky    // Success! Record the copy.
6983207619Srdivacky    Statements.push_back(Copy.takeAs<Expr>());
6984195099Sed  }
6985207619Srdivacky
6986207619Srdivacky  // \brief Reference to the __builtin_memcpy function.
6987207619Srdivacky  Expr *BuiltinMemCpyRef = 0;
6988210299Sed  // \brief Reference to the __builtin_objc_memmove_collectable function.
6989210299Sed  Expr *CollectableMemCpyRef = 0;
6990207619Srdivacky
6991207619Srdivacky  // Assign non-static members.
6992195341Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6993207619Srdivacky                                  FieldEnd = ClassDecl->field_end();
6994207619Srdivacky       Field != FieldEnd; ++Field) {
6995207619Srdivacky    // Check for members of reference type; we can't copy those.
6996207619Srdivacky    if (Field->getType()->isReferenceType()) {
6997198092Srdivacky      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6998207619Srdivacky        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6999198092Srdivacky      Diag(Field->getLocation(), diag::note_declared_at);
7000208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
7001208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7002207619Srdivacky      Invalid = true;
7003207619Srdivacky      continue;
7004207619Srdivacky    }
7005207619Srdivacky
7006207619Srdivacky    // Check for members of const-qualified, non-class type.
7007207619Srdivacky    QualType BaseType = Context.getBaseElementType(Field->getType());
7008207619Srdivacky    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7009198092Srdivacky      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7010207619Srdivacky        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7011198092Srdivacky      Diag(Field->getLocation(), diag::note_declared_at);
7012208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
7013208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7014207619Srdivacky      Invalid = true;
7015207619Srdivacky      continue;
7016195099Sed    }
7017207619Srdivacky
7018207619Srdivacky    QualType FieldType = Field->getType().getNonReferenceType();
7019208600Srdivacky    if (FieldType->isIncompleteArrayType()) {
7020208600Srdivacky      assert(ClassDecl->hasFlexibleArrayMember() &&
7021208600Srdivacky             "Incomplete array type is not valid");
7022208600Srdivacky      continue;
7023208600Srdivacky    }
7024207619Srdivacky
7025207619Srdivacky    // Build references to the field in the object we're copying from and to.
7026207619Srdivacky    CXXScopeSpec SS; // Intentionally empty
7027207619Srdivacky    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7028207619Srdivacky                              LookupMemberName);
7029207619Srdivacky    MemberLookup.addDecl(*Field);
7030207619Srdivacky    MemberLookup.resolveKind();
7031212904Sdim    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7032218893Sdim                                               Loc, /*IsArrow=*/false,
7033218893Sdim                                               SS, 0, MemberLookup, 0);
7034212904Sdim    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7035218893Sdim                                             Loc, /*IsArrow=*/true,
7036218893Sdim                                             SS, 0, MemberLookup, 0);
7037207619Srdivacky    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7038207619Srdivacky    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7039207619Srdivacky
7040207619Srdivacky    // If the field should be copied with __builtin_memcpy rather than via
7041207619Srdivacky    // explicit assignments, do so. This optimization only applies for arrays
7042207619Srdivacky    // of scalars and arrays of class type with trivial copy-assignment
7043207619Srdivacky    // operators.
7044207619Srdivacky    if (FieldType->isArrayType() &&
7045207619Srdivacky        (!BaseType->isRecordType() ||
7046207619Srdivacky         cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
7047207619Srdivacky           ->hasTrivialCopyAssignment())) {
7048207619Srdivacky      // Compute the size of the memory buffer to be copied.
7049207619Srdivacky      QualType SizeType = Context.getSizeType();
7050207619Srdivacky      llvm::APInt Size(Context.getTypeSize(SizeType),
7051207619Srdivacky                       Context.getTypeSizeInChars(BaseType).getQuantity());
7052207619Srdivacky      for (const ConstantArrayType *Array
7053207619Srdivacky              = Context.getAsConstantArrayType(FieldType);
7054207619Srdivacky           Array;
7055207619Srdivacky           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7056218893Sdim        llvm::APInt ArraySize
7057218893Sdim          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7058207619Srdivacky        Size *= ArraySize;
7059207619Srdivacky      }
7060207619Srdivacky
7061207619Srdivacky      // Take the address of the field references for "from" and "to".
7062212904Sdim      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7063212904Sdim      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7064210299Sed
7065210299Sed      bool NeedsCollectableMemCpy =
7066210299Sed          (BaseType->isRecordType() &&
7067210299Sed           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7068210299Sed
7069210299Sed      if (NeedsCollectableMemCpy) {
7070210299Sed        if (!CollectableMemCpyRef) {
7071210299Sed          // Create a reference to the __builtin_objc_memmove_collectable function.
7072210299Sed          LookupResult R(*this,
7073210299Sed                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7074210299Sed                         Loc, LookupOrdinaryName);
7075210299Sed          LookupName(R, TUScope, true);
7076210299Sed
7077210299Sed          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7078210299Sed          if (!CollectableMemCpy) {
7079210299Sed            // Something went horribly wrong earlier, and we will have
7080210299Sed            // complained about it.
7081210299Sed            Invalid = true;
7082210299Sed            continue;
7083210299Sed          }
7084210299Sed
7085210299Sed          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7086210299Sed                                                  CollectableMemCpy->getType(),
7087218893Sdim                                                  VK_LValue, Loc, 0).take();
7088210299Sed          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7089210299Sed        }
7090210299Sed      }
7091207619Srdivacky      // Create a reference to the __builtin_memcpy builtin function.
7092210299Sed      else if (!BuiltinMemCpyRef) {
7093207619Srdivacky        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7094207619Srdivacky                       LookupOrdinaryName);
7095207619Srdivacky        LookupName(R, TUScope, true);
7096207619Srdivacky
7097207619Srdivacky        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7098207619Srdivacky        if (!BuiltinMemCpy) {
7099207619Srdivacky          // Something went horribly wrong earlier, and we will have complained
7100207619Srdivacky          // about it.
7101207619Srdivacky          Invalid = true;
7102207619Srdivacky          continue;
7103207619Srdivacky        }
7104207619Srdivacky
7105207619Srdivacky        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7106207619Srdivacky                                            BuiltinMemCpy->getType(),
7107218893Sdim                                            VK_LValue, Loc, 0).take();
7108207619Srdivacky        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7109207619Srdivacky      }
7110207619Srdivacky
7111212904Sdim      ASTOwningVector<Expr*> CallArgs(*this);
7112207619Srdivacky      CallArgs.push_back(To.takeAs<Expr>());
7113207619Srdivacky      CallArgs.push_back(From.takeAs<Expr>());
7114212904Sdim      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7115212904Sdim      ExprResult Call = ExprError();
7116210299Sed      if (NeedsCollectableMemCpy)
7117210299Sed        Call = ActOnCallExpr(/*Scope=*/0,
7118212904Sdim                             CollectableMemCpyRef,
7119210299Sed                             Loc, move_arg(CallArgs),
7120218893Sdim                             Loc);
7121210299Sed      else
7122210299Sed        Call = ActOnCallExpr(/*Scope=*/0,
7123212904Sdim                             BuiltinMemCpyRef,
7124210299Sed                             Loc, move_arg(CallArgs),
7125218893Sdim                             Loc);
7126210299Sed
7127207619Srdivacky      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7128207619Srdivacky      Statements.push_back(Call.takeAs<Expr>());
7129207619Srdivacky      continue;
7130207619Srdivacky    }
7131207619Srdivacky
7132207619Srdivacky    // Build the copy of this field.
7133212904Sdim    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7134212904Sdim                                                  To.get(), From.get(),
7135207632Srdivacky                                              /*CopyingBaseSubobject=*/false);
7136207619Srdivacky    if (Copy.isInvalid()) {
7137208600Srdivacky      Diag(CurrentLocation, diag::note_member_synthesized_at)
7138208600Srdivacky        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7139208600Srdivacky      CopyAssignOperator->setInvalidDecl();
7140208600Srdivacky      return;
7141207619Srdivacky    }
7142207619Srdivacky
7143207619Srdivacky    // Success! Record the copy.
7144207619Srdivacky    Statements.push_back(Copy.takeAs<Stmt>());
7145195099Sed  }
7146203955Srdivacky
7147207619Srdivacky  if (!Invalid) {
7148207619Srdivacky    // Add a "return *this;"
7149212904Sdim    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7150207619Srdivacky
7151212904Sdim    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7152207619Srdivacky    if (Return.isInvalid())
7153207619Srdivacky      Invalid = true;
7154207619Srdivacky    else {
7155207619Srdivacky      Statements.push_back(Return.takeAs<Stmt>());
7156208600Srdivacky
7157208600Srdivacky      if (Trap.hasErrorOccurred()) {
7158208600Srdivacky        Diag(CurrentLocation, diag::note_member_synthesized_at)
7159208600Srdivacky          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7160208600Srdivacky        Invalid = true;
7161208600Srdivacky      }
7162207619Srdivacky    }
7163207619Srdivacky  }
7164195099Sed
7165207619Srdivacky  if (Invalid) {
7166207619Srdivacky    CopyAssignOperator->setInvalidDecl();
7167207619Srdivacky    return;
7168207619Srdivacky  }
7169207619Srdivacky
7170212904Sdim  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7171207619Srdivacky                                            /*isStmtExpr=*/false);
7172207619Srdivacky  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7173207619Srdivacky  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7174221345Sdim
7175221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
7176221345Sdim    L->CompletedImplicitDefinition(CopyAssignOperator);
7177221345Sdim  }
7178195099Sed}
7179195099Sed
7180223017Sdimstd::pair<Sema::ImplicitExceptionSpecification, bool>
7181223017SdimSema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
7182210299Sed  // C++ [class.copy]p5:
7183210299Sed  //   The implicitly-declared copy constructor for a class X will
7184210299Sed  //   have the form
7185210299Sed  //
7186210299Sed  //       X::X(const X&)
7187210299Sed  //
7188210299Sed  //   if
7189223017Sdim  // FIXME: It ought to be possible to store this on the record.
7190210299Sed  bool HasConstCopyConstructor = true;
7191210299Sed
7192210299Sed  //     -- each direct or virtual base class B of X has a copy
7193210299Sed  //        constructor whose first parameter is of type const B& or
7194210299Sed  //        const volatile B&, and
7195210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7196210299Sed                                       BaseEnd = ClassDecl->bases_end();
7197210299Sed       HasConstCopyConstructor && Base != BaseEnd;
7198210299Sed       ++Base) {
7199210299Sed    // Virtual bases are handled below.
7200210299Sed    if (Base->isVirtual())
7201210299Sed      continue;
7202210299Sed
7203210299Sed    CXXRecordDecl *BaseClassDecl
7204210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7205223017Sdim    LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7206223017Sdim                          &HasConstCopyConstructor);
7207210299Sed  }
7208210299Sed
7209210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7210210299Sed                                       BaseEnd = ClassDecl->vbases_end();
7211210299Sed       HasConstCopyConstructor && Base != BaseEnd;
7212210299Sed       ++Base) {
7213210299Sed    CXXRecordDecl *BaseClassDecl
7214210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7215223017Sdim    LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7216223017Sdim                          &HasConstCopyConstructor);
7217210299Sed  }
7218210299Sed
7219210299Sed  //     -- for all the nonstatic data members of X that are of a
7220210299Sed  //        class type M (or array thereof), each such class type
7221210299Sed  //        has a copy constructor whose first parameter is of type
7222210299Sed  //        const M& or const volatile M&.
7223210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7224210299Sed                                  FieldEnd = ClassDecl->field_end();
7225210299Sed       HasConstCopyConstructor && Field != FieldEnd;
7226210299Sed       ++Field) {
7227210299Sed    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7228223017Sdim    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7229223017Sdim      LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7230223017Sdim                            &HasConstCopyConstructor);
7231210299Sed    }
7232210299Sed  }
7233210299Sed  //   Otherwise, the implicitly declared copy constructor will have
7234210299Sed  //   the form
7235210299Sed  //
7236210299Sed  //       X::X(X&)
7237223017Sdim
7238210299Sed  // C++ [except.spec]p14:
7239210299Sed  //   An implicitly declared special member function (Clause 12) shall have an
7240210299Sed  //   exception-specification. [...]
7241210299Sed  ImplicitExceptionSpecification ExceptSpec(Context);
7242210299Sed  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7243210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7244210299Sed                                       BaseEnd = ClassDecl->bases_end();
7245210299Sed       Base != BaseEnd;
7246210299Sed       ++Base) {
7247210299Sed    // Virtual bases are handled below.
7248210299Sed    if (Base->isVirtual())
7249210299Sed      continue;
7250210299Sed
7251210299Sed    CXXRecordDecl *BaseClassDecl
7252210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7253223017Sdim    if (CXXConstructorDecl *CopyConstructor =
7254223017Sdim          LookupCopyConstructor(BaseClassDecl, Quals))
7255210299Sed      ExceptSpec.CalledDecl(CopyConstructor);
7256210299Sed  }
7257210299Sed  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7258210299Sed                                       BaseEnd = ClassDecl->vbases_end();
7259210299Sed       Base != BaseEnd;
7260210299Sed       ++Base) {
7261210299Sed    CXXRecordDecl *BaseClassDecl
7262210299Sed      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7263223017Sdim    if (CXXConstructorDecl *CopyConstructor =
7264223017Sdim          LookupCopyConstructor(BaseClassDecl, Quals))
7265210299Sed      ExceptSpec.CalledDecl(CopyConstructor);
7266210299Sed  }
7267210299Sed  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7268210299Sed                                  FieldEnd = ClassDecl->field_end();
7269210299Sed       Field != FieldEnd;
7270210299Sed       ++Field) {
7271210299Sed    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7272223017Sdim    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7273223017Sdim      if (CXXConstructorDecl *CopyConstructor =
7274223017Sdim        LookupCopyConstructor(FieldClassDecl, Quals))
7275223017Sdim      ExceptSpec.CalledDecl(CopyConstructor);
7276210299Sed    }
7277210299Sed  }
7278221345Sdim
7279223017Sdim  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7280223017Sdim}
7281223017Sdim
7282223017SdimCXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7283223017Sdim                                                    CXXRecordDecl *ClassDecl) {
7284223017Sdim  // C++ [class.copy]p4:
7285223017Sdim  //   If the class definition does not explicitly declare a copy
7286223017Sdim  //   constructor, one is declared implicitly.
7287223017Sdim
7288223017Sdim  ImplicitExceptionSpecification Spec(Context);
7289223017Sdim  bool Const;
7290223017Sdim  llvm::tie(Spec, Const) =
7291223017Sdim    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7292223017Sdim
7293223017Sdim  QualType ClassType = Context.getTypeDeclType(ClassDecl);
7294223017Sdim  QualType ArgType = ClassType;
7295223017Sdim  if (Const)
7296223017Sdim    ArgType = ArgType.withConst();
7297223017Sdim  ArgType = Context.getLValueReferenceType(ArgType);
7298223017Sdim
7299223017Sdim  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7300223017Sdim
7301210299Sed  DeclarationName Name
7302210299Sed    = Context.DeclarationNames.getCXXConstructorName(
7303210299Sed                                           Context.getCanonicalType(ClassType));
7304221345Sdim  SourceLocation ClassLoc = ClassDecl->getLocation();
7305221345Sdim  DeclarationNameInfo NameInfo(Name, ClassLoc);
7306223017Sdim
7307223017Sdim  //   An implicitly-declared copy constructor is an inline public
7308223017Sdim  //   member of its class.
7309210299Sed  CXXConstructorDecl *CopyConstructor
7310221345Sdim    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7311210299Sed                                 Context.getFunctionType(Context.VoidTy,
7312218893Sdim                                                         &ArgType, 1, EPI),
7313210299Sed                                 /*TInfo=*/0,
7314210299Sed                                 /*isExplicit=*/false,
7315210299Sed                                 /*isInline=*/true,
7316210299Sed                                 /*isImplicitlyDeclared=*/true);
7317210299Sed  CopyConstructor->setAccess(AS_public);
7318223017Sdim  CopyConstructor->setDefaulted();
7319210299Sed  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7320210299Sed
7321210299Sed  // Note that we have declared this constructor.
7322210299Sed  ++ASTContext::NumImplicitCopyConstructorsDeclared;
7323210299Sed
7324210299Sed  // Add the parameter to the constructor.
7325210299Sed  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
7326221345Sdim                                               ClassLoc, ClassLoc,
7327210299Sed                                               /*IdentifierInfo=*/0,
7328210299Sed                                               ArgType, /*TInfo=*/0,
7329212904Sdim                                               SC_None,
7330212904Sdim                                               SC_None, 0);
7331210299Sed  CopyConstructor->setParams(&FromParam, 1);
7332223017Sdim
7333210299Sed  if (Scope *S = getScopeForContext(ClassDecl))
7334210299Sed    PushOnScopeChains(CopyConstructor, S, false);
7335210299Sed  ClassDecl->addDecl(CopyConstructor);
7336223017Sdim
7337223017Sdim  if (ShouldDeleteCopyConstructor(CopyConstructor))
7338223017Sdim    CopyConstructor->setDeletedAsWritten();
7339210299Sed
7340210299Sed  return CopyConstructor;
7341210299Sed}
7342210299Sed
7343194711Sedvoid Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
7344223017Sdim                                   CXXConstructorDecl *CopyConstructor) {
7345223017Sdim  assert((CopyConstructor->isDefaulted() &&
7346223017Sdim          CopyConstructor->isCopyConstructor() &&
7347223017Sdim          !CopyConstructor->doesThisDeclarationHaveABody()) &&
7348194711Sed         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
7349198092Srdivacky
7350207619Srdivacky  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
7351194711Sed  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
7352203955Srdivacky
7353207619Srdivacky  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
7354218893Sdim  DiagnosticErrorTrap Trap(Diags);
7355203955Srdivacky
7356218893Sdim  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
7357208600Srdivacky      Trap.hasErrorOccurred()) {
7358207619Srdivacky    Diag(CurrentLocation, diag::note_member_synthesized_at)
7359208600Srdivacky      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
7360207619Srdivacky    CopyConstructor->setInvalidDecl();
7361208600Srdivacky  }  else {
7362208600Srdivacky    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7363208600Srdivacky                                               CopyConstructor->getLocation(),
7364208600Srdivacky                                               MultiStmtArg(*this, 0, 0),
7365208600Srdivacky                                               /*isStmtExpr=*/false)
7366208600Srdivacky                                                              .takeAs<Stmt>());
7367207619Srdivacky  }
7368208600Srdivacky
7369208600Srdivacky  CopyConstructor->setUsed();
7370221345Sdim
7371221345Sdim  if (ASTMutationListener *L = getASTMutationListener()) {
7372221345Sdim    L->CompletedImplicitDefinition(CopyConstructor);
7373221345Sdim  }
7374194711Sed}
7375194711Sed
7376212904SdimExprResult
7377198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7378198092Srdivacky                            CXXConstructorDecl *Constructor,
7379201361Srdivacky                            MultiExprArg ExprArgs,
7380203955Srdivacky                            bool RequiresZeroInit,
7381218893Sdim                            unsigned ConstructKind,
7382218893Sdim                            SourceRange ParenRange) {
7383198092Srdivacky  bool Elidable = false;
7384198092Srdivacky
7385206125Srdivacky  // C++0x [class.copy]p34:
7386206125Srdivacky  //   When certain criteria are met, an implementation is allowed to
7387206125Srdivacky  //   omit the copy/move construction of a class object, even if the
7388206125Srdivacky  //   copy/move constructor and/or destructor for the object have
7389206125Srdivacky  //   side effects. [...]
7390206125Srdivacky  //     - when a temporary class object that has not been bound to a
7391206125Srdivacky  //       reference (12.2) would be copied/moved to a class object
7392206125Srdivacky  //       with the same cv-unqualified type, the copy/move operation
7393206125Srdivacky  //       can be omitted by constructing the temporary object
7394206125Srdivacky  //       directly into the target of the omitted copy/move
7395218893Sdim  if (ConstructKind == CXXConstructExpr::CK_Complete &&
7396218893Sdim      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
7397206125Srdivacky    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
7398218893Sdim    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
7399198092Srdivacky  }
7400198092Srdivacky
7401198092Srdivacky  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
7402203955Srdivacky                               Elidable, move(ExprArgs), RequiresZeroInit,
7403218893Sdim                               ConstructKind, ParenRange);
7404198092Srdivacky}
7405198092Srdivacky
7406198092Srdivacky/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7407198092Srdivacky/// including handling of its default argument expressions.
7408212904SdimExprResult
7409198092SrdivackySema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7410198092Srdivacky                            CXXConstructorDecl *Constructor, bool Elidable,
7411201361Srdivacky                            MultiExprArg ExprArgs,
7412203955Srdivacky                            bool RequiresZeroInit,
7413218893Sdim                            unsigned ConstructKind,
7414218893Sdim                            SourceRange ParenRange) {
7415198092Srdivacky  unsigned NumExprs = ExprArgs.size();
7416198092Srdivacky  Expr **Exprs = (Expr **)ExprArgs.release();
7417198092Srdivacky
7418221345Sdim  for (specific_attr_iterator<NonNullAttr>
7419221345Sdim           i = Constructor->specific_attr_begin<NonNullAttr>(),
7420221345Sdim           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7421221345Sdim    const NonNullAttr *NonNull = *i;
7422221345Sdim    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7423221345Sdim  }
7424221345Sdim
7425199990Srdivacky  MarkDeclarationReferenced(ConstructLoc, Constructor);
7426201361Srdivacky  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
7427201361Srdivacky                                        Constructor, Elidable, Exprs, NumExprs,
7428212904Sdim                                        RequiresZeroInit,
7429218893Sdim              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7430218893Sdim                                        ParenRange));
7431198092Srdivacky}
7432198092Srdivacky
7433198092Srdivackybool Sema::InitializeVarWithConstructor(VarDecl *VD,
7434193326Sed                                        CXXConstructorDecl *Constructor,
7435198092Srdivacky                                        MultiExprArg Exprs) {
7436218893Sdim  // FIXME: Provide the correct paren SourceRange when available.
7437212904Sdim  ExprResult TempResult =
7438198893Srdivacky    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
7439218893Sdim                          move(Exprs), false, CXXConstructExpr::CK_Complete,
7440218893Sdim                          SourceRange());
7441198092Srdivacky  if (TempResult.isInvalid())
7442198092Srdivacky    return true;
7443198092Srdivacky
7444198092Srdivacky  Expr *Temp = TempResult.takeAs<Expr>();
7445218893Sdim  CheckImplicitConversions(Temp, VD->getLocation());
7446194711Sed  MarkDeclarationReferenced(VD->getLocation(), Constructor);
7447218893Sdim  Temp = MaybeCreateExprWithCleanups(Temp);
7448203955Srdivacky  VD->setInit(Temp);
7449198092Srdivacky
7450198092Srdivacky  return false;
7451193326Sed}
7452193326Sed
7453203955Srdivackyvoid Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
7454221345Sdim  if (VD->isInvalidDecl()) return;
7455221345Sdim
7456203955Srdivacky  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
7457221345Sdim  if (ClassDecl->isInvalidDecl()) return;
7458221345Sdim  if (ClassDecl->hasTrivialDestructor()) return;
7459221345Sdim  if (ClassDecl->isDependentContext()) return;
7460212904Sdim
7461221345Sdim  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7462221345Sdim  MarkDeclarationReferenced(VD->getLocation(), Destructor);
7463221345Sdim  CheckDestructorAccess(VD->getLocation(), Destructor,
7464221345Sdim                        PDiag(diag::err_access_dtor_var)
7465221345Sdim                        << VD->getDeclName()
7466221345Sdim                        << VD->getType());
7467221345Sdim
7468221345Sdim  if (!VD->hasGlobalStorage()) return;
7469221345Sdim
7470221345Sdim  // Emit warning for non-trivial dtor in global scope (a real global,
7471221345Sdim  // class-static, function-static).
7472221345Sdim  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7473221345Sdim
7474221345Sdim  // TODO: this should be re-enabled for static locals by !CXAAtExit
7475221345Sdim  if (!VD->isStaticLocal())
7476221345Sdim    Diag(VD->getLocation(), diag::warn_global_destructor);
7477195099Sed}
7478195099Sed
7479198092Srdivacky/// AddCXXDirectInitializerToDecl - This action is called immediately after
7480193326Sed/// ActOnDeclarator, when a C++ direct initializer is present.
7481193326Sed/// e.g: "int x(1);"
7482212904Sdimvoid Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
7483193326Sed                                         SourceLocation LParenLoc,
7484193326Sed                                         MultiExprArg Exprs,
7485218893Sdim                                         SourceLocation RParenLoc,
7486218893Sdim                                         bool TypeMayContainAuto) {
7487201361Srdivacky  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
7488193326Sed
7489193326Sed  // If there is no declaration, there was an error parsing it.  Just ignore
7490193326Sed  // the initializer.
7491193326Sed  if (RealDecl == 0)
7492193326Sed    return;
7493198092Srdivacky
7494193326Sed  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7495193326Sed  if (!VDecl) {
7496193326Sed    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7497193326Sed    RealDecl->setInvalidDecl();
7498193326Sed    return;
7499193326Sed  }
7500193326Sed
7501218893Sdim  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7502218893Sdim  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
7503218893Sdim    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7504218893Sdim    if (Exprs.size() > 1) {
7505218893Sdim      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7506218893Sdim           diag::err_auto_var_init_multiple_expressions)
7507218893Sdim        << VDecl->getDeclName() << VDecl->getType()
7508218893Sdim        << VDecl->getSourceRange();
7509218893Sdim      RealDecl->setInvalidDecl();
7510218893Sdim      return;
7511218893Sdim    }
7512218893Sdim
7513218893Sdim    Expr *Init = Exprs.get()[0];
7514221345Sdim    TypeSourceInfo *DeducedType = 0;
7515221345Sdim    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
7516218893Sdim      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7517218893Sdim        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7518218893Sdim        << Init->getSourceRange();
7519221345Sdim    if (!DeducedType) {
7520218893Sdim      RealDecl->setInvalidDecl();
7521218893Sdim      return;
7522218893Sdim    }
7523221345Sdim    VDecl->setTypeSourceInfo(DeducedType);
7524221345Sdim    VDecl->setType(DeducedType->getType());
7525218893Sdim
7526218893Sdim    // If this is a redeclaration, check that the type we just deduced matches
7527218893Sdim    // the previously declared type.
7528218893Sdim    if (VarDecl *Old = VDecl->getPreviousDeclaration())
7529218893Sdim      MergeVarDeclTypes(VDecl, Old);
7530218893Sdim  }
7531218893Sdim
7532198092Srdivacky  // We will represent direct-initialization similarly to copy-initialization:
7533193326Sed  //    int x(1);  -as-> int x = 1;
7534193326Sed  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7535193326Sed  //
7536193326Sed  // Clients that want to distinguish between the two forms, can check for
7537193326Sed  // direct initializer using VarDecl::hasCXXDirectInitializer().
7538193326Sed  // A major benefit is that clients that don't particularly care about which
7539193326Sed  // exactly form was it (like the CodeGen) can handle both cases without
7540193326Sed  // special case code.
7541193326Sed
7542193326Sed  // C++ 8.5p11:
7543193326Sed  // The form of initialization (using parentheses or '=') is generally
7544193326Sed  // insignificant, but does matter when the entity being initialized has a
7545193326Sed  // class type.
7546193326Sed
7547203955Srdivacky  if (!VDecl->getType()->isDependentType() &&
7548203955Srdivacky      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
7549193326Sed                          diag::err_typecheck_decl_incomplete_type)) {
7550193326Sed    VDecl->setInvalidDecl();
7551193326Sed    return;
7552193326Sed  }
7553193326Sed
7554201361Srdivacky  // The variable can not have an abstract class type.
7555201361Srdivacky  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7556201361Srdivacky                             diag::err_abstract_type_in_decl,
7557201361Srdivacky                             AbstractVariableType))
7558201361Srdivacky    VDecl->setInvalidDecl();
7559201361Srdivacky
7560203955Srdivacky  const VarDecl *Def;
7561203955Srdivacky  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7562201361Srdivacky    Diag(VDecl->getLocation(), diag::err_redefinition)
7563201361Srdivacky    << VDecl->getDeclName();
7564201361Srdivacky    Diag(Def->getLocation(), diag::note_previous_definition);
7565201361Srdivacky    VDecl->setInvalidDecl();
7566193326Sed    return;
7567193326Sed  }
7568203955Srdivacky
7569212904Sdim  // C++ [class.static.data]p4
7570212904Sdim  //   If a static data member is of const integral or const
7571212904Sdim  //   enumeration type, its declaration in the class definition can
7572212904Sdim  //   specify a constant-initializer which shall be an integral
7573212904Sdim  //   constant expression (5.19). In that case, the member can appear
7574212904Sdim  //   in integral constant expressions. The member shall still be
7575212904Sdim  //   defined in a namespace scope if it is used in the program and the
7576212904Sdim  //   namespace scope definition shall not contain an initializer.
7577212904Sdim  //
7578212904Sdim  // We already performed a redefinition check above, but for static
7579212904Sdim  // data members we also need to check whether there was an in-class
7580212904Sdim  // declaration with an initializer.
7581212904Sdim  const VarDecl* PrevInit = 0;
7582212904Sdim  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7583212904Sdim    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7584212904Sdim    Diag(PrevInit->getLocation(), diag::note_previous_definition);
7585212904Sdim    return;
7586212904Sdim  }
7587212904Sdim
7588218893Sdim  bool IsDependent = false;
7589218893Sdim  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7590218893Sdim    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7591218893Sdim      VDecl->setInvalidDecl();
7592218893Sdim      return;
7593218893Sdim    }
7594218893Sdim
7595218893Sdim    if (Exprs.get()[I]->isTypeDependent())
7596218893Sdim      IsDependent = true;
7597218893Sdim  }
7598218893Sdim
7599203955Srdivacky  // If either the declaration has a dependent type or if any of the
7600203955Srdivacky  // expressions is type-dependent, we represent the initialization
7601203955Srdivacky  // via a ParenListExpr for later use during template instantiation.
7602218893Sdim  if (VDecl->getType()->isDependentType() || IsDependent) {
7603203955Srdivacky    // Let clients know that initialization was done with a direct initializer.
7604203955Srdivacky    VDecl->setCXXDirectInitializer(true);
7605203955Srdivacky
7606203955Srdivacky    // Store the initialization expressions as a ParenListExpr.
7607203955Srdivacky    unsigned NumExprs = Exprs.size();
7608203955Srdivacky    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7609203955Srdivacky                                               (Expr **)Exprs.release(),
7610203955Srdivacky                                               NumExprs, RParenLoc));
7611203955Srdivacky    return;
7612203955Srdivacky  }
7613201361Srdivacky
7614201361Srdivacky  // Capture the variable that is being initialized and the style of
7615201361Srdivacky  // initialization.
7616201361Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7617201361Srdivacky
7618201361Srdivacky  // FIXME: Poor source location information.
7619201361Srdivacky  InitializationKind Kind
7620201361Srdivacky    = InitializationKind::CreateDirect(VDecl->getLocation(),
7621201361Srdivacky                                       LParenLoc, RParenLoc);
7622201361Srdivacky
7623201361Srdivacky  InitializationSequence InitSeq(*this, Entity, Kind,
7624212904Sdim                                 Exprs.get(), Exprs.size());
7625212904Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
7626201361Srdivacky  if (Result.isInvalid()) {
7627201361Srdivacky    VDecl->setInvalidDecl();
7628193326Sed    return;
7629193326Sed  }
7630218893Sdim
7631218893Sdim  CheckImplicitConversions(Result.get(), LParenLoc);
7632201361Srdivacky
7633218893Sdim  Result = MaybeCreateExprWithCleanups(Result);
7634203955Srdivacky  VDecl->setInit(Result.takeAs<Expr>());
7635193326Sed  VDecl->setCXXDirectInitializer(true);
7636193326Sed
7637218893Sdim  CheckCompleteVariableDeclaration(VDecl);
7638193326Sed}
7639193326Sed
7640198092Srdivacky/// \brief Given a constructor and the set of arguments provided for the
7641198092Srdivacky/// constructor, convert the arguments and add any required default arguments
7642198092Srdivacky/// to form a proper call to this constructor.
7643198092Srdivacky///
7644198092Srdivacky/// \returns true if an error occurred, false otherwise.
7645198092Srdivackybool
7646198092SrdivackySema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7647198092Srdivacky                              MultiExprArg ArgsPtr,
7648198092Srdivacky                              SourceLocation Loc,
7649212904Sdim                              ASTOwningVector<Expr*> &ConvertedArgs) {
7650198092Srdivacky  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7651198092Srdivacky  unsigned NumArgs = ArgsPtr.size();
7652198092Srdivacky  Expr **Args = (Expr **)ArgsPtr.get();
7653198092Srdivacky
7654198092Srdivacky  const FunctionProtoType *Proto
7655198092Srdivacky    = Constructor->getType()->getAs<FunctionProtoType>();
7656198092Srdivacky  assert(Proto && "Constructor without a prototype?");
7657198092Srdivacky  unsigned NumArgsInProto = Proto->getNumArgs();
7658198092Srdivacky
7659198092Srdivacky  // If too few arguments are available, we'll fill in the rest with defaults.
7660199990Srdivacky  if (NumArgs < NumArgsInProto)
7661198092Srdivacky    ConvertedArgs.reserve(NumArgsInProto);
7662199990Srdivacky  else
7663198092Srdivacky    ConvertedArgs.reserve(NumArgs);
7664199990Srdivacky
7665199990Srdivacky  VariadicCallType CallType =
7666199990Srdivacky    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7667199990Srdivacky  llvm::SmallVector<Expr *, 8> AllArgs;
7668199990Srdivacky  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7669199990Srdivacky                                        Proto, 0, Args, NumArgs, AllArgs,
7670199990Srdivacky                                        CallType);
7671199990Srdivacky  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7672199990Srdivacky    ConvertedArgs.push_back(AllArgs[i]);
7673199990Srdivacky  return Invalid;
7674198092Srdivacky}
7675198092Srdivacky
7676200583Srdivackystatic inline bool
7677200583SrdivackyCheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7678200583Srdivacky                                       const FunctionDecl *FnDecl) {
7679212904Sdim  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
7680200583Srdivacky  if (isa<NamespaceDecl>(DC)) {
7681200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7682200583Srdivacky                        diag::err_operator_new_delete_declared_in_namespace)
7683200583Srdivacky      << FnDecl->getDeclName();
7684200583Srdivacky  }
7685200583Srdivacky
7686200583Srdivacky  if (isa<TranslationUnitDecl>(DC) &&
7687212904Sdim      FnDecl->getStorageClass() == SC_Static) {
7688200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7689200583Srdivacky                        diag::err_operator_new_delete_declared_static)
7690200583Srdivacky      << FnDecl->getDeclName();
7691200583Srdivacky  }
7692200583Srdivacky
7693200583Srdivacky  return false;
7694200583Srdivacky}
7695200583Srdivacky
7696200583Srdivackystatic inline bool
7697200583SrdivackyCheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7698200583Srdivacky                            CanQualType ExpectedResultType,
7699200583Srdivacky                            CanQualType ExpectedFirstParamType,
7700200583Srdivacky                            unsigned DependentParamTypeDiag,
7701200583Srdivacky                            unsigned InvalidParamTypeDiag) {
7702200583Srdivacky  QualType ResultType =
7703200583Srdivacky    FnDecl->getType()->getAs<FunctionType>()->getResultType();
7704200583Srdivacky
7705200583Srdivacky  // Check that the result type is not dependent.
7706200583Srdivacky  if (ResultType->isDependentType())
7707200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7708200583Srdivacky                        diag::err_operator_new_delete_dependent_result_type)
7709200583Srdivacky    << FnDecl->getDeclName() << ExpectedResultType;
7710200583Srdivacky
7711200583Srdivacky  // Check that the result type is what we expect.
7712200583Srdivacky  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7713200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7714200583Srdivacky                        diag::err_operator_new_delete_invalid_result_type)
7715200583Srdivacky    << FnDecl->getDeclName() << ExpectedResultType;
7716200583Srdivacky
7717200583Srdivacky  // A function template must have at least 2 parameters.
7718200583Srdivacky  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7719200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7720200583Srdivacky                      diag::err_operator_new_delete_template_too_few_parameters)
7721200583Srdivacky        << FnDecl->getDeclName();
7722200583Srdivacky
7723200583Srdivacky  // The function decl must have at least 1 parameter.
7724200583Srdivacky  if (FnDecl->getNumParams() == 0)
7725200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7726200583Srdivacky                        diag::err_operator_new_delete_too_few_parameters)
7727200583Srdivacky      << FnDecl->getDeclName();
7728200583Srdivacky
7729200583Srdivacky  // Check the the first parameter type is not dependent.
7730200583Srdivacky  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7731200583Srdivacky  if (FirstParamType->isDependentType())
7732200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7733200583Srdivacky      << FnDecl->getDeclName() << ExpectedFirstParamType;
7734200583Srdivacky
7735200583Srdivacky  // Check that the first parameter type is what we expect.
7736201361Srdivacky  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
7737200583Srdivacky      ExpectedFirstParamType)
7738200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7739200583Srdivacky    << FnDecl->getDeclName() << ExpectedFirstParamType;
7740200583Srdivacky
7741200583Srdivacky  return false;
7742200583Srdivacky}
7743200583Srdivacky
7744200583Srdivackystatic bool
7745200583SrdivackyCheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7746200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
7747200583Srdivacky  //   A program is ill-formed if an allocation function is declared in a
7748200583Srdivacky  //   namespace scope other than global scope or declared static in global
7749200583Srdivacky  //   scope.
7750200583Srdivacky  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7751200583Srdivacky    return true;
7752200583Srdivacky
7753200583Srdivacky  CanQualType SizeTy =
7754200583Srdivacky    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7755200583Srdivacky
7756200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
7757200583Srdivacky  //  The return type shall be void*. The first parameter shall have type
7758200583Srdivacky  //  std::size_t.
7759200583Srdivacky  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7760200583Srdivacky                                  SizeTy,
7761200583Srdivacky                                  diag::err_operator_new_dependent_param_type,
7762200583Srdivacky                                  diag::err_operator_new_param_type))
7763200583Srdivacky    return true;
7764200583Srdivacky
7765200583Srdivacky  // C++ [basic.stc.dynamic.allocation]p1:
7766200583Srdivacky  //  The first parameter shall not have an associated default argument.
7767200583Srdivacky  if (FnDecl->getParamDecl(0)->hasDefaultArg())
7768200583Srdivacky    return SemaRef.Diag(FnDecl->getLocation(),
7769200583Srdivacky                        diag::err_operator_new_default_arg)
7770200583Srdivacky      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7771200583Srdivacky
7772200583Srdivacky  return false;
7773200583Srdivacky}
7774200583Srdivacky
7775200583Srdivackystatic bool
7776200583SrdivackyCheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7777200583Srdivacky  // C++ [basic.stc.dynamic.deallocation]p1:
7778200583Srdivacky  //   A program is ill-formed if deallocation functions are declared in a
7779200583Srdivacky  //   namespace scope other than global scope or declared static in global
7780200583Srdivacky  //   scope.
7781200583Srdivacky  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7782200583Srdivacky    return true;
7783200583Srdivacky
7784200583Srdivacky  // C++ [basic.stc.dynamic.deallocation]p2:
7785200583Srdivacky  //   Each deallocation function shall return void and its first parameter
7786200583Srdivacky  //   shall be void*.
7787200583Srdivacky  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7788200583Srdivacky                                  SemaRef.Context.VoidPtrTy,
7789200583Srdivacky                                 diag::err_operator_delete_dependent_param_type,
7790200583Srdivacky                                 diag::err_operator_delete_param_type))
7791200583Srdivacky    return true;
7792200583Srdivacky
7793200583Srdivacky  return false;
7794200583Srdivacky}
7795200583Srdivacky
7796193326Sed/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7797193326Sed/// of this overloaded operator is well-formed. If so, returns false;
7798193326Sed/// otherwise, emits appropriate diagnostics and returns true.
7799193326Sedbool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
7800193326Sed  assert(FnDecl && FnDecl->isOverloadedOperator() &&
7801193326Sed         "Expected an overloaded operator declaration");
7802193326Sed
7803193326Sed  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7804193326Sed
7805198092Srdivacky  // C++ [over.oper]p5:
7806193326Sed  //   The allocation and deallocation functions, operator new,
7807193326Sed  //   operator new[], operator delete and operator delete[], are
7808193326Sed  //   described completely in 3.7.3. The attributes and restrictions
7809193326Sed  //   found in the rest of this subclause do not apply to them unless
7810193326Sed  //   explicitly stated in 3.7.3.
7811199482Srdivacky  if (Op == OO_Delete || Op == OO_Array_Delete)
7812200583Srdivacky    return CheckOperatorDeleteDeclaration(*this, FnDecl);
7813199482Srdivacky
7814200583Srdivacky  if (Op == OO_New || Op == OO_Array_New)
7815200583Srdivacky    return CheckOperatorNewDeclaration(*this, FnDecl);
7816193326Sed
7817193326Sed  // C++ [over.oper]p6:
7818193326Sed  //   An operator function shall either be a non-static member
7819193326Sed  //   function or be a non-member function and have at least one
7820193326Sed  //   parameter whose type is a class, a reference to a class, an
7821193326Sed  //   enumeration, or a reference to an enumeration.
7822193326Sed  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7823193326Sed    if (MethodDecl->isStatic())
7824193326Sed      return Diag(FnDecl->getLocation(),
7825193326Sed                  diag::err_operator_overload_static) << FnDecl->getDeclName();
7826193326Sed  } else {
7827193326Sed    bool ClassOrEnumParam = false;
7828193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7829193326Sed                                   ParamEnd = FnDecl->param_end();
7830193326Sed         Param != ParamEnd; ++Param) {
7831193326Sed      QualType ParamType = (*Param)->getType().getNonReferenceType();
7832195099Sed      if (ParamType->isDependentType() || ParamType->isRecordType() ||
7833195099Sed          ParamType->isEnumeralType()) {
7834193326Sed        ClassOrEnumParam = true;
7835193326Sed        break;
7836193326Sed      }
7837193326Sed    }
7838193326Sed
7839193326Sed    if (!ClassOrEnumParam)
7840193326Sed      return Diag(FnDecl->getLocation(),
7841193326Sed                  diag::err_operator_overload_needs_class_or_enum)
7842193326Sed        << FnDecl->getDeclName();
7843193326Sed  }
7844193326Sed
7845193326Sed  // C++ [over.oper]p8:
7846193326Sed  //   An operator function cannot have default arguments (8.3.6),
7847193326Sed  //   except where explicitly stated below.
7848193326Sed  //
7849198092Srdivacky  // Only the function-call operator allows default arguments
7850193326Sed  // (C++ [over.call]p1).
7851193326Sed  if (Op != OO_Call) {
7852193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7853193326Sed         Param != FnDecl->param_end(); ++Param) {
7854200583Srdivacky      if ((*Param)->hasDefaultArg())
7855198092Srdivacky        return Diag((*Param)->getLocation(),
7856193326Sed                    diag::err_operator_overload_default_arg)
7857200583Srdivacky          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
7858193326Sed    }
7859193326Sed  }
7860193326Sed
7861193326Sed  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7862193326Sed    { false, false, false }
7863193326Sed#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7864193326Sed    , { Unary, Binary, MemberOnly }
7865193326Sed#include "clang/Basic/OperatorKinds.def"
7866193326Sed  };
7867193326Sed
7868193326Sed  bool CanBeUnaryOperator = OperatorUses[Op][0];
7869193326Sed  bool CanBeBinaryOperator = OperatorUses[Op][1];
7870193326Sed  bool MustBeMemberOperator = OperatorUses[Op][2];
7871193326Sed
7872193326Sed  // C++ [over.oper]p8:
7873193326Sed  //   [...] Operator functions cannot have more or fewer parameters
7874193326Sed  //   than the number required for the corresponding operator, as
7875193326Sed  //   described in the rest of this subclause.
7876198092Srdivacky  unsigned NumParams = FnDecl->getNumParams()
7877193326Sed                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
7878193326Sed  if (Op != OO_Call &&
7879193326Sed      ((NumParams == 1 && !CanBeUnaryOperator) ||
7880193326Sed       (NumParams == 2 && !CanBeBinaryOperator) ||
7881193326Sed       (NumParams < 1) || (NumParams > 2))) {
7882193326Sed    // We have the wrong number of parameters.
7883193326Sed    unsigned ErrorKind;
7884193326Sed    if (CanBeUnaryOperator && CanBeBinaryOperator) {
7885193326Sed      ErrorKind = 2;  // 2 -> unary or binary.
7886193326Sed    } else if (CanBeUnaryOperator) {
7887193326Sed      ErrorKind = 0;  // 0 -> unary
7888193326Sed    } else {
7889193326Sed      assert(CanBeBinaryOperator &&
7890193326Sed             "All non-call overloaded operators are unary or binary!");
7891193326Sed      ErrorKind = 1;  // 1 -> binary
7892193326Sed    }
7893193326Sed
7894193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
7895193326Sed      << FnDecl->getDeclName() << NumParams << ErrorKind;
7896193326Sed  }
7897193326Sed
7898193326Sed  // Overloaded operators other than operator() cannot be variadic.
7899193326Sed  if (Op != OO_Call &&
7900198092Srdivacky      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
7901193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
7902193326Sed      << FnDecl->getDeclName();
7903193326Sed  }
7904193326Sed
7905193326Sed  // Some operators must be non-static member functions.
7906193326Sed  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7907193326Sed    return Diag(FnDecl->getLocation(),
7908193326Sed                diag::err_operator_overload_must_be_member)
7909193326Sed      << FnDecl->getDeclName();
7910193326Sed  }
7911193326Sed
7912193326Sed  // C++ [over.inc]p1:
7913193326Sed  //   The user-defined function called operator++ implements the
7914193326Sed  //   prefix and postfix ++ operator. If this function is a member
7915193326Sed  //   function with no parameters, or a non-member function with one
7916193326Sed  //   parameter of class or enumeration type, it defines the prefix
7917193326Sed  //   increment operator ++ for objects of that type. If the function
7918193326Sed  //   is a member function with one parameter (which shall be of type
7919193326Sed  //   int) or a non-member function with two parameters (the second
7920193326Sed  //   of which shall be of type int), it defines the postfix
7921193326Sed  //   increment operator ++ for objects of that type.
7922193326Sed  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7923193326Sed    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7924193326Sed    bool ParamIsInt = false;
7925198092Srdivacky    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
7926193326Sed      ParamIsInt = BT->getKind() == BuiltinType::Int;
7927193326Sed
7928193326Sed    if (!ParamIsInt)
7929193326Sed      return Diag(LastParam->getLocation(),
7930198092Srdivacky                  diag::err_operator_overload_post_incdec_must_be_int)
7931193326Sed        << LastParam->getType() << (Op == OO_MinusMinus);
7932193326Sed  }
7933193326Sed
7934193326Sed  return false;
7935193326Sed}
7936193326Sed
7937202379Srdivacky/// CheckLiteralOperatorDeclaration - Check whether the declaration
7938202379Srdivacky/// of this literal operator function is well-formed. If so, returns
7939202379Srdivacky/// false; otherwise, emits appropriate diagnostics and returns true.
7940202379Srdivackybool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7941202379Srdivacky  DeclContext *DC = FnDecl->getDeclContext();
7942202379Srdivacky  Decl::Kind Kind = DC->getDeclKind();
7943202379Srdivacky  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7944202379Srdivacky      Kind != Decl::LinkageSpec) {
7945202379Srdivacky    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7946202379Srdivacky      << FnDecl->getDeclName();
7947202379Srdivacky    return true;
7948202379Srdivacky  }
7949202379Srdivacky
7950202379Srdivacky  bool Valid = false;
7951202379Srdivacky
7952207619Srdivacky  // template <char...> type operator "" name() is the only valid template
7953207619Srdivacky  // signature, and the only valid signature with no parameters.
7954207619Srdivacky  if (FnDecl->param_size() == 0) {
7955207619Srdivacky    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7956207619Srdivacky      // Must have only one template parameter
7957207619Srdivacky      TemplateParameterList *Params = TpDecl->getTemplateParameters();
7958207619Srdivacky      if (Params->size() == 1) {
7959207619Srdivacky        NonTypeTemplateParmDecl *PmDecl =
7960207619Srdivacky          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
7961202379Srdivacky
7962207619Srdivacky        // The template parameter must be a char parameter pack.
7963207619Srdivacky        if (PmDecl && PmDecl->isTemplateParameterPack() &&
7964207619Srdivacky            Context.hasSameType(PmDecl->getType(), Context.CharTy))
7965207619Srdivacky          Valid = true;
7966207619Srdivacky      }
7967207619Srdivacky    }
7968207619Srdivacky  } else {
7969202379Srdivacky    // Check the first parameter
7970207619Srdivacky    FunctionDecl::param_iterator Param = FnDecl->param_begin();
7971207619Srdivacky
7972202379Srdivacky    QualType T = (*Param)->getType();
7973202379Srdivacky
7974207619Srdivacky    // unsigned long long int, long double, and any character type are allowed
7975207619Srdivacky    // as the only parameters.
7976202379Srdivacky    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7977202379Srdivacky        Context.hasSameType(T, Context.LongDoubleTy) ||
7978202379Srdivacky        Context.hasSameType(T, Context.CharTy) ||
7979202379Srdivacky        Context.hasSameType(T, Context.WCharTy) ||
7980202379Srdivacky        Context.hasSameType(T, Context.Char16Ty) ||
7981202379Srdivacky        Context.hasSameType(T, Context.Char32Ty)) {
7982202379Srdivacky      if (++Param == FnDecl->param_end())
7983202379Srdivacky        Valid = true;
7984202379Srdivacky      goto FinishedParams;
7985202379Srdivacky    }
7986202379Srdivacky
7987207619Srdivacky    // Otherwise it must be a pointer to const; let's strip those qualifiers.
7988202379Srdivacky    const PointerType *PT = T->getAs<PointerType>();
7989202379Srdivacky    if (!PT)
7990202379Srdivacky      goto FinishedParams;
7991202379Srdivacky    T = PT->getPointeeType();
7992202379Srdivacky    if (!T.isConstQualified())
7993202379Srdivacky      goto FinishedParams;
7994202379Srdivacky    T = T.getUnqualifiedType();
7995202379Srdivacky
7996202379Srdivacky    // Move on to the second parameter;
7997202379Srdivacky    ++Param;
7998202379Srdivacky
7999202379Srdivacky    // If there is no second parameter, the first must be a const char *
8000202379Srdivacky    if (Param == FnDecl->param_end()) {
8001202379Srdivacky      if (Context.hasSameType(T, Context.CharTy))
8002202379Srdivacky        Valid = true;
8003202379Srdivacky      goto FinishedParams;
8004202379Srdivacky    }
8005202379Srdivacky
8006202379Srdivacky    // const char *, const wchar_t*, const char16_t*, and const char32_t*
8007202379Srdivacky    // are allowed as the first parameter to a two-parameter function
8008202379Srdivacky    if (!(Context.hasSameType(T, Context.CharTy) ||
8009202379Srdivacky          Context.hasSameType(T, Context.WCharTy) ||
8010202379Srdivacky          Context.hasSameType(T, Context.Char16Ty) ||
8011202379Srdivacky          Context.hasSameType(T, Context.Char32Ty)))
8012202379Srdivacky      goto FinishedParams;
8013202379Srdivacky
8014202379Srdivacky    // The second and final parameter must be an std::size_t
8015202379Srdivacky    T = (*Param)->getType().getUnqualifiedType();
8016202379Srdivacky    if (Context.hasSameType(T, Context.getSizeType()) &&
8017202379Srdivacky        ++Param == FnDecl->param_end())
8018202379Srdivacky      Valid = true;
8019202379Srdivacky  }
8020202379Srdivacky
8021202379Srdivacky  // FIXME: This diagnostic is absolutely terrible.
8022202379SrdivackyFinishedParams:
8023202379Srdivacky  if (!Valid) {
8024202379Srdivacky    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8025202379Srdivacky      << FnDecl->getDeclName();
8026202379Srdivacky    return true;
8027202379Srdivacky  }
8028202379Srdivacky
8029202379Srdivacky  return false;
8030202379Srdivacky}
8031202379Srdivacky
8032193326Sed/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8033193326Sed/// linkage specification, including the language and (if present)
8034193326Sed/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8035193326Sed/// the location of the language string literal, which is provided
8036193326Sed/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8037193326Sed/// the '{' brace. Otherwise, this linkage specification does not
8038193326Sed/// have any braces.
8039218893SdimDecl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8040218893Sdim                                           SourceLocation LangLoc,
8041218893Sdim                                           llvm::StringRef Lang,
8042218893Sdim                                           SourceLocation LBraceLoc) {
8043193326Sed  LinkageSpecDecl::LanguageIDs Language;
8044207619Srdivacky  if (Lang == "\"C\"")
8045193326Sed    Language = LinkageSpecDecl::lang_c;
8046207619Srdivacky  else if (Lang == "\"C++\"")
8047193326Sed    Language = LinkageSpecDecl::lang_cxx;
8048193326Sed  else {
8049193326Sed    Diag(LangLoc, diag::err_bad_language);
8050212904Sdim    return 0;
8051193326Sed  }
8052198092Srdivacky
8053193326Sed  // FIXME: Add all the various semantics of linkage specifications
8054198092Srdivacky
8055193326Sed  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
8056221345Sdim                                               ExternLoc, LangLoc, Language);
8057195341Sed  CurContext->addDecl(D);
8058193326Sed  PushDeclContext(S, D);
8059212904Sdim  return D;
8060193326Sed}
8061193326Sed
8062212904Sdim/// ActOnFinishLinkageSpecification - Complete the definition of
8063193326Sed/// the C++ linkage specification LinkageSpec. If RBraceLoc is
8064193326Sed/// valid, it's the position of the closing '}' brace in a linkage
8065193326Sed/// specification that uses braces.
8066212904SdimDecl *Sema::ActOnFinishLinkageSpecification(Scope *S,
8067221345Sdim                                            Decl *LinkageSpec,
8068221345Sdim                                            SourceLocation RBraceLoc) {
8069221345Sdim  if (LinkageSpec) {
8070221345Sdim    if (RBraceLoc.isValid()) {
8071221345Sdim      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8072221345Sdim      LSDecl->setRBraceLoc(RBraceLoc);
8073221345Sdim    }
8074193326Sed    PopDeclContext();
8075221345Sdim  }
8076193326Sed  return LinkageSpec;
8077193326Sed}
8078193326Sed
8079193326Sed/// \brief Perform semantic analysis for the variable declaration that
8080193326Sed/// occurs within a C++ catch clause, returning the newly-created
8081193326Sed/// variable.
8082221345SdimVarDecl *Sema::BuildExceptionDeclaration(Scope *S,
8083200583Srdivacky                                         TypeSourceInfo *TInfo,
8084221345Sdim                                         SourceLocation StartLoc,
8085221345Sdim                                         SourceLocation Loc,
8086221345Sdim                                         IdentifierInfo *Name) {
8087193326Sed  bool Invalid = false;
8088218893Sdim  QualType ExDeclType = TInfo->getType();
8089218893Sdim
8090193326Sed  // Arrays and functions decay.
8091193326Sed  if (ExDeclType->isArrayType())
8092193326Sed    ExDeclType = Context.getArrayDecayedType(ExDeclType);
8093193326Sed  else if (ExDeclType->isFunctionType())
8094193326Sed    ExDeclType = Context.getPointerType(ExDeclType);
8095193326Sed
8096193326Sed  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8097193326Sed  // The exception-declaration shall not denote a pointer or reference to an
8098193326Sed  // incomplete type, other than [cv] void*.
8099193326Sed  // N2844 forbids rvalue references.
8100198092Srdivacky  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
8101218893Sdim    Diag(Loc, diag::err_catch_rvalue_ref);
8102193326Sed    Invalid = true;
8103193326Sed  }
8104193326Sed
8105204962Srdivacky  // GCC allows catching pointers and references to incomplete types
8106204962Srdivacky  // as an extension; so do we, but we warn by default.
8107204962Srdivacky
8108193326Sed  QualType BaseType = ExDeclType;
8109193326Sed  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
8110193326Sed  unsigned DK = diag::err_catch_incomplete;
8111204962Srdivacky  bool IncompleteCatchIsInvalid = true;
8112198092Srdivacky  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
8113193326Sed    BaseType = Ptr->getPointeeType();
8114193326Sed    Mode = 1;
8115204962Srdivacky    DK = diag::ext_catch_incomplete_ptr;
8116204962Srdivacky    IncompleteCatchIsInvalid = false;
8117198092Srdivacky  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
8118193326Sed    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
8119193326Sed    BaseType = Ref->getPointeeType();
8120193326Sed    Mode = 2;
8121204962Srdivacky    DK = diag::ext_catch_incomplete_ref;
8122204962Srdivacky    IncompleteCatchIsInvalid = false;
8123193326Sed  }
8124193326Sed  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
8125204962Srdivacky      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8126204962Srdivacky      IncompleteCatchIsInvalid)
8127193326Sed    Invalid = true;
8128193326Sed
8129198092Srdivacky  if (!Invalid && !ExDeclType->isDependentType() &&
8130193326Sed      RequireNonAbstractType(Loc, ExDeclType,
8131193326Sed                             diag::err_abstract_type_in_decl,
8132193326Sed                             AbstractVariableType))
8133193326Sed    Invalid = true;
8134193326Sed
8135212904Sdim  // Only the non-fragile NeXT runtime currently supports C++ catches
8136212904Sdim  // of ObjC types, and no runtime supports catching ObjC types by value.
8137212904Sdim  if (!Invalid && getLangOptions().ObjC1) {
8138212904Sdim    QualType T = ExDeclType;
8139212904Sdim    if (const ReferenceType *RT = T->getAs<ReferenceType>())
8140212904Sdim      T = RT->getPointeeType();
8141212904Sdim
8142212904Sdim    if (T->isObjCObjectType()) {
8143212904Sdim      Diag(Loc, diag::err_objc_object_catch);
8144212904Sdim      Invalid = true;
8145212904Sdim    } else if (T->isObjCObjectPointerType()) {
8146221345Sdim      if (!getLangOptions().ObjCNonFragileABI) {
8147212904Sdim        Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8148212904Sdim        Invalid = true;
8149212904Sdim      }
8150212904Sdim    }
8151212904Sdim  }
8152212904Sdim
8153221345Sdim  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8154221345Sdim                                    ExDeclType, TInfo, SC_None, SC_None);
8155207619Srdivacky  ExDecl->setExceptionVariable(true);
8156207619Srdivacky
8157204793Srdivacky  if (!Invalid) {
8158218893Sdim    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
8159204793Srdivacky      // C++ [except.handle]p16:
8160204793Srdivacky      //   The object declared in an exception-declaration or, if the
8161204793Srdivacky      //   exception-declaration does not specify a name, a temporary (12.2) is
8162204793Srdivacky      //   copy-initialized (8.5) from the exception object. [...]
8163204793Srdivacky      //   The object is destroyed when the handler exits, after the destruction
8164204793Srdivacky      //   of any automatic objects initialized within the handler.
8165204793Srdivacky      //
8166204793Srdivacky      // We just pretend to initialize the object with itself, then make sure
8167204793Srdivacky      // it can be destroyed later.
8168218893Sdim      QualType initType = ExDeclType;
8169218893Sdim
8170218893Sdim      InitializedEntity entity =
8171218893Sdim        InitializedEntity::InitializeVariable(ExDecl);
8172218893Sdim      InitializationKind initKind =
8173218893Sdim        InitializationKind::CreateCopy(Loc, SourceLocation());
8174218893Sdim
8175218893Sdim      Expr *opaqueValue =
8176218893Sdim        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8177218893Sdim      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8178218893Sdim      ExprResult result = sequence.Perform(*this, entity, initKind,
8179218893Sdim                                           MultiExprArg(&opaqueValue, 1));
8180218893Sdim      if (result.isInvalid())
8181204793Srdivacky        Invalid = true;
8182218893Sdim      else {
8183218893Sdim        // If the constructor used was non-trivial, set this as the
8184218893Sdim        // "initializer".
8185218893Sdim        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8186218893Sdim        if (!construct->getConstructor()->isTrivial()) {
8187218893Sdim          Expr *init = MaybeCreateExprWithCleanups(construct);
8188218893Sdim          ExDecl->setInit(init);
8189218893Sdim        }
8190218893Sdim
8191218893Sdim        // And make sure it's destructable.
8192218893Sdim        FinalizeVarWithDestructor(ExDecl, recordType);
8193218893Sdim      }
8194204793Srdivacky    }
8195204793Srdivacky  }
8196204793Srdivacky
8197193326Sed  if (Invalid)
8198193326Sed    ExDecl->setInvalidDecl();
8199193326Sed
8200193326Sed  return ExDecl;
8201193326Sed}
8202193326Sed
8203193326Sed/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8204193326Sed/// handler.
8205212904SdimDecl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
8206210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8207218893Sdim  bool Invalid = D.isInvalidType();
8208193326Sed
8209218893Sdim  // Check for unexpanded parameter packs.
8210218893Sdim  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8211218893Sdim                                               UPPC_ExceptionType)) {
8212218893Sdim    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8213218893Sdim                                             D.getIdentifierLoc());
8214218893Sdim    Invalid = true;
8215218893Sdim  }
8216218893Sdim
8217193326Sed  IdentifierInfo *II = D.getIdentifier();
8218207619Srdivacky  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
8219207619Srdivacky                                             LookupOrdinaryName,
8220207619Srdivacky                                             ForRedeclaration)) {
8221193326Sed    // The scope should be freshly made just for us. There is just no way
8222193326Sed    // it contains any previous declaration.
8223212904Sdim    assert(!S->isDeclScope(PrevDecl));
8224193326Sed    if (PrevDecl->isTemplateParameter()) {
8225193326Sed      // Maybe we will complain about the shadowed template parameter.
8226193326Sed      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8227193326Sed    }
8228193326Sed  }
8229193326Sed
8230193326Sed  if (D.getCXXScopeSpec().isSet() && !Invalid) {
8231193326Sed    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8232193326Sed      << D.getCXXScopeSpec().getRange();
8233193326Sed    Invalid = true;
8234193326Sed  }
8235193326Sed
8236218893Sdim  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
8237221345Sdim                                              D.getSourceRange().getBegin(),
8238221345Sdim                                              D.getIdentifierLoc(),
8239221345Sdim                                              D.getIdentifier());
8240193326Sed  if (Invalid)
8241193326Sed    ExDecl->setInvalidDecl();
8242198092Srdivacky
8243193326Sed  // Add the exception declaration into this scope.
8244193326Sed  if (II)
8245193326Sed    PushOnScopeChains(ExDecl, S);
8246193326Sed  else
8247195341Sed    CurContext->addDecl(ExDecl);
8248193326Sed
8249194613Sed  ProcessDeclAttributes(S, ExDecl, D);
8250212904Sdim  return ExDecl;
8251193326Sed}
8252193326Sed
8253221345SdimDecl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
8254212904Sdim                                         Expr *AssertExpr,
8255221345Sdim                                         Expr *AssertMessageExpr_,
8256221345Sdim                                         SourceLocation RParenLoc) {
8257212904Sdim  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
8258193326Sed
8259193326Sed  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8260193326Sed    llvm::APSInt Value(32);
8261193326Sed    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
8262221345Sdim      Diag(StaticAssertLoc,
8263221345Sdim           diag::err_static_assert_expression_is_not_constant) <<
8264193326Sed        AssertExpr->getSourceRange();
8265212904Sdim      return 0;
8266193326Sed    }
8267193326Sed
8268193326Sed    if (Value == 0) {
8269221345Sdim      Diag(StaticAssertLoc, diag::err_static_assert_failed)
8270200583Srdivacky        << AssertMessage->getString() << AssertExpr->getSourceRange();
8271193326Sed    }
8272193326Sed  }
8273198092Srdivacky
8274218893Sdim  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8275218893Sdim    return 0;
8276218893Sdim
8277221345Sdim  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8278221345Sdim                                        AssertExpr, AssertMessage, RParenLoc);
8279198092Srdivacky
8280195341Sed  CurContext->addDecl(Decl);
8281212904Sdim  return Decl;
8282193326Sed}
8283193326Sed
8284207619Srdivacky/// \brief Perform semantic analysis of the given friend type declaration.
8285207619Srdivacky///
8286207619Srdivacky/// \returns A friend declaration that.
8287207619SrdivackyFriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8288207619Srdivacky                                      TypeSourceInfo *TSInfo) {
8289207619Srdivacky  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8290207619Srdivacky
8291207619Srdivacky  QualType T = TSInfo->getType();
8292208600Srdivacky  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
8293207619Srdivacky
8294207619Srdivacky  if (!getLangOptions().CPlusPlus0x) {
8295207619Srdivacky    // C++03 [class.friend]p2:
8296207619Srdivacky    //   An elaborated-type-specifier shall be used in a friend declaration
8297207619Srdivacky    //   for a class.*
8298207619Srdivacky    //
8299207619Srdivacky    //   * The class-key of the elaborated-type-specifier is required.
8300207619Srdivacky    if (!ActiveTemplateInstantiations.empty()) {
8301207619Srdivacky      // Do not complain about the form of friend template types during
8302207619Srdivacky      // template instantiation; we will already have complained when the
8303207619Srdivacky      // template was declared.
8304207619Srdivacky    } else if (!T->isElaboratedTypeSpecifier()) {
8305207619Srdivacky      // If we evaluated the type to a record type, suggest putting
8306207619Srdivacky      // a tag in front.
8307207619Srdivacky      if (const RecordType *RT = T->getAs<RecordType>()) {
8308207619Srdivacky        RecordDecl *RD = RT->getDecl();
8309207619Srdivacky
8310207619Srdivacky        std::string InsertionText = std::string(" ") + RD->getKindName();
8311207619Srdivacky
8312207619Srdivacky        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8313207619Srdivacky          << (unsigned) RD->getTagKind()
8314207619Srdivacky          << T
8315207619Srdivacky          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8316207619Srdivacky                                        InsertionText);
8317207619Srdivacky      } else {
8318207619Srdivacky        Diag(FriendLoc, diag::ext_nonclass_type_friend)
8319207619Srdivacky          << T
8320207619Srdivacky          << SourceRange(FriendLoc, TypeRange.getEnd());
8321207619Srdivacky      }
8322207619Srdivacky    } else if (T->getAs<EnumType>()) {
8323207619Srdivacky      Diag(FriendLoc, diag::ext_enum_friend)
8324207619Srdivacky        << T
8325207619Srdivacky        << SourceRange(FriendLoc, TypeRange.getEnd());
8326207619Srdivacky    }
8327207619Srdivacky  }
8328207619Srdivacky
8329207619Srdivacky  // C++0x [class.friend]p3:
8330207619Srdivacky  //   If the type specifier in a friend declaration designates a (possibly
8331207619Srdivacky  //   cv-qualified) class type, that class is declared as a friend; otherwise,
8332207619Srdivacky  //   the friend declaration is ignored.
8333207619Srdivacky
8334207619Srdivacky  // FIXME: C++0x has some syntactic restrictions on friend type declarations
8335207619Srdivacky  // in [class.friend]p3 that we do not implement.
8336207619Srdivacky
8337207619Srdivacky  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8338207619Srdivacky}
8339207619Srdivacky
8340218893Sdim/// Handle a friend tag declaration where the scope specifier was
8341218893Sdim/// templated.
8342218893SdimDecl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8343218893Sdim                                    unsigned TagSpec, SourceLocation TagLoc,
8344218893Sdim                                    CXXScopeSpec &SS,
8345218893Sdim                                    IdentifierInfo *Name, SourceLocation NameLoc,
8346218893Sdim                                    AttributeList *Attr,
8347218893Sdim                                    MultiTemplateParamsArg TempParamLists) {
8348218893Sdim  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8349218893Sdim
8350218893Sdim  bool isExplicitSpecialization = false;
8351218893Sdim  bool Invalid = false;
8352218893Sdim
8353218893Sdim  if (TemplateParameterList *TemplateParams
8354223017Sdim        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
8355218893Sdim                                                  TempParamLists.get(),
8356218893Sdim                                                  TempParamLists.size(),
8357218893Sdim                                                  /*friend*/ true,
8358218893Sdim                                                  isExplicitSpecialization,
8359218893Sdim                                                  Invalid)) {
8360218893Sdim    if (TemplateParams->size() > 0) {
8361218893Sdim      // This is a declaration of a class template.
8362218893Sdim      if (Invalid)
8363218893Sdim        return 0;
8364221345Sdim
8365218893Sdim      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8366218893Sdim                                SS, Name, NameLoc, Attr,
8367221345Sdim                                TemplateParams, AS_public,
8368221345Sdim                                TempParamLists.size() - 1,
8369221345Sdim                   (TemplateParameterList**) TempParamLists.release()).take();
8370218893Sdim    } else {
8371218893Sdim      // The "template<>" header is extraneous.
8372218893Sdim      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8373218893Sdim        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8374218893Sdim      isExplicitSpecialization = true;
8375218893Sdim    }
8376218893Sdim  }
8377218893Sdim
8378218893Sdim  if (Invalid) return 0;
8379218893Sdim
8380218893Sdim  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8381218893Sdim
8382218893Sdim  bool isAllExplicitSpecializations = true;
8383221345Sdim  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
8384218893Sdim    if (TempParamLists.get()[I]->size()) {
8385218893Sdim      isAllExplicitSpecializations = false;
8386218893Sdim      break;
8387218893Sdim    }
8388218893Sdim  }
8389218893Sdim
8390218893Sdim  // FIXME: don't ignore attributes.
8391218893Sdim
8392218893Sdim  // If it's explicit specializations all the way down, just forget
8393218893Sdim  // about the template header and build an appropriate non-templated
8394218893Sdim  // friend.  TODO: for source fidelity, remember the headers.
8395218893Sdim  if (isAllExplicitSpecializations) {
8396221345Sdim    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8397218893Sdim    ElaboratedTypeKeyword Keyword
8398218893Sdim      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8399221345Sdim    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
8400221345Sdim                                   *Name, NameLoc);
8401218893Sdim    if (T.isNull())
8402218893Sdim      return 0;
8403218893Sdim
8404218893Sdim    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8405218893Sdim    if (isa<DependentNameType>(T)) {
8406218893Sdim      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8407218893Sdim      TL.setKeywordLoc(TagLoc);
8408221345Sdim      TL.setQualifierLoc(QualifierLoc);
8409218893Sdim      TL.setNameLoc(NameLoc);
8410218893Sdim    } else {
8411218893Sdim      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8412218893Sdim      TL.setKeywordLoc(TagLoc);
8413221345Sdim      TL.setQualifierLoc(QualifierLoc);
8414218893Sdim      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8415218893Sdim    }
8416218893Sdim
8417218893Sdim    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8418218893Sdim                                            TSI, FriendLoc);
8419218893Sdim    Friend->setAccess(AS_public);
8420218893Sdim    CurContext->addDecl(Friend);
8421218893Sdim    return Friend;
8422218893Sdim  }
8423218893Sdim
8424218893Sdim  // Handle the case of a templated-scope friend class.  e.g.
8425218893Sdim  //   template <class T> class A<T>::B;
8426218893Sdim  // FIXME: we don't support these right now.
8427218893Sdim  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8428218893Sdim  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8429218893Sdim  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8430218893Sdim  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8431218893Sdim  TL.setKeywordLoc(TagLoc);
8432221345Sdim  TL.setQualifierLoc(SS.getWithLocInContext(Context));
8433218893Sdim  TL.setNameLoc(NameLoc);
8434218893Sdim
8435218893Sdim  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8436218893Sdim                                          TSI, FriendLoc);
8437218893Sdim  Friend->setAccess(AS_public);
8438218893Sdim  Friend->setUnsupportedFriend(true);
8439218893Sdim  CurContext->addDecl(Friend);
8440218893Sdim  return Friend;
8441218893Sdim}
8442218893Sdim
8443218893Sdim
8444198092Srdivacky/// Handle a friend type declaration.  This works in tandem with
8445198092Srdivacky/// ActOnTag.
8446198092Srdivacky///
8447198092Srdivacky/// Notes on friend class templates:
8448198092Srdivacky///
8449198092Srdivacky/// We generally treat friend class declarations as if they were
8450198092Srdivacky/// declaring a class.  So, for example, the elaborated type specifier
8451198092Srdivacky/// in a friend declaration is required to obey the restrictions of a
8452198092Srdivacky/// class-head (i.e. no typedefs in the scope chain), template
8453198092Srdivacky/// parameters are required to match up with simple template-ids, &c.
8454198092Srdivacky/// However, unlike when declaring a template specialization, it's
8455198092Srdivacky/// okay to refer to a template specialization without an empty
8456198092Srdivacky/// template parameter declaration, e.g.
8457198092Srdivacky///   friend class A<T>::B<unsigned>;
8458198092Srdivacky/// We permit this as a special case; if there are any template
8459198092Srdivacky/// parameters present at all, require proper matching, i.e.
8460198092Srdivacky///   template <> template <class T> friend class A<int>::B;
8461212904SdimDecl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
8462218893Sdim                                MultiTemplateParamsArg TempParams) {
8463198092Srdivacky  SourceLocation Loc = DS.getSourceRange().getBegin();
8464198092Srdivacky
8465198092Srdivacky  assert(DS.isFriendSpecified());
8466198092Srdivacky  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8467198092Srdivacky
8468198092Srdivacky  // Try to convert the decl specifier to a type.  This works for
8469198092Srdivacky  // friend templates because ActOnTag never produces a ClassTemplateDecl
8470198092Srdivacky  // for a TUK_Friend.
8471198893Srdivacky  Declarator TheDeclarator(DS, Declarator::MemberContext);
8472210299Sed  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8473210299Sed  QualType T = TSI->getType();
8474198893Srdivacky  if (TheDeclarator.isInvalidType())
8475212904Sdim    return 0;
8476198092Srdivacky
8477218893Sdim  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8478218893Sdim    return 0;
8479218893Sdim
8480198092Srdivacky  // This is definitely an error in C++98.  It's probably meant to
8481198092Srdivacky  // be forbidden in C++0x, too, but the specification is just
8482198092Srdivacky  // poorly written.
8483198092Srdivacky  //
8484198092Srdivacky  // The problem is with declarations like the following:
8485198092Srdivacky  //   template <T> friend A<T>::foo;
8486198092Srdivacky  // where deciding whether a class C is a friend or not now hinges
8487198092Srdivacky  // on whether there exists an instantiation of A that causes
8488198092Srdivacky  // 'foo' to equal C.  There are restrictions on class-heads
8489198092Srdivacky  // (which we declare (by fiat) elaborated friend declarations to
8490198092Srdivacky  // be) that makes this tractable.
8491198092Srdivacky  //
8492198092Srdivacky  // FIXME: handle "template <> friend class A<T>;", which
8493198092Srdivacky  // is possibly well-formed?  Who even knows?
8494206084Srdivacky  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
8495198092Srdivacky    Diag(Loc, diag::err_tagless_friend_type_template)
8496198092Srdivacky      << DS.getSourceRange();
8497212904Sdim    return 0;
8498193326Sed  }
8499207619Srdivacky
8500198092Srdivacky  // C++98 [class.friend]p1: A friend of a class is a function
8501198092Srdivacky  //   or class that is not a member of the class . . .
8502201361Srdivacky  // This is fixed in DR77, which just barely didn't make the C++03
8503201361Srdivacky  // deadline.  It's also a very silly restriction that seriously
8504201361Srdivacky  // affects inner classes and which nobody else seems to implement;
8505201361Srdivacky  // thus we never diagnose it, not even in -pedantic.
8506206084Srdivacky  //
8507206084Srdivacky  // But note that we could warn about it: it's always useless to
8508206084Srdivacky  // friend one of your own members (it's not, however, worthless to
8509206084Srdivacky  // friend a member of an arbitrary specialization of your template).
8510198092Srdivacky
8511198092Srdivacky  Decl *D;
8512207619Srdivacky  if (unsigned NumTempParamLists = TempParams.size())
8513198092Srdivacky    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
8514207619Srdivacky                                   NumTempParamLists,
8515218893Sdim                                   TempParams.release(),
8516206084Srdivacky                                   TSI,
8517198092Srdivacky                                   DS.getFriendSpecLoc());
8518198092Srdivacky  else
8519207619Srdivacky    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8520207619Srdivacky
8521207619Srdivacky  if (!D)
8522212904Sdim    return 0;
8523207619Srdivacky
8524198092Srdivacky  D->setAccess(AS_public);
8525198092Srdivacky  CurContext->addDecl(D);
8526198092Srdivacky
8527212904Sdim  return D;
8528193326Sed}
8529193326Sed
8530218893SdimDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8531218893Sdim                                    MultiTemplateParamsArg TemplateParams) {
8532198092Srdivacky  const DeclSpec &DS = D.getDeclSpec();
8533198092Srdivacky
8534198092Srdivacky  assert(DS.isFriendSpecified());
8535198092Srdivacky  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8536198092Srdivacky
8537198092Srdivacky  SourceLocation Loc = D.getIdentifierLoc();
8538210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8539210299Sed  QualType T = TInfo->getType();
8540198092Srdivacky
8541198092Srdivacky  // C++ [class.friend]p1
8542198092Srdivacky  //   A friend of a class is a function or class....
8543198092Srdivacky  // Note that this sees through typedefs, which is intended.
8544198092Srdivacky  // It *doesn't* see through dependent types, which is correct
8545198092Srdivacky  // according to [temp.arg.type]p3:
8546198092Srdivacky  //   If a declaration acquires a function type through a
8547198092Srdivacky  //   type dependent on a template-parameter and this causes
8548198092Srdivacky  //   a declaration that does not use the syntactic form of a
8549198092Srdivacky  //   function declarator to have a function type, the program
8550198092Srdivacky  //   is ill-formed.
8551198092Srdivacky  if (!T->isFunctionType()) {
8552198092Srdivacky    Diag(Loc, diag::err_unexpected_friend);
8553198092Srdivacky
8554198092Srdivacky    // It might be worthwhile to try to recover by creating an
8555198092Srdivacky    // appropriate declaration.
8556212904Sdim    return 0;
8557198092Srdivacky  }
8558198092Srdivacky
8559198092Srdivacky  // C++ [namespace.memdef]p3
8560198092Srdivacky  //  - If a friend declaration in a non-local class first declares a
8561198092Srdivacky  //    class or function, the friend class or function is a member
8562198092Srdivacky  //    of the innermost enclosing namespace.
8563198092Srdivacky  //  - The name of the friend is not found by simple name lookup
8564198092Srdivacky  //    until a matching declaration is provided in that namespace
8565198092Srdivacky  //    scope (either before or after the class declaration granting
8566198092Srdivacky  //    friendship).
8567198092Srdivacky  //  - If a friend function is called, its name may be found by the
8568198092Srdivacky  //    name lookup that considers functions from namespaces and
8569198092Srdivacky  //    classes associated with the types of the function arguments.
8570198092Srdivacky  //  - When looking for a prior declaration of a class or a function
8571198092Srdivacky  //    declared as a friend, scopes outside the innermost enclosing
8572198092Srdivacky  //    namespace scope are not considered.
8573198092Srdivacky
8574218893Sdim  CXXScopeSpec &SS = D.getCXXScopeSpec();
8575212904Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8576212904Sdim  DeclarationName Name = NameInfo.getName();
8577198092Srdivacky  assert(Name);
8578198092Srdivacky
8579218893Sdim  // Check for unexpanded parameter packs.
8580218893Sdim  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8581218893Sdim      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8582218893Sdim      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8583218893Sdim    return 0;
8584218893Sdim
8585198092Srdivacky  // The context we found the declaration in, or in which we should
8586198092Srdivacky  // create the declaration.
8587198092Srdivacky  DeclContext *DC;
8588218893Sdim  Scope *DCScope = S;
8589218893Sdim  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8590218893Sdim                        ForRedeclaration);
8591198092Srdivacky
8592218893Sdim  // FIXME: there are different rules in local classes
8593198092Srdivacky
8594218893Sdim  // There are four cases here.
8595218893Sdim  //   - There's no scope specifier, in which case we just go to the
8596218893Sdim  //     appropriate scope and look for a function or function template
8597218893Sdim  //     there as appropriate.
8598198092Srdivacky  // Recover from invalid scope qualifiers as if they just weren't there.
8599218893Sdim  if (SS.isInvalid() || !SS.isSet()) {
8600218893Sdim    // C++0x [namespace.memdef]p3:
8601218893Sdim    //   If the name in a friend declaration is neither qualified nor
8602218893Sdim    //   a template-id and the declaration is a function or an
8603218893Sdim    //   elaborated-type-specifier, the lookup to determine whether
8604218893Sdim    //   the entity has been previously declared shall not consider
8605218893Sdim    //   any scopes outside the innermost enclosing namespace.
8606218893Sdim    // C++0x [class.friend]p11:
8607218893Sdim    //   If a friend declaration appears in a local class and the name
8608218893Sdim    //   specified is an unqualified name, a prior declaration is
8609218893Sdim    //   looked up without considering scopes that are outside the
8610218893Sdim    //   innermost enclosing non-class scope. For a friend function
8611218893Sdim    //   declaration, if there is no prior declaration, the program is
8612218893Sdim    //   ill-formed.
8613218893Sdim    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
8614218893Sdim    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
8615198092Srdivacky
8616218893Sdim    // Find the appropriate context according to the above.
8617218893Sdim    DC = CurContext;
8618218893Sdim    while (true) {
8619218893Sdim      // Skip class contexts.  If someone can cite chapter and verse
8620218893Sdim      // for this behavior, that would be nice --- it's what GCC and
8621218893Sdim      // EDG do, and it seems like a reasonable intent, but the spec
8622218893Sdim      // really only says that checks for unqualified existing
8623218893Sdim      // declarations should stop at the nearest enclosing namespace,
8624218893Sdim      // not that they should only consider the nearest enclosing
8625218893Sdim      // namespace.
8626218893Sdim      while (DC->isRecord())
8627218893Sdim        DC = DC->getParent();
8628218893Sdim
8629218893Sdim      LookupQualifiedName(Previous, DC);
8630218893Sdim
8631218893Sdim      // TODO: decide what we think about using declarations.
8632218893Sdim      if (isLocal || !Previous.empty())
8633218893Sdim        break;
8634218893Sdim
8635218893Sdim      if (isTemplateId) {
8636218893Sdim        if (isa<TranslationUnitDecl>(DC)) break;
8637218893Sdim      } else {
8638218893Sdim        if (DC->isFileContext()) break;
8639218893Sdim      }
8640218893Sdim      DC = DC->getParent();
8641218893Sdim    }
8642218893Sdim
8643218893Sdim    // C++ [class.friend]p1: A friend of a class is a function or
8644218893Sdim    //   class that is not a member of the class . . .
8645218893Sdim    // C++0x changes this for both friend types and functions.
8646218893Sdim    // Most C++ 98 compilers do seem to give an error here, so
8647218893Sdim    // we do, too.
8648218893Sdim    if (!Previous.empty() && DC->Equals(CurContext)
8649218893Sdim        && !getLangOptions().CPlusPlus0x)
8650218893Sdim      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8651218893Sdim
8652218893Sdim    DCScope = getScopeForDeclContext(S, DC);
8653218893Sdim
8654218893Sdim  //   - There's a non-dependent scope specifier, in which case we
8655218893Sdim  //     compute it and do a previous lookup there for a function
8656218893Sdim  //     or function template.
8657218893Sdim  } else if (!SS.getScopeRep()->isDependent()) {
8658218893Sdim    DC = computeDeclContext(SS);
8659212904Sdim    if (!DC) return 0;
8660198092Srdivacky
8661218893Sdim    if (RequireCompleteDeclContext(SS, DC)) return 0;
8662218893Sdim
8663199512Srdivacky    LookupQualifiedName(Previous, DC);
8664198092Srdivacky
8665210299Sed    // Ignore things found implicitly in the wrong scope.
8666198092Srdivacky    // TODO: better diagnostics for this case.  Suggesting the right
8667198092Srdivacky    // qualified scope would be nice...
8668210299Sed    LookupResult::Filter F = Previous.makeFilter();
8669210299Sed    while (F.hasNext()) {
8670210299Sed      NamedDecl *D = F.next();
8671212904Sdim      if (!DC->InEnclosingNamespaceSetOf(
8672212904Sdim              D->getDeclContext()->getRedeclContext()))
8673210299Sed        F.erase();
8674210299Sed    }
8675210299Sed    F.done();
8676210299Sed
8677210299Sed    if (Previous.empty()) {
8678198092Srdivacky      D.setInvalidType();
8679198092Srdivacky      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8680212904Sdim      return 0;
8681198092Srdivacky    }
8682198092Srdivacky
8683198092Srdivacky    // C++ [class.friend]p1: A friend of a class is a function or
8684198092Srdivacky    //   class that is not a member of the class . . .
8685198092Srdivacky    if (DC->Equals(CurContext))
8686198092Srdivacky      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8687198092Srdivacky
8688218893Sdim  //   - There's a scope specifier that does not match any template
8689218893Sdim  //     parameter lists, in which case we use some arbitrary context,
8690218893Sdim  //     create a method or method template, and wait for instantiation.
8691218893Sdim  //   - There's a scope specifier that does match some template
8692218893Sdim  //     parameter lists, which we don't handle right now.
8693198092Srdivacky  } else {
8694198092Srdivacky    DC = CurContext;
8695218893Sdim    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
8696198092Srdivacky  }
8697198092Srdivacky
8698218893Sdim  if (!DC->isRecord()) {
8699198092Srdivacky    // This implies that it has to be an operator or function.
8700198893Srdivacky    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8701198893Srdivacky        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8702198893Srdivacky        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
8703198092Srdivacky      Diag(Loc, diag::err_introducing_special_friend) <<
8704198893Srdivacky        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8705198893Srdivacky         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
8706212904Sdim      return 0;
8707198092Srdivacky    }
8708198092Srdivacky  }
8709198092Srdivacky
8710198092Srdivacky  bool Redeclaration = false;
8711218893Sdim  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
8712198092Srdivacky                                          move(TemplateParams),
8713198092Srdivacky                                          IsDefinition,
8714198092Srdivacky                                          Redeclaration);
8715212904Sdim  if (!ND) return 0;
8716198092Srdivacky
8717198092Srdivacky  assert(ND->getDeclContext() == DC);
8718198092Srdivacky  assert(ND->getLexicalDeclContext() == CurContext);
8719198092Srdivacky
8720198092Srdivacky  // Add the function declaration to the appropriate lookup tables,
8721198092Srdivacky  // adjusting the redeclarations list as necessary.  We don't
8722198092Srdivacky  // want to do this yet if the friending class is dependent.
8723198092Srdivacky  //
8724198092Srdivacky  // Also update the scope-based lookup if the target context's
8725198092Srdivacky  // lookup context is in lexical scope.
8726198092Srdivacky  if (!CurContext->isDependentContext()) {
8727212904Sdim    DC = DC->getRedeclContext();
8728198092Srdivacky    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
8729198092Srdivacky    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8730198092Srdivacky      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
8731198092Srdivacky  }
8732198092Srdivacky
8733198092Srdivacky  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
8734198092Srdivacky                                       D.getIdentifierLoc(), ND,
8735198092Srdivacky                                       DS.getFriendSpecLoc());
8736198092Srdivacky  FrD->setAccess(AS_public);
8737198092Srdivacky  CurContext->addDecl(FrD);
8738198092Srdivacky
8739218893Sdim  if (ND->isInvalidDecl())
8740218893Sdim    FrD->setInvalidDecl();
8741218893Sdim  else {
8742218893Sdim    FunctionDecl *FD;
8743218893Sdim    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8744218893Sdim      FD = FTD->getTemplatedDecl();
8745218893Sdim    else
8746218893Sdim      FD = cast<FunctionDecl>(ND);
8747218893Sdim
8748218893Sdim    // Mark templated-scope function declarations as unsupported.
8749218893Sdim    if (FD->getNumTemplateParameterLists())
8750218893Sdim      FrD->setUnsupportedFriend(true);
8751218893Sdim  }
8752218893Sdim
8753212904Sdim  return ND;
8754198092Srdivacky}
8755198092Srdivacky
8756212904Sdimvoid Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8757212904Sdim  AdjustDeclIfTemplate(Dcl);
8758198092Srdivacky
8759193326Sed  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8760193326Sed  if (!Fn) {
8761193326Sed    Diag(DelLoc, diag::err_deleted_non_function);
8762193326Sed    return;
8763193326Sed  }
8764193326Sed  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8765193326Sed    Diag(DelLoc, diag::err_deleted_decl_not_first);
8766193326Sed    Diag(Prev->getLocation(), diag::note_previous_declaration);
8767193326Sed    // If the declaration wasn't the first, we delete the function anyway for
8768193326Sed    // recovery.
8769193326Sed  }
8770223017Sdim  Fn->setDeletedAsWritten();
8771193326Sed}
8772193326Sed
8773223017Sdimvoid Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8774223017Sdim  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8775223017Sdim
8776223017Sdim  if (MD) {
8777223017Sdim    if (MD->getParent()->isDependentType()) {
8778223017Sdim      MD->setDefaulted();
8779223017Sdim      MD->setExplicitlyDefaulted();
8780223017Sdim      return;
8781223017Sdim    }
8782223017Sdim
8783223017Sdim    CXXSpecialMember Member = getSpecialMember(MD);
8784223017Sdim    if (Member == CXXInvalid) {
8785223017Sdim      Diag(DefaultLoc, diag::err_default_special_members);
8786223017Sdim      return;
8787223017Sdim    }
8788223017Sdim
8789223017Sdim    MD->setDefaulted();
8790223017Sdim    MD->setExplicitlyDefaulted();
8791223017Sdim
8792223017Sdim    // If this definition appears within the record, do the checking when
8793223017Sdim    // the record is complete.
8794223017Sdim    const FunctionDecl *Primary = MD;
8795223017Sdim    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8796223017Sdim      // Find the uninstantiated declaration that actually had the '= default'
8797223017Sdim      // on it.
8798223017Sdim      MD->getTemplateInstantiationPattern()->isDefined(Primary);
8799223017Sdim
8800223017Sdim    if (Primary == Primary->getCanonicalDecl())
8801223017Sdim      return;
8802223017Sdim
8803223017Sdim    switch (Member) {
8804223017Sdim    case CXXDefaultConstructor: {
8805223017Sdim      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8806223017Sdim      CheckExplicitlyDefaultedDefaultConstructor(CD);
8807223017Sdim      if (!CD->isInvalidDecl())
8808223017Sdim        DefineImplicitDefaultConstructor(DefaultLoc, CD);
8809223017Sdim      break;
8810223017Sdim    }
8811223017Sdim
8812223017Sdim    case CXXCopyConstructor: {
8813223017Sdim      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8814223017Sdim      CheckExplicitlyDefaultedCopyConstructor(CD);
8815223017Sdim      if (!CD->isInvalidDecl())
8816223017Sdim        DefineImplicitCopyConstructor(DefaultLoc, CD);
8817223017Sdim      break;
8818223017Sdim    }
8819223017Sdim
8820223017Sdim    case CXXCopyAssignment: {
8821223017Sdim      CheckExplicitlyDefaultedCopyAssignment(MD);
8822223017Sdim      if (!MD->isInvalidDecl())
8823223017Sdim        DefineImplicitCopyAssignment(DefaultLoc, MD);
8824223017Sdim      break;
8825223017Sdim    }
8826223017Sdim
8827223017Sdim    case CXXDestructor: {
8828223017Sdim      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8829223017Sdim      CheckExplicitlyDefaultedDestructor(DD);
8830223017Sdim      if (!DD->isInvalidDecl())
8831223017Sdim        DefineImplicitDestructor(DefaultLoc, DD);
8832223017Sdim      break;
8833223017Sdim    }
8834223017Sdim
8835223017Sdim    case CXXMoveConstructor:
8836223017Sdim    case CXXMoveAssignment:
8837223017Sdim      Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8838223017Sdim      break;
8839223017Sdim
8840223017Sdim    default:
8841223017Sdim      // FIXME: Do the rest once we have move functions
8842223017Sdim      break;
8843223017Sdim    }
8844223017Sdim  } else {
8845223017Sdim    Diag(DefaultLoc, diag::err_default_special_members);
8846223017Sdim  }
8847223017Sdim}
8848223017Sdim
8849193326Sedstatic void SearchForReturnInStmt(Sema &Self, Stmt *S) {
8850218893Sdim  for (Stmt::child_range CI = S->children(); CI; ++CI) {
8851193326Sed    Stmt *SubStmt = *CI;
8852193326Sed    if (!SubStmt)
8853193326Sed      continue;
8854193326Sed    if (isa<ReturnStmt>(SubStmt))
8855193326Sed      Self.Diag(SubStmt->getSourceRange().getBegin(),
8856193326Sed           diag::err_return_in_constructor_handler);
8857193326Sed    if (!isa<Expr>(SubStmt))
8858193326Sed      SearchForReturnInStmt(Self, SubStmt);
8859193326Sed  }
8860193326Sed}
8861193326Sed
8862193326Sedvoid Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8863193326Sed  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8864193326Sed    CXXCatchStmt *Handler = TryBlock->getHandler(I);
8865193326Sed    SearchForReturnInStmt(*this, Handler);
8866193326Sed  }
8867193326Sed}
8868193326Sed
8869198092Srdivackybool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
8870193326Sed                                             const CXXMethodDecl *Old) {
8871198092Srdivacky  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8872198092Srdivacky  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
8873193326Sed
8874203955Srdivacky  if (Context.hasSameType(NewTy, OldTy) ||
8875203955Srdivacky      NewTy->isDependentType() || OldTy->isDependentType())
8876193326Sed    return false;
8877198092Srdivacky
8878193326Sed  // Check if the return types are covariant
8879193326Sed  QualType NewClassTy, OldClassTy;
8880198092Srdivacky
8881193326Sed  /// Both types must be pointers or references to classes.
8882202879Srdivacky  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8883202879Srdivacky    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
8884193326Sed      NewClassTy = NewPT->getPointeeType();
8885193326Sed      OldClassTy = OldPT->getPointeeType();
8886193326Sed    }
8887202879Srdivacky  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8888202879Srdivacky    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8889202879Srdivacky      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8890202879Srdivacky        NewClassTy = NewRT->getPointeeType();
8891202879Srdivacky        OldClassTy = OldRT->getPointeeType();
8892202879Srdivacky      }
8893193326Sed    }
8894193326Sed  }
8895198092Srdivacky
8896193326Sed  // The return types aren't either both pointers or references to a class type.
8897193326Sed  if (NewClassTy.isNull()) {
8898198092Srdivacky    Diag(New->getLocation(),
8899193326Sed         diag::err_different_return_type_for_overriding_virtual_function)
8900193326Sed      << New->getDeclName() << NewTy << OldTy;
8901193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8902198092Srdivacky
8903193326Sed    return true;
8904193326Sed  }
8905193326Sed
8906201361Srdivacky  // C++ [class.virtual]p6:
8907201361Srdivacky  //   If the return type of D::f differs from the return type of B::f, the
8908201361Srdivacky  //   class type in the return type of D::f shall be complete at the point of
8909201361Srdivacky  //   declaration of D::f or shall be the class type D.
8910201361Srdivacky  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8911201361Srdivacky    if (!RT->isBeingDefined() &&
8912201361Srdivacky        RequireCompleteType(New->getLocation(), NewClassTy,
8913201361Srdivacky                            PDiag(diag::err_covariant_return_incomplete)
8914201361Srdivacky                              << New->getDeclName()))
8915201361Srdivacky    return true;
8916201361Srdivacky  }
8917201361Srdivacky
8918199482Srdivacky  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
8919193326Sed    // Check if the new class derives from the old class.
8920193326Sed    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8921193326Sed      Diag(New->getLocation(),
8922193326Sed           diag::err_covariant_return_not_derived)
8923193326Sed      << New->getDeclName() << NewTy << OldTy;
8924193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8925193326Sed      return true;
8926193326Sed    }
8927198092Srdivacky
8928193326Sed    // Check if we the conversion from derived to base is valid.
8929205219Srdivacky    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
8930207619Srdivacky                    diag::err_covariant_return_inaccessible_base,
8931207619Srdivacky                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
8932207619Srdivacky                    // FIXME: Should this point to the return type?
8933207619Srdivacky                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
8934218893Sdim      // FIXME: this note won't trigger for delayed access control
8935218893Sdim      // diagnostics, and it's impossible to get an undelayed error
8936218893Sdim      // here from access control during the original parse because
8937218893Sdim      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
8938193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8939193326Sed      return true;
8940193326Sed    }
8941193326Sed  }
8942198092Srdivacky
8943193326Sed  // The qualifiers of the return types must be the same.
8944202879Srdivacky  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
8945193326Sed    Diag(New->getLocation(),
8946193326Sed         diag::err_covariant_return_type_different_qualifications)
8947193326Sed    << New->getDeclName() << NewTy << OldTy;
8948193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8949193326Sed    return true;
8950193326Sed  };
8951193326Sed
8952198092Srdivacky
8953193326Sed  // The new class type must have the same or less qualifiers as the old type.
8954193326Sed  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8955193326Sed    Diag(New->getLocation(),
8956193326Sed         diag::err_covariant_return_type_class_type_more_qualified)
8957193326Sed    << New->getDeclName() << NewTy << OldTy;
8958193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8959193326Sed    return true;
8960193326Sed  };
8961198092Srdivacky
8962193326Sed  return false;
8963193326Sed}
8964194613Sed
8965200583Srdivacky/// \brief Mark the given method pure.
8966200583Srdivacky///
8967200583Srdivacky/// \param Method the method to be marked pure.
8968200583Srdivacky///
8969200583Srdivacky/// \param InitRange the source range that covers the "0" initializer.
8970200583Srdivackybool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
8971221345Sdim  SourceLocation EndLoc = InitRange.getEnd();
8972221345Sdim  if (EndLoc.isValid())
8973221345Sdim    Method->setRangeEnd(EndLoc);
8974221345Sdim
8975200583Srdivacky  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8976200583Srdivacky    Method->setPure();
8977200583Srdivacky    return false;
8978221345Sdim  }
8979200583Srdivacky
8980200583Srdivacky  if (!Method->isInvalidDecl())
8981200583Srdivacky    Diag(Method->getLocation(), diag::err_non_virtual_pure)
8982200583Srdivacky      << Method->getDeclName() << InitRange;
8983200583Srdivacky  return true;
8984200583Srdivacky}
8985200583Srdivacky
8986201361Srdivacky/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8987201361Srdivacky/// an initializer for the out-of-line declaration 'Dcl'.  The scope
8988201361Srdivacky/// is a fresh scope pushed for just this purpose.
8989201361Srdivacky///
8990194613Sed/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8991194613Sed/// static data member of class X, names should be looked up in the scope of
8992194613Sed/// class X.
8993212904Sdimvoid Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
8994201361Srdivacky  // If there is no declaration, there was an error parsing it.
8995221345Sdim  if (D == 0 || D->isInvalidDecl()) return;
8996194613Sed
8997201361Srdivacky  // We should only get called for declarations with scope specifiers, like:
8998201361Srdivacky  //   int foo::bar;
8999201361Srdivacky  assert(D->isOutOfLine());
9000194613Sed  EnterDeclaratorContext(S, D->getDeclContext());
9001194613Sed}
9002194613Sed
9003194613Sed/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
9004212904Sdim/// initializer for the out-of-line declaration 'D'.
9005212904Sdimvoid Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
9006201361Srdivacky  // If there is no declaration, there was an error parsing it.
9007221345Sdim  if (D == 0 || D->isInvalidDecl()) return;
9008194613Sed
9009201361Srdivacky  assert(D->isOutOfLine());
9010194613Sed  ExitDeclaratorContext(S);
9011194613Sed}
9012199990Srdivacky
9013199990Srdivacky/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9014199990Srdivacky/// C++ if/switch/while/for statement.
9015199990Srdivacky/// e.g: "if (int x = f()) {...}"
9016212904SdimDeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
9017199990Srdivacky  // C++ 6.4p2:
9018199990Srdivacky  // The declarator shall not specify a function or an array.
9019199990Srdivacky  // The type-specifier-seq shall not contain typedef and shall not declare a
9020199990Srdivacky  // new class or enumeration.
9021199990Srdivacky  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9022199990Srdivacky         "Parser allowed 'typedef' as storage class of condition decl.");
9023199990Srdivacky
9024199990Srdivacky  TagDecl *OwnedTag = 0;
9025210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9026210299Sed  QualType Ty = TInfo->getType();
9027199990Srdivacky
9028199990Srdivacky  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9029199990Srdivacky                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9030199990Srdivacky                              // would be created and CXXConditionDeclExpr wants a VarDecl.
9031199990Srdivacky    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9032199990Srdivacky      << D.getSourceRange();
9033199990Srdivacky    return DeclResult();
9034199990Srdivacky  } else if (OwnedTag && OwnedTag->isDefinition()) {
9035199990Srdivacky    // The type-specifier-seq shall not declare a new class or enumeration.
9036199990Srdivacky    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9037199990Srdivacky  }
9038199990Srdivacky
9039212904Sdim  Decl *Dcl = ActOnDeclarator(S, D);
9040199990Srdivacky  if (!Dcl)
9041199990Srdivacky    return DeclResult();
9042199990Srdivacky
9043199990Srdivacky  return Dcl;
9044199990Srdivacky}
9045200583Srdivacky
9046208600Srdivackyvoid Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9047208600Srdivacky                          bool DefinitionRequired) {
9048208600Srdivacky  // Ignore any vtable uses in unevaluated operands or for classes that do
9049208600Srdivacky  // not have a vtable.
9050208600Srdivacky  if (!Class->isDynamicClass() || Class->isDependentContext() ||
9051208600Srdivacky      CurContext->isDependentContext() ||
9052208600Srdivacky      ExprEvalContexts.back().Context == Unevaluated)
9053208600Srdivacky    return;
9054204643Srdivacky
9055208600Srdivacky  // Try to insert this class into the map.
9056208600Srdivacky  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9057208600Srdivacky  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9058208600Srdivacky    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9059208600Srdivacky  if (!Pos.second) {
9060208600Srdivacky    // If we already had an entry, check to see if we are promoting this vtable
9061208600Srdivacky    // to required a definition. If so, we need to reappend to the VTableUses
9062208600Srdivacky    // list, since we may have already processed the first entry.
9063208600Srdivacky    if (DefinitionRequired && !Pos.first->second) {
9064208600Srdivacky      Pos.first->second = true;
9065208600Srdivacky    } else {
9066208600Srdivacky      // Otherwise, we can early exit.
9067208600Srdivacky      return;
9068208600Srdivacky    }
9069208600Srdivacky  }
9070204643Srdivacky
9071208600Srdivacky  // Local classes need to have their virtual members marked
9072208600Srdivacky  // immediately. For all other classes, we mark their virtual members
9073208600Srdivacky  // at the end of the translation unit.
9074208600Srdivacky  if (Class->isLocalClass())
9075208600Srdivacky    MarkVirtualMembersReferenced(Loc, Class);
9076208600Srdivacky  else
9077208600Srdivacky    VTableUses.push_back(std::make_pair(Class, Loc));
9078208600Srdivacky}
9079204643Srdivacky
9080208600Srdivackybool Sema::DefineUsedVTables() {
9081208600Srdivacky  if (VTableUses.empty())
9082204643Srdivacky    return false;
9083218893Sdim
9084208600Srdivacky  // Note: The VTableUses vector could grow as a result of marking
9085208600Srdivacky  // the members of a class as "used", so we check the size each
9086208600Srdivacky  // time through the loop and prefer indices (with are stable) to
9087208600Srdivacky  // iterators (which are not).
9088221345Sdim  bool DefinedAnything = false;
9089208600Srdivacky  for (unsigned I = 0; I != VTableUses.size(); ++I) {
9090208600Srdivacky    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
9091208600Srdivacky    if (!Class)
9092208600Srdivacky      continue;
9093204643Srdivacky
9094208600Srdivacky    SourceLocation Loc = VTableUses[I].second;
9095204643Srdivacky
9096208600Srdivacky    // If this class has a key function, but that key function is
9097208600Srdivacky    // defined in another translation unit, we don't need to emit the
9098208600Srdivacky    // vtable even though we're using it.
9099208600Srdivacky    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
9100210299Sed    if (KeyFunction && !KeyFunction->hasBody()) {
9101208600Srdivacky      switch (KeyFunction->getTemplateSpecializationKind()) {
9102208600Srdivacky      case TSK_Undeclared:
9103208600Srdivacky      case TSK_ExplicitSpecialization:
9104208600Srdivacky      case TSK_ExplicitInstantiationDeclaration:
9105208600Srdivacky        // The key function is in another translation unit.
9106208600Srdivacky        continue;
9107204643Srdivacky
9108208600Srdivacky      case TSK_ExplicitInstantiationDefinition:
9109208600Srdivacky      case TSK_ImplicitInstantiation:
9110208600Srdivacky        // We will be instantiating the key function.
9111208600Srdivacky        break;
9112208600Srdivacky      }
9113208600Srdivacky    } else if (!KeyFunction) {
9114208600Srdivacky      // If we have a class with no key function that is the subject
9115208600Srdivacky      // of an explicit instantiation declaration, suppress the
9116208600Srdivacky      // vtable; it will live with the explicit instantiation
9117208600Srdivacky      // definition.
9118208600Srdivacky      bool IsExplicitInstantiationDeclaration
9119208600Srdivacky        = Class->getTemplateSpecializationKind()
9120208600Srdivacky                                      == TSK_ExplicitInstantiationDeclaration;
9121208600Srdivacky      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9122208600Srdivacky                                 REnd = Class->redecls_end();
9123208600Srdivacky           R != REnd; ++R) {
9124208600Srdivacky        TemplateSpecializationKind TSK
9125208600Srdivacky          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9126208600Srdivacky        if (TSK == TSK_ExplicitInstantiationDeclaration)
9127208600Srdivacky          IsExplicitInstantiationDeclaration = true;
9128208600Srdivacky        else if (TSK == TSK_ExplicitInstantiationDefinition) {
9129208600Srdivacky          IsExplicitInstantiationDeclaration = false;
9130208600Srdivacky          break;
9131208600Srdivacky        }
9132208600Srdivacky      }
9133204643Srdivacky
9134208600Srdivacky      if (IsExplicitInstantiationDeclaration)
9135208600Srdivacky        continue;
9136208600Srdivacky    }
9137204643Srdivacky
9138208600Srdivacky    // Mark all of the virtual members of this class as referenced, so
9139208600Srdivacky    // that we can build a vtable. Then, tell the AST consumer that a
9140208600Srdivacky    // vtable for this class is required.
9141221345Sdim    DefinedAnything = true;
9142208600Srdivacky    MarkVirtualMembersReferenced(Loc, Class);
9143208600Srdivacky    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9144208600Srdivacky    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9145204643Srdivacky
9146208600Srdivacky    // Optionally warn if we're emitting a weak vtable.
9147208600Srdivacky    if (Class->getLinkage() == ExternalLinkage &&
9148208600Srdivacky        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
9149210299Sed      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
9150208600Srdivacky        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9151208600Srdivacky    }
9152208600Srdivacky  }
9153208600Srdivacky  VTableUses.clear();
9154204962Srdivacky
9155221345Sdim  return DefinedAnything;
9156200583Srdivacky}
9157200583Srdivacky
9158206084Srdivackyvoid Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9159206084Srdivacky                                        const CXXRecordDecl *RD) {
9160200583Srdivacky  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9161200583Srdivacky       e = RD->method_end(); i != e; ++i) {
9162200583Srdivacky    CXXMethodDecl *MD = *i;
9163200583Srdivacky
9164200583Srdivacky    // C++ [basic.def.odr]p2:
9165200583Srdivacky    //   [...] A virtual member function is used if it is not pure. [...]
9166200583Srdivacky    if (MD->isVirtual() && !MD->isPure())
9167200583Srdivacky      MarkDeclarationReferenced(Loc, MD);
9168200583Srdivacky  }
9169206084Srdivacky
9170206084Srdivacky  // Only classes that have virtual bases need a VTT.
9171206084Srdivacky  if (RD->getNumVBases() == 0)
9172206084Srdivacky    return;
9173206084Srdivacky
9174206084Srdivacky  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9175206084Srdivacky           e = RD->bases_end(); i != e; ++i) {
9176206084Srdivacky    const CXXRecordDecl *Base =
9177206084Srdivacky        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
9178206084Srdivacky    if (Base->getNumVBases() == 0)
9179206084Srdivacky      continue;
9180206084Srdivacky    MarkVirtualMembersReferenced(Loc, Base);
9181206084Srdivacky  }
9182200583Srdivacky}
9183207619Srdivacky
9184207619Srdivacky/// SetIvarInitializers - This routine builds initialization ASTs for the
9185207619Srdivacky/// Objective-C implementation whose ivars need be initialized.
9186207619Srdivackyvoid Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9187207619Srdivacky  if (!getLangOptions().CPlusPlus)
9188207619Srdivacky    return;
9189212904Sdim  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
9190207619Srdivacky    llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9191207619Srdivacky    CollectIvarsToConstructOrDestruct(OID, ivars);
9192207619Srdivacky    if (ivars.empty())
9193207619Srdivacky      return;
9194218893Sdim    llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
9195207619Srdivacky    for (unsigned i = 0; i < ivars.size(); i++) {
9196207619Srdivacky      FieldDecl *Field = ivars[i];
9197208600Srdivacky      if (Field->isInvalidDecl())
9198208600Srdivacky        continue;
9199208600Srdivacky
9200218893Sdim      CXXCtorInitializer *Member;
9201207619Srdivacky      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9202207619Srdivacky      InitializationKind InitKind =
9203207619Srdivacky        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9204207619Srdivacky
9205207619Srdivacky      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
9206212904Sdim      ExprResult MemberInit =
9207212904Sdim        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
9208218893Sdim      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
9209207619Srdivacky      // Note, MemberInit could actually come back empty if no initialization
9210207619Srdivacky      // is required (e.g., because it would call a trivial default constructor)
9211207619Srdivacky      if (!MemberInit.get() || MemberInit.isInvalid())
9212207619Srdivacky        continue;
9213218893Sdim
9214207619Srdivacky      Member =
9215218893Sdim        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9216218893Sdim                                         SourceLocation(),
9217218893Sdim                                         MemberInit.takeAs<Expr>(),
9218218893Sdim                                         SourceLocation());
9219207619Srdivacky      AllToInit.push_back(Member);
9220208600Srdivacky
9221208600Srdivacky      // Be sure that the destructor is accessible and is marked as referenced.
9222208600Srdivacky      if (const RecordType *RecordTy
9223208600Srdivacky                  = Context.getBaseElementType(Field->getType())
9224208600Srdivacky                                                        ->getAs<RecordType>()) {
9225208600Srdivacky                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
9226210299Sed        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
9227208600Srdivacky          MarkDeclarationReferenced(Field->getLocation(), Destructor);
9228208600Srdivacky          CheckDestructorAccess(Field->getLocation(), Destructor,
9229208600Srdivacky                            PDiag(diag::err_access_dtor_ivar)
9230208600Srdivacky                              << Context.getBaseElementType(Field->getType()));
9231208600Srdivacky        }
9232208600Srdivacky      }
9233207619Srdivacky    }
9234207619Srdivacky    ObjCImplementation->setIvarInitializers(Context,
9235207619Srdivacky                                            AllToInit.data(), AllToInit.size());
9236207619Srdivacky  }
9237207619Srdivacky}
9238223017Sdim
9239223017Sdimstatic
9240223017Sdimvoid DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9241223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9242223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9243223017Sdim                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9244223017Sdim                           Sema &S) {
9245223017Sdim  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9246223017Sdim                                                   CE = Current.end();
9247223017Sdim  if (Ctor->isInvalidDecl())
9248223017Sdim    return;
9249223017Sdim
9250223017Sdim  const FunctionDecl *FNTarget = 0;
9251223017Sdim  CXXConstructorDecl *Target;
9252223017Sdim
9253223017Sdim  // We ignore the result here since if we don't have a body, Target will be
9254223017Sdim  // null below.
9255223017Sdim  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9256223017Sdim  Target
9257223017Sdim= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9258223017Sdim
9259223017Sdim  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9260223017Sdim                     // Avoid dereferencing a null pointer here.
9261223017Sdim                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9262223017Sdim
9263223017Sdim  if (!Current.insert(Canonical))
9264223017Sdim    return;
9265223017Sdim
9266223017Sdim  // We know that beyond here, we aren't chaining into a cycle.
9267223017Sdim  if (!Target || !Target->isDelegatingConstructor() ||
9268223017Sdim      Target->isInvalidDecl() || Valid.count(TCanonical)) {
9269223017Sdim    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9270223017Sdim      Valid.insert(*CI);
9271223017Sdim    Current.clear();
9272223017Sdim  // We've hit a cycle.
9273223017Sdim  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9274223017Sdim             Current.count(TCanonical)) {
9275223017Sdim    // If we haven't diagnosed this cycle yet, do so now.
9276223017Sdim    if (!Invalid.count(TCanonical)) {
9277223017Sdim      S.Diag((*Ctor->init_begin())->getSourceLocation(),
9278223017Sdim             diag::warn_delegating_ctor_cycle)
9279223017Sdim        << Ctor;
9280223017Sdim
9281223017Sdim      // Don't add a note for a function delegating directo to itself.
9282223017Sdim      if (TCanonical != Canonical)
9283223017Sdim        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9284223017Sdim
9285223017Sdim      CXXConstructorDecl *C = Target;
9286223017Sdim      while (C->getCanonicalDecl() != Canonical) {
9287223017Sdim        (void)C->getTargetConstructor()->hasBody(FNTarget);
9288223017Sdim        assert(FNTarget && "Ctor cycle through bodiless function");
9289223017Sdim
9290223017Sdim        C
9291223017Sdim       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9292223017Sdim        S.Diag(C->getLocation(), diag::note_which_delegates_to);
9293223017Sdim      }
9294223017Sdim    }
9295223017Sdim
9296223017Sdim    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9297223017Sdim      Invalid.insert(*CI);
9298223017Sdim    Current.clear();
9299223017Sdim  } else {
9300223017Sdim    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9301223017Sdim  }
9302223017Sdim}
9303223017Sdim
9304223017Sdim
9305223017Sdimvoid Sema::CheckDelegatingCtorCycles() {
9306223017Sdim  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9307223017Sdim
9308223017Sdim  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9309223017Sdim                                                   CE = Current.end();
9310223017Sdim
9311223017Sdim  for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
9312223017Sdim         I = DelegatingCtorDecls.begin(),
9313223017Sdim         E = DelegatingCtorDecls.end();
9314223017Sdim       I != E; ++I) {
9315223017Sdim   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
9316223017Sdim  }
9317223017Sdim
9318223017Sdim  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9319223017Sdim    (*CI)->setInvalidDecl();
9320223017Sdim}
9321