SemaDeclCXX.cpp revision 193326
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
14193326Sed#include "Sema.h"
15193326Sed#include "SemaInherit.h"
16193326Sed#include "clang/AST/ASTConsumer.h"
17193326Sed#include "clang/AST/ASTContext.h"
18193326Sed#include "clang/AST/DeclVisitor.h"
19193326Sed#include "clang/AST/TypeOrdering.h"
20193326Sed#include "clang/AST/StmtVisitor.h"
21193326Sed#include "clang/Lex/Preprocessor.h"
22193326Sed#include "clang/Parse/DeclSpec.h"
23193326Sed#include "llvm/ADT/STLExtras.h"
24193326Sed#include "llvm/Support/Compiler.h"
25193326Sed#include <algorithm> // for std::equal
26193326Sed#include <map>
27193326Sed
28193326Sedusing namespace clang;
29193326Sed
30193326Sed//===----------------------------------------------------------------------===//
31193326Sed// CheckDefaultArgumentVisitor
32193326Sed//===----------------------------------------------------------------------===//
33193326Sed
34193326Sednamespace {
35193326Sed  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36193326Sed  /// the default argument of a parameter to determine whether it
37193326Sed  /// contains any ill-formed subexpressions. For example, this will
38193326Sed  /// diagnose the use of local variables or parameters within the
39193326Sed  /// default argument expression.
40193326Sed  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
41193326Sed    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
42193326Sed    Expr *DefaultArg;
43193326Sed    Sema *S;
44193326Sed
45193326Sed  public:
46193326Sed    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47193326Sed      : DefaultArg(defarg), S(s) {}
48193326Sed
49193326Sed    bool VisitExpr(Expr *Node);
50193326Sed    bool VisitDeclRefExpr(DeclRefExpr *DRE);
51193326Sed    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
52193326Sed  };
53193326Sed
54193326Sed  /// VisitExpr - Visit all of the children of this expression.
55193326Sed  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56193326Sed    bool IsInvalid = false;
57193326Sed    for (Stmt::child_iterator I = Node->child_begin(),
58193326Sed         E = Node->child_end(); I != E; ++I)
59193326Sed      IsInvalid |= Visit(*I);
60193326Sed    return IsInvalid;
61193326Sed  }
62193326Sed
63193326Sed  /// VisitDeclRefExpr - Visit a reference to a declaration, to
64193326Sed  /// determine whether this declaration can be used in the default
65193326Sed  /// argument expression.
66193326Sed  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
67193326Sed    NamedDecl *Decl = DRE->getDecl();
68193326Sed    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69193326Sed      // C++ [dcl.fct.default]p9
70193326Sed      //   Default arguments are evaluated each time the function is
71193326Sed      //   called. The order of evaluation of function arguments is
72193326Sed      //   unspecified. Consequently, parameters of a function shall not
73193326Sed      //   be used in default argument expressions, even if they are not
74193326Sed      //   evaluated. Parameters of a function declared before a default
75193326Sed      //   argument expression are in scope and can hide namespace and
76193326Sed      //   class member names.
77193326Sed      return S->Diag(DRE->getSourceRange().getBegin(),
78193326Sed                     diag::err_param_default_argument_references_param)
79193326Sed         << Param->getDeclName() << DefaultArg->getSourceRange();
80193326Sed    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
81193326Sed      // C++ [dcl.fct.default]p7
82193326Sed      //   Local variables shall not be used in default argument
83193326Sed      //   expressions.
84193326Sed      if (VDecl->isBlockVarDecl())
85193326Sed        return S->Diag(DRE->getSourceRange().getBegin(),
86193326Sed                       diag::err_param_default_argument_references_local)
87193326Sed          << VDecl->getDeclName() << DefaultArg->getSourceRange();
88193326Sed    }
89193326Sed
90193326Sed    return false;
91193326Sed  }
92193326Sed
93193326Sed  /// VisitCXXThisExpr - Visit a C++ "this" expression.
94193326Sed  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95193326Sed    // C++ [dcl.fct.default]p8:
96193326Sed    //   The keyword this shall not be used in a default argument of a
97193326Sed    //   member function.
98193326Sed    return S->Diag(ThisE->getSourceRange().getBegin(),
99193326Sed                   diag::err_param_default_argument_references_this)
100193326Sed               << ThisE->getSourceRange();
101193326Sed  }
102193326Sed}
103193326Sed
104193326Sed/// ActOnParamDefaultArgument - Check whether the default argument
105193326Sed/// provided for a function parameter is well-formed. If so, attach it
106193326Sed/// to the parameter declaration.
107193326Sedvoid
108193326SedSema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
109193326Sed                                ExprArg defarg) {
110193326Sed  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
111193326Sed  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
112193326Sed  QualType ParamType = Param->getType();
113193326Sed
114193326Sed  // Default arguments are only permitted in C++
115193326Sed  if (!getLangOptions().CPlusPlus) {
116193326Sed    Diag(EqualLoc, diag::err_param_default_argument)
117193326Sed      << DefaultArg->getSourceRange();
118193326Sed    Param->setInvalidDecl();
119193326Sed    return;
120193326Sed  }
121193326Sed
122193326Sed  // C++ [dcl.fct.default]p5
123193326Sed  //   A default argument expression is implicitly converted (clause
124193326Sed  //   4) to the parameter type. The default argument expression has
125193326Sed  //   the same semantic constraints as the initializer expression in
126193326Sed  //   a declaration of a variable of the parameter type, using the
127193326Sed  //   copy-initialization semantics (8.5).
128193326Sed  Expr *DefaultArgPtr = DefaultArg.get();
129193326Sed  bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
130193326Sed                                                 EqualLoc,
131193326Sed                                                 Param->getDeclName(),
132193326Sed                                                 /*DirectInit=*/false);
133193326Sed  if (DefaultArgPtr != DefaultArg.get()) {
134193326Sed    DefaultArg.take();
135193326Sed    DefaultArg.reset(DefaultArgPtr);
136193326Sed  }
137193326Sed  if (DefaultInitFailed) {
138193326Sed    return;
139193326Sed  }
140193326Sed
141193326Sed  // Check that the default argument is well-formed
142193326Sed  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
143193326Sed  if (DefaultArgChecker.Visit(DefaultArg.get())) {
144193326Sed    Param->setInvalidDecl();
145193326Sed    return;
146193326Sed  }
147193326Sed
148193326Sed  // Okay: add the default argument to the parameter
149193326Sed  Param->setDefaultArg(DefaultArg.take());
150193326Sed}
151193326Sed
152193326Sed/// ActOnParamUnparsedDefaultArgument - We've seen a default
153193326Sed/// argument for a function parameter, but we can't parse it yet
154193326Sed/// because we're inside a class definition. Note that this default
155193326Sed/// argument will be parsed later.
156193326Sedvoid Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
157193326Sed                                             SourceLocation EqualLoc) {
158193326Sed  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
159193326Sed  if (Param)
160193326Sed    Param->setUnparsedDefaultArg();
161193326Sed}
162193326Sed
163193326Sed/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
164193326Sed/// the default argument for the parameter param failed.
165193326Sedvoid Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
166193326Sed  cast<ParmVarDecl>(param.getAs<Decl>())->setInvalidDecl();
167193326Sed}
168193326Sed
169193326Sed/// CheckExtraCXXDefaultArguments - Check for any extra default
170193326Sed/// arguments in the declarator, which is not a function declaration
171193326Sed/// or definition and therefore is not permitted to have default
172193326Sed/// arguments. This routine should be invoked for every declarator
173193326Sed/// that is not a function declaration or definition.
174193326Sedvoid Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
175193326Sed  // C++ [dcl.fct.default]p3
176193326Sed  //   A default argument expression shall be specified only in the
177193326Sed  //   parameter-declaration-clause of a function declaration or in a
178193326Sed  //   template-parameter (14.1). It shall not be specified for a
179193326Sed  //   parameter pack. If it is specified in a
180193326Sed  //   parameter-declaration-clause, it shall not occur within a
181193326Sed  //   declarator or abstract-declarator of a parameter-declaration.
182193326Sed  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
183193326Sed    DeclaratorChunk &chunk = D.getTypeObject(i);
184193326Sed    if (chunk.Kind == DeclaratorChunk::Function) {
185193326Sed      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
186193326Sed        ParmVarDecl *Param =
187193326Sed          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
188193326Sed        if (Param->hasUnparsedDefaultArg()) {
189193326Sed          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
190193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
191193326Sed            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
192193326Sed          delete Toks;
193193326Sed          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
194193326Sed        } else if (Param->getDefaultArg()) {
195193326Sed          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
196193326Sed            << Param->getDefaultArg()->getSourceRange();
197193326Sed          Param->setDefaultArg(0);
198193326Sed        }
199193326Sed      }
200193326Sed    }
201193326Sed  }
202193326Sed}
203193326Sed
204193326Sed// MergeCXXFunctionDecl - Merge two declarations of the same C++
205193326Sed// function, once we already know that they have the same
206193326Sed// type. Subroutine of MergeFunctionDecl. Returns true if there was an
207193326Sed// error, false otherwise.
208193326Sedbool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
209193326Sed  bool Invalid = false;
210193326Sed
211193326Sed  // C++ [dcl.fct.default]p4:
212193326Sed  //
213193326Sed  //   For non-template functions, default arguments can be added in
214193326Sed  //   later declarations of a function in the same
215193326Sed  //   scope. Declarations in different scopes have completely
216193326Sed  //   distinct sets of default arguments. That is, declarations in
217193326Sed  //   inner scopes do not acquire default arguments from
218193326Sed  //   declarations in outer scopes, and vice versa. In a given
219193326Sed  //   function declaration, all parameters subsequent to a
220193326Sed  //   parameter with a default argument shall have default
221193326Sed  //   arguments supplied in this or previous declarations. A
222193326Sed  //   default argument shall not be redefined by a later
223193326Sed  //   declaration (not even to the same value).
224193326Sed  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
225193326Sed    ParmVarDecl *OldParam = Old->getParamDecl(p);
226193326Sed    ParmVarDecl *NewParam = New->getParamDecl(p);
227193326Sed
228193326Sed    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
229193326Sed      Diag(NewParam->getLocation(),
230193326Sed           diag::err_param_default_argument_redefinition)
231193326Sed        << NewParam->getDefaultArg()->getSourceRange();
232193326Sed      Diag(OldParam->getLocation(), diag::note_previous_definition);
233193326Sed      Invalid = true;
234193326Sed    } else if (OldParam->getDefaultArg()) {
235193326Sed      // Merge the old default argument into the new parameter
236193326Sed      NewParam->setDefaultArg(OldParam->getDefaultArg());
237193326Sed    }
238193326Sed  }
239193326Sed
240193326Sed  return Invalid;
241193326Sed}
242193326Sed
243193326Sed/// CheckCXXDefaultArguments - Verify that the default arguments for a
244193326Sed/// function declaration are well-formed according to C++
245193326Sed/// [dcl.fct.default].
246193326Sedvoid Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
247193326Sed  unsigned NumParams = FD->getNumParams();
248193326Sed  unsigned p;
249193326Sed
250193326Sed  // Find first parameter with a default argument
251193326Sed  for (p = 0; p < NumParams; ++p) {
252193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
253193326Sed    if (Param->getDefaultArg())
254193326Sed      break;
255193326Sed  }
256193326Sed
257193326Sed  // C++ [dcl.fct.default]p4:
258193326Sed  //   In a given function declaration, all parameters
259193326Sed  //   subsequent to a parameter with a default argument shall
260193326Sed  //   have default arguments supplied in this or previous
261193326Sed  //   declarations. A default argument shall not be redefined
262193326Sed  //   by a later declaration (not even to the same value).
263193326Sed  unsigned LastMissingDefaultArg = 0;
264193326Sed  for(; p < NumParams; ++p) {
265193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
266193326Sed    if (!Param->getDefaultArg()) {
267193326Sed      if (Param->isInvalidDecl())
268193326Sed        /* We already complained about this parameter. */;
269193326Sed      else if (Param->getIdentifier())
270193326Sed        Diag(Param->getLocation(),
271193326Sed             diag::err_param_default_argument_missing_name)
272193326Sed          << Param->getIdentifier();
273193326Sed      else
274193326Sed        Diag(Param->getLocation(),
275193326Sed             diag::err_param_default_argument_missing);
276193326Sed
277193326Sed      LastMissingDefaultArg = p;
278193326Sed    }
279193326Sed  }
280193326Sed
281193326Sed  if (LastMissingDefaultArg > 0) {
282193326Sed    // Some default arguments were missing. Clear out all of the
283193326Sed    // default arguments up to (and including) the last missing
284193326Sed    // default argument, so that we leave the function parameters
285193326Sed    // in a semantically valid state.
286193326Sed    for (p = 0; p <= LastMissingDefaultArg; ++p) {
287193326Sed      ParmVarDecl *Param = FD->getParamDecl(p);
288193326Sed      if (Param->getDefaultArg()) {
289193326Sed        if (!Param->hasUnparsedDefaultArg())
290193326Sed          Param->getDefaultArg()->Destroy(Context);
291193326Sed        Param->setDefaultArg(0);
292193326Sed      }
293193326Sed    }
294193326Sed  }
295193326Sed}
296193326Sed
297193326Sed/// isCurrentClassName - Determine whether the identifier II is the
298193326Sed/// name of the class type currently being defined. In the case of
299193326Sed/// nested classes, this will only return true if II is the name of
300193326Sed/// the innermost class.
301193326Sedbool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
302193326Sed                              const CXXScopeSpec *SS) {
303193326Sed  CXXRecordDecl *CurDecl;
304193326Sed  if (SS && SS->isSet() && !SS->isInvalid()) {
305193326Sed    DeclContext *DC = computeDeclContext(*SS);
306193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
307193326Sed  } else
308193326Sed    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
309193326Sed
310193326Sed  if (CurDecl)
311193326Sed    return &II == CurDecl->getIdentifier();
312193326Sed  else
313193326Sed    return false;
314193326Sed}
315193326Sed
316193326Sed/// \brief Check the validity of a C++ base class specifier.
317193326Sed///
318193326Sed/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
319193326Sed/// and returns NULL otherwise.
320193326SedCXXBaseSpecifier *
321193326SedSema::CheckBaseSpecifier(CXXRecordDecl *Class,
322193326Sed                         SourceRange SpecifierRange,
323193326Sed                         bool Virtual, AccessSpecifier Access,
324193326Sed                         QualType BaseType,
325193326Sed                         SourceLocation BaseLoc) {
326193326Sed  // C++ [class.union]p1:
327193326Sed  //   A union shall not have base classes.
328193326Sed  if (Class->isUnion()) {
329193326Sed    Diag(Class->getLocation(), diag::err_base_clause_on_union)
330193326Sed      << SpecifierRange;
331193326Sed    return 0;
332193326Sed  }
333193326Sed
334193326Sed  if (BaseType->isDependentType())
335193326Sed    return new CXXBaseSpecifier(SpecifierRange, Virtual,
336193326Sed                                Class->getTagKind() == RecordDecl::TK_class,
337193326Sed                                Access, BaseType);
338193326Sed
339193326Sed  // Base specifiers must be record types.
340193326Sed  if (!BaseType->isRecordType()) {
341193326Sed    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
342193326Sed    return 0;
343193326Sed  }
344193326Sed
345193326Sed  // C++ [class.union]p1:
346193326Sed  //   A union shall not be used as a base class.
347193326Sed  if (BaseType->isUnionType()) {
348193326Sed    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
349193326Sed    return 0;
350193326Sed  }
351193326Sed
352193326Sed  // C++ [class.derived]p2:
353193326Sed  //   The class-name in a base-specifier shall not be an incompletely
354193326Sed  //   defined class.
355193326Sed  if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
356193326Sed                          SpecifierRange))
357193326Sed    return 0;
358193326Sed
359193326Sed  // If the base class is polymorphic, the new one is, too.
360193326Sed  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
361193326Sed  assert(BaseDecl && "Record type has no declaration");
362193326Sed  BaseDecl = BaseDecl->getDefinition(Context);
363193326Sed  assert(BaseDecl && "Base type is not incomplete, but has no definition");
364193326Sed  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
365193326Sed    Class->setPolymorphic(true);
366193326Sed
367193326Sed  // C++ [dcl.init.aggr]p1:
368193326Sed  //   An aggregate is [...] a class with [...] no base classes [...].
369193326Sed  Class->setAggregate(false);
370193326Sed  Class->setPOD(false);
371193326Sed
372193326Sed  if (Virtual) {
373193326Sed    // C++ [class.ctor]p5:
374193326Sed    //   A constructor is trivial if its class has no virtual base classes.
375193326Sed    Class->setHasTrivialConstructor(false);
376193326Sed  } else {
377193326Sed    // C++ [class.ctor]p5:
378193326Sed    //   A constructor is trivial if all the direct base classes of its
379193326Sed    //   class have trivial constructors.
380193326Sed    Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
381193326Sed                                    hasTrivialConstructor());
382193326Sed  }
383193326Sed
384193326Sed  // C++ [class.ctor]p3:
385193326Sed  //   A destructor is trivial if all the direct base classes of its class
386193326Sed  //   have trivial destructors.
387193326Sed  Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
388193326Sed                                 hasTrivialDestructor());
389193326Sed
390193326Sed  // Create the base specifier.
391193326Sed  // FIXME: Allocate via ASTContext?
392193326Sed  return new CXXBaseSpecifier(SpecifierRange, Virtual,
393193326Sed                              Class->getTagKind() == RecordDecl::TK_class,
394193326Sed                              Access, BaseType);
395193326Sed}
396193326Sed
397193326Sed/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
398193326Sed/// one entry in the base class list of a class specifier, for
399193326Sed/// example:
400193326Sed///    class foo : public bar, virtual private baz {
401193326Sed/// 'public bar' and 'virtual private baz' are each base-specifiers.
402193326SedSema::BaseResult
403193326SedSema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
404193326Sed                         bool Virtual, AccessSpecifier Access,
405193326Sed                         TypeTy *basetype, SourceLocation BaseLoc) {
406193326Sed  AdjustDeclIfTemplate(classdecl);
407193326Sed  CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
408193326Sed  QualType BaseType = QualType::getFromOpaquePtr(basetype);
409193326Sed  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
410193326Sed                                                      Virtual, Access,
411193326Sed                                                      BaseType, BaseLoc))
412193326Sed    return BaseSpec;
413193326Sed
414193326Sed  return true;
415193326Sed}
416193326Sed
417193326Sed/// \brief Performs the actual work of attaching the given base class
418193326Sed/// specifiers to a C++ class.
419193326Sedbool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
420193326Sed                                unsigned NumBases) {
421193326Sed if (NumBases == 0)
422193326Sed    return false;
423193326Sed
424193326Sed  // Used to keep track of which base types we have already seen, so
425193326Sed  // that we can properly diagnose redundant direct base types. Note
426193326Sed  // that the key is always the unqualified canonical type of the base
427193326Sed  // class.
428193326Sed  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
429193326Sed
430193326Sed  // Copy non-redundant base specifiers into permanent storage.
431193326Sed  unsigned NumGoodBases = 0;
432193326Sed  bool Invalid = false;
433193326Sed  for (unsigned idx = 0; idx < NumBases; ++idx) {
434193326Sed    QualType NewBaseType
435193326Sed      = Context.getCanonicalType(Bases[idx]->getType());
436193326Sed    NewBaseType = NewBaseType.getUnqualifiedType();
437193326Sed
438193326Sed    if (KnownBaseTypes[NewBaseType]) {
439193326Sed      // C++ [class.mi]p3:
440193326Sed      //   A class shall not be specified as a direct base class of a
441193326Sed      //   derived class more than once.
442193326Sed      Diag(Bases[idx]->getSourceRange().getBegin(),
443193326Sed           diag::err_duplicate_base_class)
444193326Sed        << KnownBaseTypes[NewBaseType]->getType()
445193326Sed        << Bases[idx]->getSourceRange();
446193326Sed
447193326Sed      // Delete the duplicate base class specifier; we're going to
448193326Sed      // overwrite its pointer later.
449193326Sed      delete Bases[idx];
450193326Sed
451193326Sed      Invalid = true;
452193326Sed    } else {
453193326Sed      // Okay, add this new base class.
454193326Sed      KnownBaseTypes[NewBaseType] = Bases[idx];
455193326Sed      Bases[NumGoodBases++] = Bases[idx];
456193326Sed    }
457193326Sed  }
458193326Sed
459193326Sed  // Attach the remaining base class specifiers to the derived class.
460193326Sed  Class->setBases(Bases, NumGoodBases);
461193326Sed
462193326Sed  // Delete the remaining (good) base class specifiers, since their
463193326Sed  // data has been copied into the CXXRecordDecl.
464193326Sed  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
465193326Sed    delete Bases[idx];
466193326Sed
467193326Sed  return Invalid;
468193326Sed}
469193326Sed
470193326Sed/// ActOnBaseSpecifiers - Attach the given base specifiers to the
471193326Sed/// class, after checking whether there are any duplicate base
472193326Sed/// classes.
473193326Sedvoid Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
474193326Sed                               unsigned NumBases) {
475193326Sed  if (!ClassDecl || !Bases || !NumBases)
476193326Sed    return;
477193326Sed
478193326Sed  AdjustDeclIfTemplate(ClassDecl);
479193326Sed  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
480193326Sed                       (CXXBaseSpecifier**)(Bases), NumBases);
481193326Sed}
482193326Sed
483193326Sed//===----------------------------------------------------------------------===//
484193326Sed// C++ class member Handling
485193326Sed//===----------------------------------------------------------------------===//
486193326Sed
487193326Sed/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
488193326Sed/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
489193326Sed/// bitfield width if there is one and 'InitExpr' specifies the initializer if
490193326Sed/// any.
491193326SedSema::DeclPtrTy
492193326SedSema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
493193326Sed                               ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
494193326Sed  const DeclSpec &DS = D.getDeclSpec();
495193326Sed  DeclarationName Name = GetNameForDeclarator(D);
496193326Sed  Expr *BitWidth = static_cast<Expr*>(BW);
497193326Sed  Expr *Init = static_cast<Expr*>(InitExpr);
498193326Sed  SourceLocation Loc = D.getIdentifierLoc();
499193326Sed
500193326Sed  bool isFunc = D.isFunctionDeclarator();
501193326Sed
502193326Sed  // C++ 9.2p6: A member shall not be declared to have automatic storage
503193326Sed  // duration (auto, register) or with the extern storage-class-specifier.
504193326Sed  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
505193326Sed  // data members and cannot be applied to names declared const or static,
506193326Sed  // and cannot be applied to reference members.
507193326Sed  switch (DS.getStorageClassSpec()) {
508193326Sed    case DeclSpec::SCS_unspecified:
509193326Sed    case DeclSpec::SCS_typedef:
510193326Sed    case DeclSpec::SCS_static:
511193326Sed      // FALL THROUGH.
512193326Sed      break;
513193326Sed    case DeclSpec::SCS_mutable:
514193326Sed      if (isFunc) {
515193326Sed        if (DS.getStorageClassSpecLoc().isValid())
516193326Sed          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
517193326Sed        else
518193326Sed          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
519193326Sed
520193326Sed        // FIXME: It would be nicer if the keyword was ignored only for this
521193326Sed        // declarator. Otherwise we could get follow-up errors.
522193326Sed        D.getMutableDeclSpec().ClearStorageClassSpecs();
523193326Sed      } else {
524193326Sed        QualType T = GetTypeForDeclarator(D, S);
525193326Sed        diag::kind err = static_cast<diag::kind>(0);
526193326Sed        if (T->isReferenceType())
527193326Sed          err = diag::err_mutable_reference;
528193326Sed        else if (T.isConstQualified())
529193326Sed          err = diag::err_mutable_const;
530193326Sed        if (err != 0) {
531193326Sed          if (DS.getStorageClassSpecLoc().isValid())
532193326Sed            Diag(DS.getStorageClassSpecLoc(), err);
533193326Sed          else
534193326Sed            Diag(DS.getThreadSpecLoc(), err);
535193326Sed          // FIXME: It would be nicer if the keyword was ignored only for this
536193326Sed          // declarator. Otherwise we could get follow-up errors.
537193326Sed          D.getMutableDeclSpec().ClearStorageClassSpecs();
538193326Sed        }
539193326Sed      }
540193326Sed      break;
541193326Sed    default:
542193326Sed      if (DS.getStorageClassSpecLoc().isValid())
543193326Sed        Diag(DS.getStorageClassSpecLoc(),
544193326Sed             diag::err_storageclass_invalid_for_member);
545193326Sed      else
546193326Sed        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
547193326Sed      D.getMutableDeclSpec().ClearStorageClassSpecs();
548193326Sed  }
549193326Sed
550193326Sed  if (!isFunc &&
551193326Sed      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
552193326Sed      D.getNumTypeObjects() == 0) {
553193326Sed    // Check also for this case:
554193326Sed    //
555193326Sed    // typedef int f();
556193326Sed    // f a;
557193326Sed    //
558193326Sed    QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
559193326Sed    isFunc = TDType->isFunctionType();
560193326Sed  }
561193326Sed
562193326Sed  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
563193326Sed                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
564193326Sed                      !isFunc);
565193326Sed
566193326Sed  Decl *Member;
567193326Sed  if (isInstField) {
568193326Sed    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
569193326Sed                         AS);
570193326Sed    assert(Member && "HandleField never returns null");
571193326Sed  } else {
572193326Sed    Member = ActOnDeclarator(S, D).getAs<Decl>();
573193326Sed    if (!Member) {
574193326Sed      if (BitWidth) DeleteExpr(BitWidth);
575193326Sed      return DeclPtrTy();
576193326Sed    }
577193326Sed
578193326Sed    // Non-instance-fields can't have a bitfield.
579193326Sed    if (BitWidth) {
580193326Sed      if (Member->isInvalidDecl()) {
581193326Sed        // don't emit another diagnostic.
582193326Sed      } else if (isa<VarDecl>(Member)) {
583193326Sed        // C++ 9.6p3: A bit-field shall not be a static member.
584193326Sed        // "static member 'A' cannot be a bit-field"
585193326Sed        Diag(Loc, diag::err_static_not_bitfield)
586193326Sed          << Name << BitWidth->getSourceRange();
587193326Sed      } else if (isa<TypedefDecl>(Member)) {
588193326Sed        // "typedef member 'x' cannot be a bit-field"
589193326Sed        Diag(Loc, diag::err_typedef_not_bitfield)
590193326Sed          << Name << BitWidth->getSourceRange();
591193326Sed      } else {
592193326Sed        // A function typedef ("typedef int f(); f a;").
593193326Sed        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
594193326Sed        Diag(Loc, diag::err_not_integral_type_bitfield)
595193326Sed          << Name << cast<ValueDecl>(Member)->getType()
596193326Sed          << BitWidth->getSourceRange();
597193326Sed      }
598193326Sed
599193326Sed      DeleteExpr(BitWidth);
600193326Sed      BitWidth = 0;
601193326Sed      Member->setInvalidDecl();
602193326Sed    }
603193326Sed
604193326Sed    Member->setAccess(AS);
605193326Sed  }
606193326Sed
607193326Sed  assert((Name || isInstField) && "No identifier for non-field ?");
608193326Sed
609193326Sed  if (Init)
610193326Sed    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
611193326Sed  if (Deleted) // FIXME: Source location is not very good.
612193326Sed    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
613193326Sed
614193326Sed  if (isInstField) {
615193326Sed    FieldCollector->Add(cast<FieldDecl>(Member));
616193326Sed    return DeclPtrTy();
617193326Sed  }
618193326Sed  return DeclPtrTy::make(Member);
619193326Sed}
620193326Sed
621193326Sed/// ActOnMemInitializer - Handle a C++ member initializer.
622193326SedSema::MemInitResult
623193326SedSema::ActOnMemInitializer(DeclPtrTy ConstructorD,
624193326Sed                          Scope *S,
625193326Sed                          IdentifierInfo *MemberOrBase,
626193326Sed                          SourceLocation IdLoc,
627193326Sed                          SourceLocation LParenLoc,
628193326Sed                          ExprTy **Args, unsigned NumArgs,
629193326Sed                          SourceLocation *CommaLocs,
630193326Sed                          SourceLocation RParenLoc) {
631193326Sed  CXXConstructorDecl *Constructor
632193326Sed    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
633193326Sed  if (!Constructor) {
634193326Sed    // The user wrote a constructor initializer on a function that is
635193326Sed    // not a C++ constructor. Ignore the error for now, because we may
636193326Sed    // have more member initializers coming; we'll diagnose it just
637193326Sed    // once in ActOnMemInitializers.
638193326Sed    return true;
639193326Sed  }
640193326Sed
641193326Sed  CXXRecordDecl *ClassDecl = Constructor->getParent();
642193326Sed
643193326Sed  // C++ [class.base.init]p2:
644193326Sed  //   Names in a mem-initializer-id are looked up in the scope of the
645193326Sed  //   constructor���s class and, if not found in that scope, are looked
646193326Sed  //   up in the scope containing the constructor���s
647193326Sed  //   definition. [Note: if the constructor���s class contains a member
648193326Sed  //   with the same name as a direct or virtual base class of the
649193326Sed  //   class, a mem-initializer-id naming the member or base class and
650193326Sed  //   composed of a single identifier refers to the class member. A
651193326Sed  //   mem-initializer-id for the hidden base class may be specified
652193326Sed  //   using a qualified name. ]
653193326Sed  // Look for a member, first.
654193326Sed  FieldDecl *Member = 0;
655193326Sed  DeclContext::lookup_result Result
656193326Sed    = ClassDecl->lookup(Context, MemberOrBase);
657193326Sed  if (Result.first != Result.second)
658193326Sed    Member = dyn_cast<FieldDecl>(*Result.first);
659193326Sed
660193326Sed  // FIXME: Handle members of an anonymous union.
661193326Sed
662193326Sed  if (Member) {
663193326Sed    // FIXME: Perform direct initialization of the member.
664193326Sed    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
665193326Sed  }
666193326Sed
667193326Sed  // It didn't name a member, so see if it names a class.
668193326Sed  TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
669193326Sed  if (!BaseTy)
670193326Sed    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
671193326Sed      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
672193326Sed
673193326Sed  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
674193326Sed  if (!BaseType->isRecordType())
675193326Sed    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
676193326Sed      << BaseType << SourceRange(IdLoc, RParenLoc);
677193326Sed
678193326Sed  // C++ [class.base.init]p2:
679193326Sed  //   [...] Unless the mem-initializer-id names a nonstatic data
680193326Sed  //   member of the constructor���s class or a direct or virtual base
681193326Sed  //   of that class, the mem-initializer is ill-formed. A
682193326Sed  //   mem-initializer-list can initialize a base class using any
683193326Sed  //   name that denotes that base class type.
684193326Sed
685193326Sed  // First, check for a direct base class.
686193326Sed  const CXXBaseSpecifier *DirectBaseSpec = 0;
687193326Sed  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
688193326Sed       Base != ClassDecl->bases_end(); ++Base) {
689193326Sed    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
690193326Sed        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
691193326Sed      // We found a direct base of this type. That's what we're
692193326Sed      // initializing.
693193326Sed      DirectBaseSpec = &*Base;
694193326Sed      break;
695193326Sed    }
696193326Sed  }
697193326Sed
698193326Sed  // Check for a virtual base class.
699193326Sed  // FIXME: We might be able to short-circuit this if we know in advance that
700193326Sed  // there are no virtual bases.
701193326Sed  const CXXBaseSpecifier *VirtualBaseSpec = 0;
702193326Sed  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
703193326Sed    // We haven't found a base yet; search the class hierarchy for a
704193326Sed    // virtual base class.
705193326Sed    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
706193326Sed                    /*DetectVirtual=*/false);
707193326Sed    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
708193326Sed      for (BasePaths::paths_iterator Path = Paths.begin();
709193326Sed           Path != Paths.end(); ++Path) {
710193326Sed        if (Path->back().Base->isVirtual()) {
711193326Sed          VirtualBaseSpec = Path->back().Base;
712193326Sed          break;
713193326Sed        }
714193326Sed      }
715193326Sed    }
716193326Sed  }
717193326Sed
718193326Sed  // C++ [base.class.init]p2:
719193326Sed  //   If a mem-initializer-id is ambiguous because it designates both
720193326Sed  //   a direct non-virtual base class and an inherited virtual base
721193326Sed  //   class, the mem-initializer is ill-formed.
722193326Sed  if (DirectBaseSpec && VirtualBaseSpec)
723193326Sed    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
724193326Sed      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
725193326Sed
726193326Sed  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
727193326Sed}
728193326Sed
729193326Sedvoid Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
730193326Sed                                SourceLocation ColonLoc,
731193326Sed                                MemInitTy **MemInits, unsigned NumMemInits) {
732193326Sed  CXXConstructorDecl *Constructor =
733193326Sed  dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
734193326Sed
735193326Sed  if (!Constructor) {
736193326Sed    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
737193326Sed    return;
738193326Sed  }
739193326Sed}
740193326Sed
741193326Sednamespace {
742193326Sed  /// PureVirtualMethodCollector - traverses a class and its superclasses
743193326Sed  /// and determines if it has any pure virtual methods.
744193326Sed  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
745193326Sed    ASTContext &Context;
746193326Sed
747193326Sed  public:
748193326Sed    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
749193326Sed
750193326Sed  private:
751193326Sed    MethodList Methods;
752193326Sed
753193326Sed    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
754193326Sed
755193326Sed  public:
756193326Sed    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
757193326Sed      : Context(Ctx) {
758193326Sed
759193326Sed      MethodList List;
760193326Sed      Collect(RD, List);
761193326Sed
762193326Sed      // Copy the temporary list to methods, and make sure to ignore any
763193326Sed      // null entries.
764193326Sed      for (size_t i = 0, e = List.size(); i != e; ++i) {
765193326Sed        if (List[i])
766193326Sed          Methods.push_back(List[i]);
767193326Sed      }
768193326Sed    }
769193326Sed
770193326Sed    bool empty() const { return Methods.empty(); }
771193326Sed
772193326Sed    MethodList::const_iterator methods_begin() { return Methods.begin(); }
773193326Sed    MethodList::const_iterator methods_end() { return Methods.end(); }
774193326Sed  };
775193326Sed
776193326Sed  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
777193326Sed                                           MethodList& Methods) {
778193326Sed    // First, collect the pure virtual methods for the base classes.
779193326Sed    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
780193326Sed         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
781193326Sed      if (const RecordType *RT = Base->getType()->getAsRecordType()) {
782193326Sed        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
783193326Sed        if (BaseDecl && BaseDecl->isAbstract())
784193326Sed          Collect(BaseDecl, Methods);
785193326Sed      }
786193326Sed    }
787193326Sed
788193326Sed    // Next, zero out any pure virtual methods that this class overrides.
789193326Sed    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
790193326Sed
791193326Sed    MethodSetTy OverriddenMethods;
792193326Sed    size_t MethodsSize = Methods.size();
793193326Sed
794193326Sed    for (RecordDecl::decl_iterator i = RD->decls_begin(Context),
795193326Sed         e = RD->decls_end(Context);
796193326Sed         i != e; ++i) {
797193326Sed      // Traverse the record, looking for methods.
798193326Sed      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
799193326Sed        // If the method is pre virtual, add it to the methods vector.
800193326Sed        if (MD->isPure()) {
801193326Sed          Methods.push_back(MD);
802193326Sed          continue;
803193326Sed        }
804193326Sed
805193326Sed        // Otherwise, record all the overridden methods in our set.
806193326Sed        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
807193326Sed             E = MD->end_overridden_methods(); I != E; ++I) {
808193326Sed          // Keep track of the overridden methods.
809193326Sed          OverriddenMethods.insert(*I);
810193326Sed        }
811193326Sed      }
812193326Sed    }
813193326Sed
814193326Sed    // Now go through the methods and zero out all the ones we know are
815193326Sed    // overridden.
816193326Sed    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
817193326Sed      if (OverriddenMethods.count(Methods[i]))
818193326Sed        Methods[i] = 0;
819193326Sed    }
820193326Sed
821193326Sed  }
822193326Sed}
823193326Sed
824193326Sedbool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
825193326Sed                                  unsigned DiagID, AbstractDiagSelID SelID,
826193326Sed                                  const CXXRecordDecl *CurrentRD) {
827193326Sed
828193326Sed  if (!getLangOptions().CPlusPlus)
829193326Sed    return false;
830193326Sed
831193326Sed  if (const ArrayType *AT = Context.getAsArrayType(T))
832193326Sed    return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
833193326Sed                                  CurrentRD);
834193326Sed
835193326Sed  if (const PointerType *PT = T->getAsPointerType()) {
836193326Sed    // Find the innermost pointer type.
837193326Sed    while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
838193326Sed      PT = T;
839193326Sed
840193326Sed    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
841193326Sed      return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
842193326Sed                                    CurrentRD);
843193326Sed  }
844193326Sed
845193326Sed  const RecordType *RT = T->getAsRecordType();
846193326Sed  if (!RT)
847193326Sed    return false;
848193326Sed
849193326Sed  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
850193326Sed  if (!RD)
851193326Sed    return false;
852193326Sed
853193326Sed  if (CurrentRD && CurrentRD != RD)
854193326Sed    return false;
855193326Sed
856193326Sed  if (!RD->isAbstract())
857193326Sed    return false;
858193326Sed
859193326Sed  Diag(Loc, DiagID) << RD->getDeclName() << SelID;
860193326Sed
861193326Sed  // Check if we've already emitted the list of pure virtual functions for this
862193326Sed  // class.
863193326Sed  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
864193326Sed    return true;
865193326Sed
866193326Sed  PureVirtualMethodCollector Collector(Context, RD);
867193326Sed
868193326Sed  for (PureVirtualMethodCollector::MethodList::const_iterator I =
869193326Sed       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
870193326Sed    const CXXMethodDecl *MD = *I;
871193326Sed
872193326Sed    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
873193326Sed      MD->getDeclName();
874193326Sed  }
875193326Sed
876193326Sed  if (!PureVirtualClassDiagSet)
877193326Sed    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
878193326Sed  PureVirtualClassDiagSet->insert(RD);
879193326Sed
880193326Sed  return true;
881193326Sed}
882193326Sed
883193326Sednamespace {
884193326Sed  class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
885193326Sed    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
886193326Sed    Sema &SemaRef;
887193326Sed    CXXRecordDecl *AbstractClass;
888193326Sed
889193326Sed    bool VisitDeclContext(const DeclContext *DC) {
890193326Sed      bool Invalid = false;
891193326Sed
892193326Sed      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(SemaRef.Context),
893193326Sed           E = DC->decls_end(SemaRef.Context); I != E; ++I)
894193326Sed        Invalid |= Visit(*I);
895193326Sed
896193326Sed      return Invalid;
897193326Sed    }
898193326Sed
899193326Sed  public:
900193326Sed    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
901193326Sed      : SemaRef(SemaRef), AbstractClass(ac) {
902193326Sed        Visit(SemaRef.Context.getTranslationUnitDecl());
903193326Sed    }
904193326Sed
905193326Sed    bool VisitFunctionDecl(const FunctionDecl *FD) {
906193326Sed      if (FD->isThisDeclarationADefinition()) {
907193326Sed        // No need to do the check if we're in a definition, because it requires
908193326Sed        // that the return/param types are complete.
909193326Sed        // because that requires
910193326Sed        return VisitDeclContext(FD);
911193326Sed      }
912193326Sed
913193326Sed      // Check the return type.
914193326Sed      QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
915193326Sed      bool Invalid =
916193326Sed        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
917193326Sed                                       diag::err_abstract_type_in_decl,
918193326Sed                                       Sema::AbstractReturnType,
919193326Sed                                       AbstractClass);
920193326Sed
921193326Sed      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
922193326Sed           E = FD->param_end(); I != E; ++I) {
923193326Sed        const ParmVarDecl *VD = *I;
924193326Sed        Invalid |=
925193326Sed          SemaRef.RequireNonAbstractType(VD->getLocation(),
926193326Sed                                         VD->getOriginalType(),
927193326Sed                                         diag::err_abstract_type_in_decl,
928193326Sed                                         Sema::AbstractParamType,
929193326Sed                                         AbstractClass);
930193326Sed      }
931193326Sed
932193326Sed      return Invalid;
933193326Sed    }
934193326Sed
935193326Sed    bool VisitDecl(const Decl* D) {
936193326Sed      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
937193326Sed        return VisitDeclContext(DC);
938193326Sed
939193326Sed      return false;
940193326Sed    }
941193326Sed  };
942193326Sed}
943193326Sed
944193326Sedvoid Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
945193326Sed                                             DeclPtrTy TagDecl,
946193326Sed                                             SourceLocation LBrac,
947193326Sed                                             SourceLocation RBrac) {
948193326Sed  AdjustDeclIfTemplate(TagDecl);
949193326Sed  ActOnFields(S, RLoc, TagDecl,
950193326Sed              (DeclPtrTy*)FieldCollector->getCurFields(),
951193326Sed              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
952193326Sed
953193326Sed  CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
954193326Sed  if (!RD->isAbstract()) {
955193326Sed    // Collect all the pure virtual methods and see if this is an abstract
956193326Sed    // class after all.
957193326Sed    PureVirtualMethodCollector Collector(Context, RD);
958193326Sed    if (!Collector.empty())
959193326Sed      RD->setAbstract(true);
960193326Sed  }
961193326Sed
962193326Sed  if (RD->isAbstract())
963193326Sed    AbstractClassUsageDiagnoser(*this, RD);
964193326Sed
965193326Sed  if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
966193326Sed    for (RecordDecl::field_iterator i = RD->field_begin(Context),
967193326Sed         e = RD->field_end(Context); i != e; ++i) {
968193326Sed      // All the nonstatic data members must have trivial constructors.
969193326Sed      QualType FTy = i->getType();
970193326Sed      while (const ArrayType *AT = Context.getAsArrayType(FTy))
971193326Sed        FTy = AT->getElementType();
972193326Sed
973193326Sed      if (const RecordType *RT = FTy->getAsRecordType()) {
974193326Sed        CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
975193326Sed
976193326Sed        if (!FieldRD->hasTrivialConstructor())
977193326Sed          RD->setHasTrivialConstructor(false);
978193326Sed        if (!FieldRD->hasTrivialDestructor())
979193326Sed          RD->setHasTrivialDestructor(false);
980193326Sed
981193326Sed        // If RD has neither a trivial constructor nor a trivial destructor
982193326Sed        // we don't need to continue checking.
983193326Sed        if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
984193326Sed          break;
985193326Sed      }
986193326Sed    }
987193326Sed  }
988193326Sed
989193326Sed  if (!RD->isDependentType())
990193326Sed    AddImplicitlyDeclaredMembersToClass(RD);
991193326Sed}
992193326Sed
993193326Sed/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
994193326Sed/// special functions, such as the default constructor, copy
995193326Sed/// constructor, or destructor, to the given C++ class (C++
996193326Sed/// [special]p1).  This routine can only be executed just before the
997193326Sed/// definition of the class is complete.
998193326Sedvoid Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
999193326Sed  QualType ClassType = Context.getTypeDeclType(ClassDecl);
1000193326Sed  ClassType = Context.getCanonicalType(ClassType);
1001193326Sed
1002193326Sed  // FIXME: Implicit declarations have exception specifications, which are
1003193326Sed  // the union of the specifications of the implicitly called functions.
1004193326Sed
1005193326Sed  if (!ClassDecl->hasUserDeclaredConstructor()) {
1006193326Sed    // C++ [class.ctor]p5:
1007193326Sed    //   A default constructor for a class X is a constructor of class X
1008193326Sed    //   that can be called without an argument. If there is no
1009193326Sed    //   user-declared constructor for class X, a default constructor is
1010193326Sed    //   implicitly declared. An implicitly-declared default constructor
1011193326Sed    //   is an inline public member of its class.
1012193326Sed    DeclarationName Name
1013193326Sed      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1014193326Sed    CXXConstructorDecl *DefaultCon =
1015193326Sed      CXXConstructorDecl::Create(Context, ClassDecl,
1016193326Sed                                 ClassDecl->getLocation(), Name,
1017193326Sed                                 Context.getFunctionType(Context.VoidTy,
1018193326Sed                                                         0, 0, false, 0),
1019193326Sed                                 /*isExplicit=*/false,
1020193326Sed                                 /*isInline=*/true,
1021193326Sed                                 /*isImplicitlyDeclared=*/true);
1022193326Sed    DefaultCon->setAccess(AS_public);
1023193326Sed    DefaultCon->setImplicit();
1024193326Sed    ClassDecl->addDecl(Context, DefaultCon);
1025193326Sed
1026193326Sed    // Notify the class that we've added a constructor.
1027193326Sed    ClassDecl->addedConstructor(Context, DefaultCon);
1028193326Sed  }
1029193326Sed
1030193326Sed  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1031193326Sed    // C++ [class.copy]p4:
1032193326Sed    //   If the class definition does not explicitly declare a copy
1033193326Sed    //   constructor, one is declared implicitly.
1034193326Sed
1035193326Sed    // C++ [class.copy]p5:
1036193326Sed    //   The implicitly-declared copy constructor for a class X will
1037193326Sed    //   have the form
1038193326Sed    //
1039193326Sed    //       X::X(const X&)
1040193326Sed    //
1041193326Sed    //   if
1042193326Sed    bool HasConstCopyConstructor = true;
1043193326Sed
1044193326Sed    //     -- each direct or virtual base class B of X has a copy
1045193326Sed    //        constructor whose first parameter is of type const B& or
1046193326Sed    //        const volatile B&, and
1047193326Sed    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1048193326Sed         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1049193326Sed      const CXXRecordDecl *BaseClassDecl
1050193326Sed        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1051193326Sed      HasConstCopyConstructor
1052193326Sed        = BaseClassDecl->hasConstCopyConstructor(Context);
1053193326Sed    }
1054193326Sed
1055193326Sed    //     -- for all the nonstatic data members of X that are of a
1056193326Sed    //        class type M (or array thereof), each such class type
1057193326Sed    //        has a copy constructor whose first parameter is of type
1058193326Sed    //        const M& or const volatile M&.
1059193326Sed    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1060193326Sed         HasConstCopyConstructor && Field != ClassDecl->field_end(Context);
1061193326Sed         ++Field) {
1062193326Sed      QualType FieldType = (*Field)->getType();
1063193326Sed      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1064193326Sed        FieldType = Array->getElementType();
1065193326Sed      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1066193326Sed        const CXXRecordDecl *FieldClassDecl
1067193326Sed          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1068193326Sed        HasConstCopyConstructor
1069193326Sed          = FieldClassDecl->hasConstCopyConstructor(Context);
1070193326Sed      }
1071193326Sed    }
1072193326Sed
1073193326Sed    //   Otherwise, the implicitly declared copy constructor will have
1074193326Sed    //   the form
1075193326Sed    //
1076193326Sed    //       X::X(X&)
1077193326Sed    QualType ArgType = ClassType;
1078193326Sed    if (HasConstCopyConstructor)
1079193326Sed      ArgType = ArgType.withConst();
1080193326Sed    ArgType = Context.getLValueReferenceType(ArgType);
1081193326Sed
1082193326Sed    //   An implicitly-declared copy constructor is an inline public
1083193326Sed    //   member of its class.
1084193326Sed    DeclarationName Name
1085193326Sed      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1086193326Sed    CXXConstructorDecl *CopyConstructor
1087193326Sed      = CXXConstructorDecl::Create(Context, ClassDecl,
1088193326Sed                                   ClassDecl->getLocation(), Name,
1089193326Sed                                   Context.getFunctionType(Context.VoidTy,
1090193326Sed                                                           &ArgType, 1,
1091193326Sed                                                           false, 0),
1092193326Sed                                   /*isExplicit=*/false,
1093193326Sed                                   /*isInline=*/true,
1094193326Sed                                   /*isImplicitlyDeclared=*/true);
1095193326Sed    CopyConstructor->setAccess(AS_public);
1096193326Sed    CopyConstructor->setImplicit();
1097193326Sed
1098193326Sed    // Add the parameter to the constructor.
1099193326Sed    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1100193326Sed                                                 ClassDecl->getLocation(),
1101193326Sed                                                 /*IdentifierInfo=*/0,
1102193326Sed                                                 ArgType, VarDecl::None, 0);
1103193326Sed    CopyConstructor->setParams(Context, &FromParam, 1);
1104193326Sed
1105193326Sed    ClassDecl->addedConstructor(Context, CopyConstructor);
1106193326Sed    ClassDecl->addDecl(Context, CopyConstructor);
1107193326Sed  }
1108193326Sed
1109193326Sed  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1110193326Sed    // Note: The following rules are largely analoguous to the copy
1111193326Sed    // constructor rules. Note that virtual bases are not taken into account
1112193326Sed    // for determining the argument type of the operator. Note also that
1113193326Sed    // operators taking an object instead of a reference are allowed.
1114193326Sed    //
1115193326Sed    // C++ [class.copy]p10:
1116193326Sed    //   If the class definition does not explicitly declare a copy
1117193326Sed    //   assignment operator, one is declared implicitly.
1118193326Sed    //   The implicitly-defined copy assignment operator for a class X
1119193326Sed    //   will have the form
1120193326Sed    //
1121193326Sed    //       X& X::operator=(const X&)
1122193326Sed    //
1123193326Sed    //   if
1124193326Sed    bool HasConstCopyAssignment = true;
1125193326Sed
1126193326Sed    //       -- each direct base class B of X has a copy assignment operator
1127193326Sed    //          whose parameter is of type const B&, const volatile B& or B,
1128193326Sed    //          and
1129193326Sed    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1130193326Sed         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1131193326Sed      const CXXRecordDecl *BaseClassDecl
1132193326Sed        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1133193326Sed      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1134193326Sed    }
1135193326Sed
1136193326Sed    //       -- for all the nonstatic data members of X that are of a class
1137193326Sed    //          type M (or array thereof), each such class type has a copy
1138193326Sed    //          assignment operator whose parameter is of type const M&,
1139193326Sed    //          const volatile M& or M.
1140193326Sed    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1141193326Sed         HasConstCopyAssignment && Field != ClassDecl->field_end(Context);
1142193326Sed         ++Field) {
1143193326Sed      QualType FieldType = (*Field)->getType();
1144193326Sed      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1145193326Sed        FieldType = Array->getElementType();
1146193326Sed      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1147193326Sed        const CXXRecordDecl *FieldClassDecl
1148193326Sed          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1149193326Sed        HasConstCopyAssignment
1150193326Sed          = FieldClassDecl->hasConstCopyAssignment(Context);
1151193326Sed      }
1152193326Sed    }
1153193326Sed
1154193326Sed    //   Otherwise, the implicitly declared copy assignment operator will
1155193326Sed    //   have the form
1156193326Sed    //
1157193326Sed    //       X& X::operator=(X&)
1158193326Sed    QualType ArgType = ClassType;
1159193326Sed    QualType RetType = Context.getLValueReferenceType(ArgType);
1160193326Sed    if (HasConstCopyAssignment)
1161193326Sed      ArgType = ArgType.withConst();
1162193326Sed    ArgType = Context.getLValueReferenceType(ArgType);
1163193326Sed
1164193326Sed    //   An implicitly-declared copy assignment operator is an inline public
1165193326Sed    //   member of its class.
1166193326Sed    DeclarationName Name =
1167193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1168193326Sed    CXXMethodDecl *CopyAssignment =
1169193326Sed      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1170193326Sed                            Context.getFunctionType(RetType, &ArgType, 1,
1171193326Sed                                                    false, 0),
1172193326Sed                            /*isStatic=*/false, /*isInline=*/true);
1173193326Sed    CopyAssignment->setAccess(AS_public);
1174193326Sed    CopyAssignment->setImplicit();
1175193326Sed
1176193326Sed    // Add the parameter to the operator.
1177193326Sed    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1178193326Sed                                                 ClassDecl->getLocation(),
1179193326Sed                                                 /*IdentifierInfo=*/0,
1180193326Sed                                                 ArgType, VarDecl::None, 0);
1181193326Sed    CopyAssignment->setParams(Context, &FromParam, 1);
1182193326Sed
1183193326Sed    // Don't call addedAssignmentOperator. There is no way to distinguish an
1184193326Sed    // implicit from an explicit assignment operator.
1185193326Sed    ClassDecl->addDecl(Context, CopyAssignment);
1186193326Sed  }
1187193326Sed
1188193326Sed  if (!ClassDecl->hasUserDeclaredDestructor()) {
1189193326Sed    // C++ [class.dtor]p2:
1190193326Sed    //   If a class has no user-declared destructor, a destructor is
1191193326Sed    //   declared implicitly. An implicitly-declared destructor is an
1192193326Sed    //   inline public member of its class.
1193193326Sed    DeclarationName Name
1194193326Sed      = Context.DeclarationNames.getCXXDestructorName(ClassType);
1195193326Sed    CXXDestructorDecl *Destructor
1196193326Sed      = CXXDestructorDecl::Create(Context, ClassDecl,
1197193326Sed                                  ClassDecl->getLocation(), Name,
1198193326Sed                                  Context.getFunctionType(Context.VoidTy,
1199193326Sed                                                          0, 0, false, 0),
1200193326Sed                                  /*isInline=*/true,
1201193326Sed                                  /*isImplicitlyDeclared=*/true);
1202193326Sed    Destructor->setAccess(AS_public);
1203193326Sed    Destructor->setImplicit();
1204193326Sed    ClassDecl->addDecl(Context, Destructor);
1205193326Sed  }
1206193326Sed}
1207193326Sed
1208193326Sedvoid Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1209193326Sed  TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1210193326Sed  if (!Template)
1211193326Sed    return;
1212193326Sed
1213193326Sed  TemplateParameterList *Params = Template->getTemplateParameters();
1214193326Sed  for (TemplateParameterList::iterator Param = Params->begin(),
1215193326Sed                                    ParamEnd = Params->end();
1216193326Sed       Param != ParamEnd; ++Param) {
1217193326Sed    NamedDecl *Named = cast<NamedDecl>(*Param);
1218193326Sed    if (Named->getDeclName()) {
1219193326Sed      S->AddDecl(DeclPtrTy::make(Named));
1220193326Sed      IdResolver.AddDecl(Named);
1221193326Sed    }
1222193326Sed  }
1223193326Sed}
1224193326Sed
1225193326Sed/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1226193326Sed/// parsing a top-level (non-nested) C++ class, and we are now
1227193326Sed/// parsing those parts of the given Method declaration that could
1228193326Sed/// not be parsed earlier (C++ [class.mem]p2), such as default
1229193326Sed/// arguments. This action should enter the scope of the given
1230193326Sed/// Method declaration as if we had just parsed the qualified method
1231193326Sed/// name. However, it should not bring the parameters into scope;
1232193326Sed/// that will be performed by ActOnDelayedCXXMethodParameter.
1233193326Sedvoid Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1234193326Sed  CXXScopeSpec SS;
1235193326Sed  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1236193326Sed  QualType ClassTy
1237193326Sed    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1238193326Sed  SS.setScopeRep(
1239193326Sed    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1240193326Sed  ActOnCXXEnterDeclaratorScope(S, SS);
1241193326Sed}
1242193326Sed
1243193326Sed/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1244193326Sed/// C++ method declaration. We're (re-)introducing the given
1245193326Sed/// function parameter into scope for use in parsing later parts of
1246193326Sed/// the method declaration. For example, we could see an
1247193326Sed/// ActOnParamDefaultArgument event for this parameter.
1248193326Sedvoid Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
1249193326Sed  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
1250193326Sed
1251193326Sed  // If this parameter has an unparsed default argument, clear it out
1252193326Sed  // to make way for the parsed default argument.
1253193326Sed  if (Param->hasUnparsedDefaultArg())
1254193326Sed    Param->setDefaultArg(0);
1255193326Sed
1256193326Sed  S->AddDecl(DeclPtrTy::make(Param));
1257193326Sed  if (Param->getDeclName())
1258193326Sed    IdResolver.AddDecl(Param);
1259193326Sed}
1260193326Sed
1261193326Sed/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1262193326Sed/// processing the delayed method declaration for Method. The method
1263193326Sed/// declaration is now considered finished. There may be a separate
1264193326Sed/// ActOnStartOfFunctionDef action later (not necessarily
1265193326Sed/// immediately!) for this method, if it was also defined inside the
1266193326Sed/// class body.
1267193326Sedvoid Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1268193326Sed  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1269193326Sed  CXXScopeSpec SS;
1270193326Sed  QualType ClassTy
1271193326Sed    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1272193326Sed  SS.setScopeRep(
1273193326Sed    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1274193326Sed  ActOnCXXExitDeclaratorScope(S, SS);
1275193326Sed
1276193326Sed  // Now that we have our default arguments, check the constructor
1277193326Sed  // again. It could produce additional diagnostics or affect whether
1278193326Sed  // the class has implicitly-declared destructors, among other
1279193326Sed  // things.
1280193326Sed  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1281193326Sed    CheckConstructor(Constructor);
1282193326Sed
1283193326Sed  // Check the default arguments, which we may have added.
1284193326Sed  if (!Method->isInvalidDecl())
1285193326Sed    CheckCXXDefaultArguments(Method);
1286193326Sed}
1287193326Sed
1288193326Sed/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1289193326Sed/// the well-formedness of the constructor declarator @p D with type @p
1290193326Sed/// R. If there are any errors in the declarator, this routine will
1291193326Sed/// emit diagnostics and set the invalid bit to true.  In any case, the type
1292193326Sed/// will be updated to reflect a well-formed type for the constructor and
1293193326Sed/// returned.
1294193326SedQualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1295193326Sed                                          FunctionDecl::StorageClass &SC) {
1296193326Sed  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1297193326Sed
1298193326Sed  // C++ [class.ctor]p3:
1299193326Sed  //   A constructor shall not be virtual (10.3) or static (9.4). A
1300193326Sed  //   constructor can be invoked for a const, volatile or const
1301193326Sed  //   volatile object. A constructor shall not be declared const,
1302193326Sed  //   volatile, or const volatile (9.3.2).
1303193326Sed  if (isVirtual) {
1304193326Sed    if (!D.isInvalidType())
1305193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1306193326Sed        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1307193326Sed        << SourceRange(D.getIdentifierLoc());
1308193326Sed    D.setInvalidType();
1309193326Sed  }
1310193326Sed  if (SC == FunctionDecl::Static) {
1311193326Sed    if (!D.isInvalidType())
1312193326Sed      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1313193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1314193326Sed        << SourceRange(D.getIdentifierLoc());
1315193326Sed    D.setInvalidType();
1316193326Sed    SC = FunctionDecl::None;
1317193326Sed  }
1318193326Sed
1319193326Sed  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1320193326Sed  if (FTI.TypeQuals != 0) {
1321193326Sed    if (FTI.TypeQuals & QualType::Const)
1322193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1323193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
1324193326Sed    if (FTI.TypeQuals & QualType::Volatile)
1325193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1326193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
1327193326Sed    if (FTI.TypeQuals & QualType::Restrict)
1328193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1329193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
1330193326Sed  }
1331193326Sed
1332193326Sed  // Rebuild the function type "R" without any type qualifiers (in
1333193326Sed  // case any of the errors above fired) and with "void" as the
1334193326Sed  // return type, since constructors don't have return types. We
1335193326Sed  // *always* have to do this, because GetTypeForDeclarator will
1336193326Sed  // put in a result type of "int" when none was specified.
1337193326Sed  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1338193326Sed  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1339193326Sed                                 Proto->getNumArgs(),
1340193326Sed                                 Proto->isVariadic(), 0);
1341193326Sed}
1342193326Sed
1343193326Sed/// CheckConstructor - Checks a fully-formed constructor for
1344193326Sed/// well-formedness, issuing any diagnostics required. Returns true if
1345193326Sed/// the constructor declarator is invalid.
1346193326Sedvoid Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1347193326Sed  CXXRecordDecl *ClassDecl
1348193326Sed    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1349193326Sed  if (!ClassDecl)
1350193326Sed    return Constructor->setInvalidDecl();
1351193326Sed
1352193326Sed  // C++ [class.copy]p3:
1353193326Sed  //   A declaration of a constructor for a class X is ill-formed if
1354193326Sed  //   its first parameter is of type (optionally cv-qualified) X and
1355193326Sed  //   either there are no other parameters or else all other
1356193326Sed  //   parameters have default arguments.
1357193326Sed  if (!Constructor->isInvalidDecl() &&
1358193326Sed      ((Constructor->getNumParams() == 1) ||
1359193326Sed       (Constructor->getNumParams() > 1 &&
1360193326Sed        Constructor->getParamDecl(1)->getDefaultArg() != 0))) {
1361193326Sed    QualType ParamType = Constructor->getParamDecl(0)->getType();
1362193326Sed    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1363193326Sed    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1364193326Sed      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1365193326Sed      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
1366193326Sed        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
1367193326Sed      Constructor->setInvalidDecl();
1368193326Sed    }
1369193326Sed  }
1370193326Sed
1371193326Sed  // Notify the class that we've added a constructor.
1372193326Sed  ClassDecl->addedConstructor(Context, Constructor);
1373193326Sed}
1374193326Sed
1375193326Sedstatic inline bool
1376193326SedFTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1377193326Sed  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1378193326Sed          FTI.ArgInfo[0].Param &&
1379193326Sed          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1380193326Sed}
1381193326Sed
1382193326Sed/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1383193326Sed/// the well-formednes of the destructor declarator @p D with type @p
1384193326Sed/// R. If there are any errors in the declarator, this routine will
1385193326Sed/// emit diagnostics and set the declarator to invalid.  Even if this happens,
1386193326Sed/// will be updated to reflect a well-formed type for the destructor and
1387193326Sed/// returned.
1388193326SedQualType Sema::CheckDestructorDeclarator(Declarator &D,
1389193326Sed                                         FunctionDecl::StorageClass& SC) {
1390193326Sed  // C++ [class.dtor]p1:
1391193326Sed  //   [...] A typedef-name that names a class is a class-name
1392193326Sed  //   (7.1.3); however, a typedef-name that names a class shall not
1393193326Sed  //   be used as the identifier in the declarator for a destructor
1394193326Sed  //   declaration.
1395193326Sed  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1396193326Sed  if (isa<TypedefType>(DeclaratorType)) {
1397193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
1398193326Sed      << DeclaratorType;
1399193326Sed    D.setInvalidType();
1400193326Sed  }
1401193326Sed
1402193326Sed  // C++ [class.dtor]p2:
1403193326Sed  //   A destructor is used to destroy objects of its class type. A
1404193326Sed  //   destructor takes no parameters, and no return type can be
1405193326Sed  //   specified for it (not even void). The address of a destructor
1406193326Sed  //   shall not be taken. A destructor shall not be static. A
1407193326Sed  //   destructor can be invoked for a const, volatile or const
1408193326Sed  //   volatile object. A destructor shall not be declared const,
1409193326Sed  //   volatile or const volatile (9.3.2).
1410193326Sed  if (SC == FunctionDecl::Static) {
1411193326Sed    if (!D.isInvalidType())
1412193326Sed      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1413193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1414193326Sed        << SourceRange(D.getIdentifierLoc());
1415193326Sed    SC = FunctionDecl::None;
1416193326Sed    D.setInvalidType();
1417193326Sed  }
1418193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1419193326Sed    // Destructors don't have return types, but the parser will
1420193326Sed    // happily parse something like:
1421193326Sed    //
1422193326Sed    //   class X {
1423193326Sed    //     float ~X();
1424193326Sed    //   };
1425193326Sed    //
1426193326Sed    // The return type will be eliminated later.
1427193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1428193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1429193326Sed      << SourceRange(D.getIdentifierLoc());
1430193326Sed  }
1431193326Sed
1432193326Sed  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1433193326Sed  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
1434193326Sed    if (FTI.TypeQuals & QualType::Const)
1435193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1436193326Sed        << "const" << SourceRange(D.getIdentifierLoc());
1437193326Sed    if (FTI.TypeQuals & QualType::Volatile)
1438193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1439193326Sed        << "volatile" << SourceRange(D.getIdentifierLoc());
1440193326Sed    if (FTI.TypeQuals & QualType::Restrict)
1441193326Sed      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1442193326Sed        << "restrict" << SourceRange(D.getIdentifierLoc());
1443193326Sed    D.setInvalidType();
1444193326Sed  }
1445193326Sed
1446193326Sed  // Make sure we don't have any parameters.
1447193326Sed  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
1448193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1449193326Sed
1450193326Sed    // Delete the parameters.
1451193326Sed    FTI.freeArgs();
1452193326Sed    D.setInvalidType();
1453193326Sed  }
1454193326Sed
1455193326Sed  // Make sure the destructor isn't variadic.
1456193326Sed  if (FTI.isVariadic) {
1457193326Sed    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1458193326Sed    D.setInvalidType();
1459193326Sed  }
1460193326Sed
1461193326Sed  // Rebuild the function type "R" without any type qualifiers or
1462193326Sed  // parameters (in case any of the errors above fired) and with
1463193326Sed  // "void" as the return type, since destructors don't have return
1464193326Sed  // types. We *always* have to do this, because GetTypeForDeclarator
1465193326Sed  // will put in a result type of "int" when none was specified.
1466193326Sed  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1467193326Sed}
1468193326Sed
1469193326Sed/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1470193326Sed/// well-formednes of the conversion function declarator @p D with
1471193326Sed/// type @p R. If there are any errors in the declarator, this routine
1472193326Sed/// will emit diagnostics and return true. Otherwise, it will return
1473193326Sed/// false. Either way, the type @p R will be updated to reflect a
1474193326Sed/// well-formed type for the conversion operator.
1475193326Sedvoid Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1476193326Sed                                     FunctionDecl::StorageClass& SC) {
1477193326Sed  // C++ [class.conv.fct]p1:
1478193326Sed  //   Neither parameter types nor return type can be specified. The
1479193326Sed  //   type of a conversion function (8.3.5) is ���function taking no
1480193326Sed  //   parameter returning conversion-type-id.���
1481193326Sed  if (SC == FunctionDecl::Static) {
1482193326Sed    if (!D.isInvalidType())
1483193326Sed      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1484193326Sed        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1485193326Sed        << SourceRange(D.getIdentifierLoc());
1486193326Sed    D.setInvalidType();
1487193326Sed    SC = FunctionDecl::None;
1488193326Sed  }
1489193326Sed  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1490193326Sed    // Conversion functions don't have return types, but the parser will
1491193326Sed    // happily parse something like:
1492193326Sed    //
1493193326Sed    //   class X {
1494193326Sed    //     float operator bool();
1495193326Sed    //   };
1496193326Sed    //
1497193326Sed    // The return type will be changed later anyway.
1498193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1499193326Sed      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1500193326Sed      << SourceRange(D.getIdentifierLoc());
1501193326Sed  }
1502193326Sed
1503193326Sed  // Make sure we don't have any parameters.
1504193326Sed  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1505193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1506193326Sed
1507193326Sed    // Delete the parameters.
1508193326Sed    D.getTypeObject(0).Fun.freeArgs();
1509193326Sed    D.setInvalidType();
1510193326Sed  }
1511193326Sed
1512193326Sed  // Make sure the conversion function isn't variadic.
1513193326Sed  if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
1514193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1515193326Sed    D.setInvalidType();
1516193326Sed  }
1517193326Sed
1518193326Sed  // C++ [class.conv.fct]p4:
1519193326Sed  //   The conversion-type-id shall not represent a function type nor
1520193326Sed  //   an array type.
1521193326Sed  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1522193326Sed  if (ConvType->isArrayType()) {
1523193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1524193326Sed    ConvType = Context.getPointerType(ConvType);
1525193326Sed    D.setInvalidType();
1526193326Sed  } else if (ConvType->isFunctionType()) {
1527193326Sed    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1528193326Sed    ConvType = Context.getPointerType(ConvType);
1529193326Sed    D.setInvalidType();
1530193326Sed  }
1531193326Sed
1532193326Sed  // Rebuild the function type "R" without any parameters (in case any
1533193326Sed  // of the errors above fired) and with the conversion type as the
1534193326Sed  // return type.
1535193326Sed  R = Context.getFunctionType(ConvType, 0, 0, false,
1536193326Sed                              R->getAsFunctionProtoType()->getTypeQuals());
1537193326Sed
1538193326Sed  // C++0x explicit conversion operators.
1539193326Sed  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1540193326Sed    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1541193326Sed         diag::warn_explicit_conversion_functions)
1542193326Sed      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1543193326Sed}
1544193326Sed
1545193326Sed/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1546193326Sed/// the declaration of the given C++ conversion function. This routine
1547193326Sed/// is responsible for recording the conversion function in the C++
1548193326Sed/// class, if possible.
1549193326SedSema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1550193326Sed  assert(Conversion && "Expected to receive a conversion function declaration");
1551193326Sed
1552193326Sed  // Set the lexical context of this conversion function
1553193326Sed  Conversion->setLexicalDeclContext(CurContext);
1554193326Sed
1555193326Sed  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1556193326Sed
1557193326Sed  // Make sure we aren't redeclaring the conversion function.
1558193326Sed  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1559193326Sed
1560193326Sed  // C++ [class.conv.fct]p1:
1561193326Sed  //   [...] A conversion function is never used to convert a
1562193326Sed  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1563193326Sed  //   same object type (or a reference to it), to a (possibly
1564193326Sed  //   cv-qualified) base class of that type (or a reference to it),
1565193326Sed  //   or to (possibly cv-qualified) void.
1566193326Sed  // FIXME: Suppress this warning if the conversion function ends up being a
1567193326Sed  // virtual function that overrides a virtual function in a base class.
1568193326Sed  QualType ClassType
1569193326Sed    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1570193326Sed  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1571193326Sed    ConvType = ConvTypeRef->getPointeeType();
1572193326Sed  if (ConvType->isRecordType()) {
1573193326Sed    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1574193326Sed    if (ConvType == ClassType)
1575193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1576193326Sed        << ClassType;
1577193326Sed    else if (IsDerivedFrom(ClassType, ConvType))
1578193326Sed      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1579193326Sed        <<  ClassType << ConvType;
1580193326Sed  } else if (ConvType->isVoidType()) {
1581193326Sed    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1582193326Sed      << ClassType << ConvType;
1583193326Sed  }
1584193326Sed
1585193326Sed  if (Conversion->getPreviousDeclaration()) {
1586193326Sed    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1587193326Sed    for (OverloadedFunctionDecl::function_iterator
1588193326Sed           Conv = Conversions->function_begin(),
1589193326Sed           ConvEnd = Conversions->function_end();
1590193326Sed         Conv != ConvEnd; ++Conv) {
1591193326Sed      if (*Conv == Conversion->getPreviousDeclaration()) {
1592193326Sed        *Conv = Conversion;
1593193326Sed        return DeclPtrTy::make(Conversion);
1594193326Sed      }
1595193326Sed    }
1596193326Sed    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1597193326Sed  } else
1598193326Sed    ClassDecl->addConversionFunction(Context, Conversion);
1599193326Sed
1600193326Sed  return DeclPtrTy::make(Conversion);
1601193326Sed}
1602193326Sed
1603193326Sed//===----------------------------------------------------------------------===//
1604193326Sed// Namespace Handling
1605193326Sed//===----------------------------------------------------------------------===//
1606193326Sed
1607193326Sed/// ActOnStartNamespaceDef - This is called at the start of a namespace
1608193326Sed/// definition.
1609193326SedSema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1610193326Sed                                             SourceLocation IdentLoc,
1611193326Sed                                             IdentifierInfo *II,
1612193326Sed                                             SourceLocation LBrace) {
1613193326Sed  NamespaceDecl *Namespc =
1614193326Sed      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1615193326Sed  Namespc->setLBracLoc(LBrace);
1616193326Sed
1617193326Sed  Scope *DeclRegionScope = NamespcScope->getParent();
1618193326Sed
1619193326Sed  if (II) {
1620193326Sed    // C++ [namespace.def]p2:
1621193326Sed    // The identifier in an original-namespace-definition shall not have been
1622193326Sed    // previously defined in the declarative region in which the
1623193326Sed    // original-namespace-definition appears. The identifier in an
1624193326Sed    // original-namespace-definition is the name of the namespace. Subsequently
1625193326Sed    // in that declarative region, it is treated as an original-namespace-name.
1626193326Sed
1627193326Sed    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1628193326Sed                                     true);
1629193326Sed
1630193326Sed    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1631193326Sed      // This is an extended namespace definition.
1632193326Sed      // Attach this namespace decl to the chain of extended namespace
1633193326Sed      // definitions.
1634193326Sed      OrigNS->setNextNamespace(Namespc);
1635193326Sed      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1636193326Sed
1637193326Sed      // Remove the previous declaration from the scope.
1638193326Sed      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
1639193326Sed        IdResolver.RemoveDecl(OrigNS);
1640193326Sed        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
1641193326Sed      }
1642193326Sed    } else if (PrevDecl) {
1643193326Sed      // This is an invalid name redefinition.
1644193326Sed      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1645193326Sed       << Namespc->getDeclName();
1646193326Sed      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1647193326Sed      Namespc->setInvalidDecl();
1648193326Sed      // Continue on to push Namespc as current DeclContext and return it.
1649193326Sed    }
1650193326Sed
1651193326Sed    PushOnScopeChains(Namespc, DeclRegionScope);
1652193326Sed  } else {
1653193326Sed    // FIXME: Handle anonymous namespaces
1654193326Sed  }
1655193326Sed
1656193326Sed  // Although we could have an invalid decl (i.e. the namespace name is a
1657193326Sed  // redefinition), push it as current DeclContext and try to continue parsing.
1658193326Sed  // FIXME: We should be able to push Namespc here, so that the each DeclContext
1659193326Sed  // for the namespace has the declarations that showed up in that particular
1660193326Sed  // namespace definition.
1661193326Sed  PushDeclContext(NamespcScope, Namespc);
1662193326Sed  return DeclPtrTy::make(Namespc);
1663193326Sed}
1664193326Sed
1665193326Sed/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1666193326Sed/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1667193326Sedvoid Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1668193326Sed  Decl *Dcl = D.getAs<Decl>();
1669193326Sed  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1670193326Sed  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1671193326Sed  Namespc->setRBracLoc(RBrace);
1672193326Sed  PopDeclContext();
1673193326Sed}
1674193326Sed
1675193326SedSema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1676193326Sed                                          SourceLocation UsingLoc,
1677193326Sed                                          SourceLocation NamespcLoc,
1678193326Sed                                          const CXXScopeSpec &SS,
1679193326Sed                                          SourceLocation IdentLoc,
1680193326Sed                                          IdentifierInfo *NamespcName,
1681193326Sed                                          AttributeList *AttrList) {
1682193326Sed  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1683193326Sed  assert(NamespcName && "Invalid NamespcName.");
1684193326Sed  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1685193326Sed  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1686193326Sed
1687193326Sed  UsingDirectiveDecl *UDir = 0;
1688193326Sed
1689193326Sed  // Lookup namespace name.
1690193326Sed  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1691193326Sed                                    LookupNamespaceName, false);
1692193326Sed  if (R.isAmbiguous()) {
1693193326Sed    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1694193326Sed    return DeclPtrTy();
1695193326Sed  }
1696193326Sed  if (NamedDecl *NS = R) {
1697193326Sed    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1698193326Sed    // C++ [namespace.udir]p1:
1699193326Sed    //   A using-directive specifies that the names in the nominated
1700193326Sed    //   namespace can be used in the scope in which the
1701193326Sed    //   using-directive appears after the using-directive. During
1702193326Sed    //   unqualified name lookup (3.4.1), the names appear as if they
1703193326Sed    //   were declared in the nearest enclosing namespace which
1704193326Sed    //   contains both the using-directive and the nominated
1705193326Sed    //   namespace. [Note: in this context, ���contains��� means ���contains
1706193326Sed    //   directly or indirectly���. ]
1707193326Sed
1708193326Sed    // Find enclosing context containing both using-directive and
1709193326Sed    // nominated namespace.
1710193326Sed    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1711193326Sed    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1712193326Sed      CommonAncestor = CommonAncestor->getParent();
1713193326Sed
1714193326Sed    UDir = UsingDirectiveDecl::Create(Context,
1715193326Sed                                      CurContext, UsingLoc,
1716193326Sed                                      NamespcLoc,
1717193326Sed                                      SS.getRange(),
1718193326Sed                                      (NestedNameSpecifier *)SS.getScopeRep(),
1719193326Sed                                      IdentLoc,
1720193326Sed                                      cast<NamespaceDecl>(NS),
1721193326Sed                                      CommonAncestor);
1722193326Sed    PushUsingDirective(S, UDir);
1723193326Sed  } else {
1724193326Sed    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1725193326Sed  }
1726193326Sed
1727193326Sed  // FIXME: We ignore attributes for now.
1728193326Sed  delete AttrList;
1729193326Sed  return DeclPtrTy::make(UDir);
1730193326Sed}
1731193326Sed
1732193326Sedvoid Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1733193326Sed  // If scope has associated entity, then using directive is at namespace
1734193326Sed  // or translation unit scope. We add UsingDirectiveDecls, into
1735193326Sed  // it's lookup structure.
1736193326Sed  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1737193326Sed    Ctx->addDecl(Context, UDir);
1738193326Sed  else
1739193326Sed    // Otherwise it is block-sope. using-directives will affect lookup
1740193326Sed    // only to the end of scope.
1741193326Sed    S->PushUsingDirective(DeclPtrTy::make(UDir));
1742193326Sed}
1743193326Sed
1744193326Sed/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1745193326Sed/// is a namespace alias, returns the namespace it points to.
1746193326Sedstatic inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1747193326Sed  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1748193326Sed    return AD->getNamespace();
1749193326Sed  return dyn_cast_or_null<NamespaceDecl>(D);
1750193326Sed}
1751193326Sed
1752193326SedSema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
1753193326Sed                                             SourceLocation NamespaceLoc,
1754193326Sed                                             SourceLocation AliasLoc,
1755193326Sed                                             IdentifierInfo *Alias,
1756193326Sed                                             const CXXScopeSpec &SS,
1757193326Sed                                             SourceLocation IdentLoc,
1758193326Sed                                             IdentifierInfo *Ident) {
1759193326Sed
1760193326Sed  // Lookup the namespace name.
1761193326Sed  LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1762193326Sed
1763193326Sed  // Check if we have a previous declaration with the same name.
1764193326Sed  if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
1765193326Sed    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1766193326Sed      // We already have an alias with the same name that points to the same
1767193326Sed      // namespace, so don't create a new one.
1768193326Sed      if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1769193326Sed        return DeclPtrTy();
1770193326Sed    }
1771193326Sed
1772193326Sed    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1773193326Sed      diag::err_redefinition_different_kind;
1774193326Sed    Diag(AliasLoc, DiagID) << Alias;
1775193326Sed    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1776193326Sed    return DeclPtrTy();
1777193326Sed  }
1778193326Sed
1779193326Sed  if (R.isAmbiguous()) {
1780193326Sed    DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
1781193326Sed    return DeclPtrTy();
1782193326Sed  }
1783193326Sed
1784193326Sed  if (!R) {
1785193326Sed    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
1786193326Sed    return DeclPtrTy();
1787193326Sed  }
1788193326Sed
1789193326Sed  NamespaceAliasDecl *AliasDecl =
1790193326Sed    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1791193326Sed                               Alias, SS.getRange(),
1792193326Sed                               (NestedNameSpecifier *)SS.getScopeRep(),
1793193326Sed                               IdentLoc, R);
1794193326Sed
1795193326Sed  CurContext->addDecl(Context, AliasDecl);
1796193326Sed  return DeclPtrTy::make(AliasDecl);
1797193326Sed}
1798193326Sed
1799193326Sedvoid Sema::InitializeVarWithConstructor(VarDecl *VD,
1800193326Sed                                        CXXConstructorDecl *Constructor,
1801193326Sed                                        QualType DeclInitType,
1802193326Sed                                        Expr **Exprs, unsigned NumExprs) {
1803193326Sed  Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
1804193326Sed                                        false, Exprs, NumExprs);
1805193326Sed  VD->setInit(Context, Temp);
1806193326Sed}
1807193326Sed
1808193326Sed/// AddCXXDirectInitializerToDecl - This action is called immediately after
1809193326Sed/// ActOnDeclarator, when a C++ direct initializer is present.
1810193326Sed/// e.g: "int x(1);"
1811193326Sedvoid Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
1812193326Sed                                         SourceLocation LParenLoc,
1813193326Sed                                         MultiExprArg Exprs,
1814193326Sed                                         SourceLocation *CommaLocs,
1815193326Sed                                         SourceLocation RParenLoc) {
1816193326Sed  unsigned NumExprs = Exprs.size();
1817193326Sed  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
1818193326Sed  Decl *RealDecl = Dcl.getAs<Decl>();
1819193326Sed
1820193326Sed  // If there is no declaration, there was an error parsing it.  Just ignore
1821193326Sed  // the initializer.
1822193326Sed  if (RealDecl == 0)
1823193326Sed    return;
1824193326Sed
1825193326Sed  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1826193326Sed  if (!VDecl) {
1827193326Sed    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1828193326Sed    RealDecl->setInvalidDecl();
1829193326Sed    return;
1830193326Sed  }
1831193326Sed
1832193326Sed  // FIXME: Need to handle dependent types and expressions here.
1833193326Sed
1834193326Sed  // We will treat direct-initialization as a copy-initialization:
1835193326Sed  //    int x(1);  -as-> int x = 1;
1836193326Sed  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1837193326Sed  //
1838193326Sed  // Clients that want to distinguish between the two forms, can check for
1839193326Sed  // direct initializer using VarDecl::hasCXXDirectInitializer().
1840193326Sed  // A major benefit is that clients that don't particularly care about which
1841193326Sed  // exactly form was it (like the CodeGen) can handle both cases without
1842193326Sed  // special case code.
1843193326Sed
1844193326Sed  // C++ 8.5p11:
1845193326Sed  // The form of initialization (using parentheses or '=') is generally
1846193326Sed  // insignificant, but does matter when the entity being initialized has a
1847193326Sed  // class type.
1848193326Sed  QualType DeclInitType = VDecl->getType();
1849193326Sed  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1850193326Sed    DeclInitType = Array->getElementType();
1851193326Sed
1852193326Sed  // FIXME: This isn't the right place to complete the type.
1853193326Sed  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
1854193326Sed                          diag::err_typecheck_decl_incomplete_type)) {
1855193326Sed    VDecl->setInvalidDecl();
1856193326Sed    return;
1857193326Sed  }
1858193326Sed
1859193326Sed  if (VDecl->getType()->isRecordType()) {
1860193326Sed    CXXConstructorDecl *Constructor
1861193326Sed      = PerformInitializationByConstructor(DeclInitType,
1862193326Sed                                           (Expr **)Exprs.get(), NumExprs,
1863193326Sed                                           VDecl->getLocation(),
1864193326Sed                                           SourceRange(VDecl->getLocation(),
1865193326Sed                                                       RParenLoc),
1866193326Sed                                           VDecl->getDeclName(),
1867193326Sed                                           IK_Direct);
1868193326Sed    if (!Constructor)
1869193326Sed      RealDecl->setInvalidDecl();
1870193326Sed    else {
1871193326Sed      VDecl->setCXXDirectInitializer(true);
1872193326Sed      InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
1873193326Sed                                   (Expr**)Exprs.release(), NumExprs);
1874193326Sed    }
1875193326Sed    return;
1876193326Sed  }
1877193326Sed
1878193326Sed  if (NumExprs > 1) {
1879193326Sed    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1880193326Sed      << SourceRange(VDecl->getLocation(), RParenLoc);
1881193326Sed    RealDecl->setInvalidDecl();
1882193326Sed    return;
1883193326Sed  }
1884193326Sed
1885193326Sed  // Let clients know that initialization was done with a direct initializer.
1886193326Sed  VDecl->setCXXDirectInitializer(true);
1887193326Sed
1888193326Sed  assert(NumExprs == 1 && "Expected 1 expression");
1889193326Sed  // Set the init expression, handles conversions.
1890193326Sed  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1891193326Sed                       /*DirectInit=*/true);
1892193326Sed}
1893193326Sed
1894193326Sed/// PerformInitializationByConstructor - Perform initialization by
1895193326Sed/// constructor (C++ [dcl.init]p14), which may occur as part of
1896193326Sed/// direct-initialization or copy-initialization. We are initializing
1897193326Sed/// an object of type @p ClassType with the given arguments @p
1898193326Sed/// Args. @p Loc is the location in the source code where the
1899193326Sed/// initializer occurs (e.g., a declaration, member initializer,
1900193326Sed/// functional cast, etc.) while @p Range covers the whole
1901193326Sed/// initialization. @p InitEntity is the entity being initialized,
1902193326Sed/// which may by the name of a declaration or a type. @p Kind is the
1903193326Sed/// kind of initialization we're performing, which affects whether
1904193326Sed/// explicit constructors will be considered. When successful, returns
1905193326Sed/// the constructor that will be used to perform the initialization;
1906193326Sed/// when the initialization fails, emits a diagnostic and returns
1907193326Sed/// null.
1908193326SedCXXConstructorDecl *
1909193326SedSema::PerformInitializationByConstructor(QualType ClassType,
1910193326Sed                                         Expr **Args, unsigned NumArgs,
1911193326Sed                                         SourceLocation Loc, SourceRange Range,
1912193326Sed                                         DeclarationName InitEntity,
1913193326Sed                                         InitializationKind Kind) {
1914193326Sed  const RecordType *ClassRec = ClassType->getAsRecordType();
1915193326Sed  assert(ClassRec && "Can only initialize a class type here");
1916193326Sed
1917193326Sed  // C++ [dcl.init]p14:
1918193326Sed  //
1919193326Sed  //   If the initialization is direct-initialization, or if it is
1920193326Sed  //   copy-initialization where the cv-unqualified version of the
1921193326Sed  //   source type is the same class as, or a derived class of, the
1922193326Sed  //   class of the destination, constructors are considered. The
1923193326Sed  //   applicable constructors are enumerated (13.3.1.3), and the
1924193326Sed  //   best one is chosen through overload resolution (13.3). The
1925193326Sed  //   constructor so selected is called to initialize the object,
1926193326Sed  //   with the initializer expression(s) as its argument(s). If no
1927193326Sed  //   constructor applies, or the overload resolution is ambiguous,
1928193326Sed  //   the initialization is ill-formed.
1929193326Sed  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1930193326Sed  OverloadCandidateSet CandidateSet;
1931193326Sed
1932193326Sed  // Add constructors to the overload set.
1933193326Sed  DeclarationName ConstructorName
1934193326Sed    = Context.DeclarationNames.getCXXConstructorName(
1935193326Sed                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
1936193326Sed  DeclContext::lookup_const_iterator Con, ConEnd;
1937193326Sed  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(Context, ConstructorName);
1938193326Sed       Con != ConEnd; ++Con) {
1939193326Sed    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1940193326Sed    if ((Kind == IK_Direct) ||
1941193326Sed        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1942193326Sed        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1943193326Sed      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1944193326Sed  }
1945193326Sed
1946193326Sed  // FIXME: When we decide not to synthesize the implicitly-declared
1947193326Sed  // constructors, we'll need to make them appear here.
1948193326Sed
1949193326Sed  OverloadCandidateSet::iterator Best;
1950193326Sed  switch (BestViableFunction(CandidateSet, Best)) {
1951193326Sed  case OR_Success:
1952193326Sed    // We found a constructor. Return it.
1953193326Sed    return cast<CXXConstructorDecl>(Best->Function);
1954193326Sed
1955193326Sed  case OR_No_Viable_Function:
1956193326Sed    if (InitEntity)
1957193326Sed      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1958193326Sed        << InitEntity << Range;
1959193326Sed    else
1960193326Sed      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1961193326Sed        << ClassType << Range;
1962193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1963193326Sed    return 0;
1964193326Sed
1965193326Sed  case OR_Ambiguous:
1966193326Sed    if (InitEntity)
1967193326Sed      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1968193326Sed    else
1969193326Sed      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
1970193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1971193326Sed    return 0;
1972193326Sed
1973193326Sed  case OR_Deleted:
1974193326Sed    if (InitEntity)
1975193326Sed      Diag(Loc, diag::err_ovl_deleted_init)
1976193326Sed        << Best->Function->isDeleted()
1977193326Sed        << InitEntity << Range;
1978193326Sed    else
1979193326Sed      Diag(Loc, diag::err_ovl_deleted_init)
1980193326Sed        << Best->Function->isDeleted()
1981193326Sed        << InitEntity << Range;
1982193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1983193326Sed    return 0;
1984193326Sed  }
1985193326Sed
1986193326Sed  return 0;
1987193326Sed}
1988193326Sed
1989193326Sed/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1990193326Sed/// determine whether they are reference-related,
1991193326Sed/// reference-compatible, reference-compatible with added
1992193326Sed/// qualification, or incompatible, for use in C++ initialization by
1993193326Sed/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1994193326Sed/// type, and the first type (T1) is the pointee type of the reference
1995193326Sed/// type being initialized.
1996193326SedSema::ReferenceCompareResult
1997193326SedSema::CompareReferenceRelationship(QualType T1, QualType T2,
1998193326Sed                                   bool& DerivedToBase) {
1999193326Sed  assert(!T1->isReferenceType() &&
2000193326Sed    "T1 must be the pointee type of the reference type");
2001193326Sed  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2002193326Sed
2003193326Sed  T1 = Context.getCanonicalType(T1);
2004193326Sed  T2 = Context.getCanonicalType(T2);
2005193326Sed  QualType UnqualT1 = T1.getUnqualifiedType();
2006193326Sed  QualType UnqualT2 = T2.getUnqualifiedType();
2007193326Sed
2008193326Sed  // C++ [dcl.init.ref]p4:
2009193326Sed  //   Given types ���cv1 T1��� and ���cv2 T2,��� ���cv1 T1��� is
2010193326Sed  //   reference-related to ���cv2 T2��� if T1 is the same type as T2, or
2011193326Sed  //   T1 is a base class of T2.
2012193326Sed  if (UnqualT1 == UnqualT2)
2013193326Sed    DerivedToBase = false;
2014193326Sed  else if (IsDerivedFrom(UnqualT2, UnqualT1))
2015193326Sed    DerivedToBase = true;
2016193326Sed  else
2017193326Sed    return Ref_Incompatible;
2018193326Sed
2019193326Sed  // At this point, we know that T1 and T2 are reference-related (at
2020193326Sed  // least).
2021193326Sed
2022193326Sed  // C++ [dcl.init.ref]p4:
2023193326Sed  //   "cv1 T1��� is reference-compatible with ���cv2 T2��� if T1 is
2024193326Sed  //   reference-related to T2 and cv1 is the same cv-qualification
2025193326Sed  //   as, or greater cv-qualification than, cv2. For purposes of
2026193326Sed  //   overload resolution, cases for which cv1 is greater
2027193326Sed  //   cv-qualification than cv2 are identified as
2028193326Sed  //   reference-compatible with added qualification (see 13.3.3.2).
2029193326Sed  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2030193326Sed    return Ref_Compatible;
2031193326Sed  else if (T1.isMoreQualifiedThan(T2))
2032193326Sed    return Ref_Compatible_With_Added_Qualification;
2033193326Sed  else
2034193326Sed    return Ref_Related;
2035193326Sed}
2036193326Sed
2037193326Sed/// CheckReferenceInit - Check the initialization of a reference
2038193326Sed/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2039193326Sed/// the initializer (either a simple initializer or an initializer
2040193326Sed/// list), and DeclType is the type of the declaration. When ICS is
2041193326Sed/// non-null, this routine will compute the implicit conversion
2042193326Sed/// sequence according to C++ [over.ics.ref] and will not produce any
2043193326Sed/// diagnostics; when ICS is null, it will emit diagnostics when any
2044193326Sed/// errors are found. Either way, a return value of true indicates
2045193326Sed/// that there was a failure, a return value of false indicates that
2046193326Sed/// the reference initialization succeeded.
2047193326Sed///
2048193326Sed/// When @p SuppressUserConversions, user-defined conversions are
2049193326Sed/// suppressed.
2050193326Sed/// When @p AllowExplicit, we also permit explicit user-defined
2051193326Sed/// conversion functions.
2052193326Sed/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
2053193326Sedbool
2054193326SedSema::CheckReferenceInit(Expr *&Init, QualType DeclType,
2055193326Sed                         ImplicitConversionSequence *ICS,
2056193326Sed                         bool SuppressUserConversions,
2057193326Sed                         bool AllowExplicit, bool ForceRValue) {
2058193326Sed  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2059193326Sed
2060193326Sed  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2061193326Sed  QualType T2 = Init->getType();
2062193326Sed
2063193326Sed  // If the initializer is the address of an overloaded function, try
2064193326Sed  // to resolve the overloaded function. If all goes well, T2 is the
2065193326Sed  // type of the resulting function.
2066193326Sed  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
2067193326Sed    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2068193326Sed                                                          ICS != 0);
2069193326Sed    if (Fn) {
2070193326Sed      // Since we're performing this reference-initialization for
2071193326Sed      // real, update the initializer with the resulting function.
2072193326Sed      if (!ICS) {
2073193326Sed        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2074193326Sed          return true;
2075193326Sed
2076193326Sed        FixOverloadedFunctionReference(Init, Fn);
2077193326Sed      }
2078193326Sed
2079193326Sed      T2 = Fn->getType();
2080193326Sed    }
2081193326Sed  }
2082193326Sed
2083193326Sed  // Compute some basic properties of the types and the initializer.
2084193326Sed  bool isRValRef = DeclType->isRValueReferenceType();
2085193326Sed  bool DerivedToBase = false;
2086193326Sed  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2087193326Sed                                                  Init->isLvalue(Context);
2088193326Sed  ReferenceCompareResult RefRelationship
2089193326Sed    = CompareReferenceRelationship(T1, T2, DerivedToBase);
2090193326Sed
2091193326Sed  // Most paths end in a failed conversion.
2092193326Sed  if (ICS)
2093193326Sed    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
2094193326Sed
2095193326Sed  // C++ [dcl.init.ref]p5:
2096193326Sed  //   A reference to type ���cv1 T1��� is initialized by an expression
2097193326Sed  //   of type ���cv2 T2��� as follows:
2098193326Sed
2099193326Sed  //     -- If the initializer expression
2100193326Sed
2101193326Sed  // Rvalue references cannot bind to lvalues (N2812).
2102193326Sed  // There is absolutely no situation where they can. In particular, note that
2103193326Sed  // this is ill-formed, even if B has a user-defined conversion to A&&:
2104193326Sed  //   B b;
2105193326Sed  //   A&& r = b;
2106193326Sed  if (isRValRef && InitLvalue == Expr::LV_Valid) {
2107193326Sed    if (!ICS)
2108193326Sed      Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2109193326Sed        << Init->getSourceRange();
2110193326Sed    return true;
2111193326Sed  }
2112193326Sed
2113193326Sed  bool BindsDirectly = false;
2114193326Sed  //       -- is an lvalue (but is not a bit-field), and ���cv1 T1��� is
2115193326Sed  //          reference-compatible with ���cv2 T2,��� or
2116193326Sed  //
2117193326Sed  // Note that the bit-field check is skipped if we are just computing
2118193326Sed  // the implicit conversion sequence (C++ [over.best.ics]p2).
2119193326Sed  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
2120193326Sed      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2121193326Sed    BindsDirectly = true;
2122193326Sed
2123193326Sed    if (ICS) {
2124193326Sed      // C++ [over.ics.ref]p1:
2125193326Sed      //   When a parameter of reference type binds directly (8.5.3)
2126193326Sed      //   to an argument expression, the implicit conversion sequence
2127193326Sed      //   is the identity conversion, unless the argument expression
2128193326Sed      //   has a type that is a derived class of the parameter type,
2129193326Sed      //   in which case the implicit conversion sequence is a
2130193326Sed      //   derived-to-base Conversion (13.3.3.1).
2131193326Sed      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2132193326Sed      ICS->Standard.First = ICK_Identity;
2133193326Sed      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2134193326Sed      ICS->Standard.Third = ICK_Identity;
2135193326Sed      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2136193326Sed      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2137193326Sed      ICS->Standard.ReferenceBinding = true;
2138193326Sed      ICS->Standard.DirectBinding = true;
2139193326Sed      ICS->Standard.RRefBinding = false;
2140193326Sed      ICS->Standard.CopyConstructor = 0;
2141193326Sed
2142193326Sed      // Nothing more to do: the inaccessibility/ambiguity check for
2143193326Sed      // derived-to-base conversions is suppressed when we're
2144193326Sed      // computing the implicit conversion sequence (C++
2145193326Sed      // [over.best.ics]p2).
2146193326Sed      return false;
2147193326Sed    } else {
2148193326Sed      // Perform the conversion.
2149193326Sed      // FIXME: Binding to a subobject of the lvalue is going to require more
2150193326Sed      // AST annotation than this.
2151193326Sed      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2152193326Sed    }
2153193326Sed  }
2154193326Sed
2155193326Sed  //       -- has a class type (i.e., T2 is a class type) and can be
2156193326Sed  //          implicitly converted to an lvalue of type ���cv3 T3,���
2157193326Sed  //          where ���cv1 T1��� is reference-compatible with ���cv3 T3���
2158193326Sed  //          92) (this conversion is selected by enumerating the
2159193326Sed  //          applicable conversion functions (13.3.1.6) and choosing
2160193326Sed  //          the best one through overload resolution (13.3)),
2161193326Sed  if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
2162193326Sed    // FIXME: Look for conversions in base classes!
2163193326Sed    CXXRecordDecl *T2RecordDecl
2164193326Sed      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
2165193326Sed
2166193326Sed    OverloadCandidateSet CandidateSet;
2167193326Sed    OverloadedFunctionDecl *Conversions
2168193326Sed      = T2RecordDecl->getConversionFunctions();
2169193326Sed    for (OverloadedFunctionDecl::function_iterator Func
2170193326Sed           = Conversions->function_begin();
2171193326Sed         Func != Conversions->function_end(); ++Func) {
2172193326Sed      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2173193326Sed
2174193326Sed      // If the conversion function doesn't return a reference type,
2175193326Sed      // it can't be considered for this conversion.
2176193326Sed      if (Conv->getConversionType()->isLValueReferenceType() &&
2177193326Sed          (AllowExplicit || !Conv->isExplicit()))
2178193326Sed        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2179193326Sed    }
2180193326Sed
2181193326Sed    OverloadCandidateSet::iterator Best;
2182193326Sed    switch (BestViableFunction(CandidateSet, Best)) {
2183193326Sed    case OR_Success:
2184193326Sed      // This is a direct binding.
2185193326Sed      BindsDirectly = true;
2186193326Sed
2187193326Sed      if (ICS) {
2188193326Sed        // C++ [over.ics.ref]p1:
2189193326Sed        //
2190193326Sed        //   [...] If the parameter binds directly to the result of
2191193326Sed        //   applying a conversion function to the argument
2192193326Sed        //   expression, the implicit conversion sequence is a
2193193326Sed        //   user-defined conversion sequence (13.3.3.1.2), with the
2194193326Sed        //   second standard conversion sequence either an identity
2195193326Sed        //   conversion or, if the conversion function returns an
2196193326Sed        //   entity of a type that is a derived class of the parameter
2197193326Sed        //   type, a derived-to-base Conversion.
2198193326Sed        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2199193326Sed        ICS->UserDefined.Before = Best->Conversions[0].Standard;
2200193326Sed        ICS->UserDefined.After = Best->FinalConversion;
2201193326Sed        ICS->UserDefined.ConversionFunction = Best->Function;
2202193326Sed        assert(ICS->UserDefined.After.ReferenceBinding &&
2203193326Sed               ICS->UserDefined.After.DirectBinding &&
2204193326Sed               "Expected a direct reference binding!");
2205193326Sed        return false;
2206193326Sed      } else {
2207193326Sed        // Perform the conversion.
2208193326Sed        // FIXME: Binding to a subobject of the lvalue is going to require more
2209193326Sed        // AST annotation than this.
2210193326Sed        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2211193326Sed      }
2212193326Sed      break;
2213193326Sed
2214193326Sed    case OR_Ambiguous:
2215193326Sed      assert(false && "Ambiguous reference binding conversions not implemented.");
2216193326Sed      return true;
2217193326Sed
2218193326Sed    case OR_No_Viable_Function:
2219193326Sed    case OR_Deleted:
2220193326Sed      // There was no suitable conversion, or we found a deleted
2221193326Sed      // conversion; continue with other checks.
2222193326Sed      break;
2223193326Sed    }
2224193326Sed  }
2225193326Sed
2226193326Sed  if (BindsDirectly) {
2227193326Sed    // C++ [dcl.init.ref]p4:
2228193326Sed    //   [...] In all cases where the reference-related or
2229193326Sed    //   reference-compatible relationship of two types is used to
2230193326Sed    //   establish the validity of a reference binding, and T1 is a
2231193326Sed    //   base class of T2, a program that necessitates such a binding
2232193326Sed    //   is ill-formed if T1 is an inaccessible (clause 11) or
2233193326Sed    //   ambiguous (10.2) base class of T2.
2234193326Sed    //
2235193326Sed    // Note that we only check this condition when we're allowed to
2236193326Sed    // complain about errors, because we should not be checking for
2237193326Sed    // ambiguity (or inaccessibility) unless the reference binding
2238193326Sed    // actually happens.
2239193326Sed    if (DerivedToBase)
2240193326Sed      return CheckDerivedToBaseConversion(T2, T1,
2241193326Sed                                          Init->getSourceRange().getBegin(),
2242193326Sed                                          Init->getSourceRange());
2243193326Sed    else
2244193326Sed      return false;
2245193326Sed  }
2246193326Sed
2247193326Sed  //     -- Otherwise, the reference shall be to a non-volatile const
2248193326Sed  //        type (i.e., cv1 shall be const), or the reference shall be an
2249193326Sed  //        rvalue reference and the initializer expression shall be an rvalue.
2250193326Sed  if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
2251193326Sed    if (!ICS)
2252193326Sed      Diag(Init->getSourceRange().getBegin(),
2253193326Sed           diag::err_not_reference_to_const_init)
2254193326Sed        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2255193326Sed        << T2 << Init->getSourceRange();
2256193326Sed    return true;
2257193326Sed  }
2258193326Sed
2259193326Sed  //       -- If the initializer expression is an rvalue, with T2 a
2260193326Sed  //          class type, and ���cv1 T1��� is reference-compatible with
2261193326Sed  //          ���cv2 T2,��� the reference is bound in one of the
2262193326Sed  //          following ways (the choice is implementation-defined):
2263193326Sed  //
2264193326Sed  //          -- The reference is bound to the object represented by
2265193326Sed  //             the rvalue (see 3.10) or to a sub-object within that
2266193326Sed  //             object.
2267193326Sed  //
2268193326Sed  //          -- A temporary of type ���cv1 T2��� [sic] is created, and
2269193326Sed  //             a constructor is called to copy the entire rvalue
2270193326Sed  //             object into the temporary. The reference is bound to
2271193326Sed  //             the temporary or to a sub-object within the
2272193326Sed  //             temporary.
2273193326Sed  //
2274193326Sed  //          The constructor that would be used to make the copy
2275193326Sed  //          shall be callable whether or not the copy is actually
2276193326Sed  //          done.
2277193326Sed  //
2278193326Sed  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2279193326Sed  // freedom, so we will always take the first option and never build
2280193326Sed  // a temporary in this case. FIXME: We will, however, have to check
2281193326Sed  // for the presence of a copy constructor in C++98/03 mode.
2282193326Sed  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2283193326Sed      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2284193326Sed    if (ICS) {
2285193326Sed      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2286193326Sed      ICS->Standard.First = ICK_Identity;
2287193326Sed      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2288193326Sed      ICS->Standard.Third = ICK_Identity;
2289193326Sed      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2290193326Sed      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2291193326Sed      ICS->Standard.ReferenceBinding = true;
2292193326Sed      ICS->Standard.DirectBinding = false;
2293193326Sed      ICS->Standard.RRefBinding = isRValRef;
2294193326Sed      ICS->Standard.CopyConstructor = 0;
2295193326Sed    } else {
2296193326Sed      // FIXME: Binding to a subobject of the rvalue is going to require more
2297193326Sed      // AST annotation than this.
2298193326Sed      ImpCastExprToType(Init, T1, /*isLvalue=*/false);
2299193326Sed    }
2300193326Sed    return false;
2301193326Sed  }
2302193326Sed
2303193326Sed  //       -- Otherwise, a temporary of type ���cv1 T1��� is created and
2304193326Sed  //          initialized from the initializer expression using the
2305193326Sed  //          rules for a non-reference copy initialization (8.5). The
2306193326Sed  //          reference is then bound to the temporary. If T1 is
2307193326Sed  //          reference-related to T2, cv1 must be the same
2308193326Sed  //          cv-qualification as, or greater cv-qualification than,
2309193326Sed  //          cv2; otherwise, the program is ill-formed.
2310193326Sed  if (RefRelationship == Ref_Related) {
2311193326Sed    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2312193326Sed    // we would be reference-compatible or reference-compatible with
2313193326Sed    // added qualification. But that wasn't the case, so the reference
2314193326Sed    // initialization fails.
2315193326Sed    if (!ICS)
2316193326Sed      Diag(Init->getSourceRange().getBegin(),
2317193326Sed           diag::err_reference_init_drops_quals)
2318193326Sed        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2319193326Sed        << T2 << Init->getSourceRange();
2320193326Sed    return true;
2321193326Sed  }
2322193326Sed
2323193326Sed  // If at least one of the types is a class type, the types are not
2324193326Sed  // related, and we aren't allowed any user conversions, the
2325193326Sed  // reference binding fails. This case is important for breaking
2326193326Sed  // recursion, since TryImplicitConversion below will attempt to
2327193326Sed  // create a temporary through the use of a copy constructor.
2328193326Sed  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2329193326Sed      (T1->isRecordType() || T2->isRecordType())) {
2330193326Sed    if (!ICS)
2331193326Sed      Diag(Init->getSourceRange().getBegin(),
2332193326Sed           diag::err_typecheck_convert_incompatible)
2333193326Sed        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2334193326Sed    return true;
2335193326Sed  }
2336193326Sed
2337193326Sed  // Actually try to convert the initializer to T1.
2338193326Sed  if (ICS) {
2339193326Sed    // C++ [over.ics.ref]p2:
2340193326Sed    //
2341193326Sed    //   When a parameter of reference type is not bound directly to
2342193326Sed    //   an argument expression, the conversion sequence is the one
2343193326Sed    //   required to convert the argument expression to the
2344193326Sed    //   underlying type of the reference according to
2345193326Sed    //   13.3.3.1. Conceptually, this conversion sequence corresponds
2346193326Sed    //   to copy-initializing a temporary of the underlying type with
2347193326Sed    //   the argument expression. Any difference in top-level
2348193326Sed    //   cv-qualification is subsumed by the initialization itself
2349193326Sed    //   and does not constitute a conversion.
2350193326Sed    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2351193326Sed    // Of course, that's still a reference binding.
2352193326Sed    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2353193326Sed      ICS->Standard.ReferenceBinding = true;
2354193326Sed      ICS->Standard.RRefBinding = isRValRef;
2355193326Sed    } else if(ICS->ConversionKind ==
2356193326Sed              ImplicitConversionSequence::UserDefinedConversion) {
2357193326Sed      ICS->UserDefined.After.ReferenceBinding = true;
2358193326Sed      ICS->UserDefined.After.RRefBinding = isRValRef;
2359193326Sed    }
2360193326Sed    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2361193326Sed  } else {
2362193326Sed    return PerformImplicitConversion(Init, T1, "initializing");
2363193326Sed  }
2364193326Sed}
2365193326Sed
2366193326Sed/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2367193326Sed/// of this overloaded operator is well-formed. If so, returns false;
2368193326Sed/// otherwise, emits appropriate diagnostics and returns true.
2369193326Sedbool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2370193326Sed  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2371193326Sed         "Expected an overloaded operator declaration");
2372193326Sed
2373193326Sed  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2374193326Sed
2375193326Sed  // C++ [over.oper]p5:
2376193326Sed  //   The allocation and deallocation functions, operator new,
2377193326Sed  //   operator new[], operator delete and operator delete[], are
2378193326Sed  //   described completely in 3.7.3. The attributes and restrictions
2379193326Sed  //   found in the rest of this subclause do not apply to them unless
2380193326Sed  //   explicitly stated in 3.7.3.
2381193326Sed  // FIXME: Write a separate routine for checking this. For now, just allow it.
2382193326Sed  if (Op == OO_New || Op == OO_Array_New ||
2383193326Sed      Op == OO_Delete || Op == OO_Array_Delete)
2384193326Sed    return false;
2385193326Sed
2386193326Sed  // C++ [over.oper]p6:
2387193326Sed  //   An operator function shall either be a non-static member
2388193326Sed  //   function or be a non-member function and have at least one
2389193326Sed  //   parameter whose type is a class, a reference to a class, an
2390193326Sed  //   enumeration, or a reference to an enumeration.
2391193326Sed  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2392193326Sed    if (MethodDecl->isStatic())
2393193326Sed      return Diag(FnDecl->getLocation(),
2394193326Sed                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2395193326Sed  } else {
2396193326Sed    bool ClassOrEnumParam = false;
2397193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2398193326Sed                                   ParamEnd = FnDecl->param_end();
2399193326Sed         Param != ParamEnd; ++Param) {
2400193326Sed      QualType ParamType = (*Param)->getType().getNonReferenceType();
2401193326Sed      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2402193326Sed        ClassOrEnumParam = true;
2403193326Sed        break;
2404193326Sed      }
2405193326Sed    }
2406193326Sed
2407193326Sed    if (!ClassOrEnumParam)
2408193326Sed      return Diag(FnDecl->getLocation(),
2409193326Sed                  diag::err_operator_overload_needs_class_or_enum)
2410193326Sed        << FnDecl->getDeclName();
2411193326Sed  }
2412193326Sed
2413193326Sed  // C++ [over.oper]p8:
2414193326Sed  //   An operator function cannot have default arguments (8.3.6),
2415193326Sed  //   except where explicitly stated below.
2416193326Sed  //
2417193326Sed  // Only the function-call operator allows default arguments
2418193326Sed  // (C++ [over.call]p1).
2419193326Sed  if (Op != OO_Call) {
2420193326Sed    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2421193326Sed         Param != FnDecl->param_end(); ++Param) {
2422193326Sed      if ((*Param)->hasUnparsedDefaultArg())
2423193326Sed        return Diag((*Param)->getLocation(),
2424193326Sed                    diag::err_operator_overload_default_arg)
2425193326Sed          << FnDecl->getDeclName();
2426193326Sed      else if (Expr *DefArg = (*Param)->getDefaultArg())
2427193326Sed        return Diag((*Param)->getLocation(),
2428193326Sed                    diag::err_operator_overload_default_arg)
2429193326Sed          << FnDecl->getDeclName() << DefArg->getSourceRange();
2430193326Sed    }
2431193326Sed  }
2432193326Sed
2433193326Sed  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2434193326Sed    { false, false, false }
2435193326Sed#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2436193326Sed    , { Unary, Binary, MemberOnly }
2437193326Sed#include "clang/Basic/OperatorKinds.def"
2438193326Sed  };
2439193326Sed
2440193326Sed  bool CanBeUnaryOperator = OperatorUses[Op][0];
2441193326Sed  bool CanBeBinaryOperator = OperatorUses[Op][1];
2442193326Sed  bool MustBeMemberOperator = OperatorUses[Op][2];
2443193326Sed
2444193326Sed  // C++ [over.oper]p8:
2445193326Sed  //   [...] Operator functions cannot have more or fewer parameters
2446193326Sed  //   than the number required for the corresponding operator, as
2447193326Sed  //   described in the rest of this subclause.
2448193326Sed  unsigned NumParams = FnDecl->getNumParams()
2449193326Sed                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2450193326Sed  if (Op != OO_Call &&
2451193326Sed      ((NumParams == 1 && !CanBeUnaryOperator) ||
2452193326Sed       (NumParams == 2 && !CanBeBinaryOperator) ||
2453193326Sed       (NumParams < 1) || (NumParams > 2))) {
2454193326Sed    // We have the wrong number of parameters.
2455193326Sed    unsigned ErrorKind;
2456193326Sed    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2457193326Sed      ErrorKind = 2;  // 2 -> unary or binary.
2458193326Sed    } else if (CanBeUnaryOperator) {
2459193326Sed      ErrorKind = 0;  // 0 -> unary
2460193326Sed    } else {
2461193326Sed      assert(CanBeBinaryOperator &&
2462193326Sed             "All non-call overloaded operators are unary or binary!");
2463193326Sed      ErrorKind = 1;  // 1 -> binary
2464193326Sed    }
2465193326Sed
2466193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2467193326Sed      << FnDecl->getDeclName() << NumParams << ErrorKind;
2468193326Sed  }
2469193326Sed
2470193326Sed  // Overloaded operators other than operator() cannot be variadic.
2471193326Sed  if (Op != OO_Call &&
2472193326Sed      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2473193326Sed    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2474193326Sed      << FnDecl->getDeclName();
2475193326Sed  }
2476193326Sed
2477193326Sed  // Some operators must be non-static member functions.
2478193326Sed  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2479193326Sed    return Diag(FnDecl->getLocation(),
2480193326Sed                diag::err_operator_overload_must_be_member)
2481193326Sed      << FnDecl->getDeclName();
2482193326Sed  }
2483193326Sed
2484193326Sed  // C++ [over.inc]p1:
2485193326Sed  //   The user-defined function called operator++ implements the
2486193326Sed  //   prefix and postfix ++ operator. If this function is a member
2487193326Sed  //   function with no parameters, or a non-member function with one
2488193326Sed  //   parameter of class or enumeration type, it defines the prefix
2489193326Sed  //   increment operator ++ for objects of that type. If the function
2490193326Sed  //   is a member function with one parameter (which shall be of type
2491193326Sed  //   int) or a non-member function with two parameters (the second
2492193326Sed  //   of which shall be of type int), it defines the postfix
2493193326Sed  //   increment operator ++ for objects of that type.
2494193326Sed  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2495193326Sed    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2496193326Sed    bool ParamIsInt = false;
2497193326Sed    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2498193326Sed      ParamIsInt = BT->getKind() == BuiltinType::Int;
2499193326Sed
2500193326Sed    if (!ParamIsInt)
2501193326Sed      return Diag(LastParam->getLocation(),
2502193326Sed                  diag::err_operator_overload_post_incdec_must_be_int)
2503193326Sed        << LastParam->getType() << (Op == OO_MinusMinus);
2504193326Sed  }
2505193326Sed
2506193326Sed  // Notify the class if it got an assignment operator.
2507193326Sed  if (Op == OO_Equal) {
2508193326Sed    // Would have returned earlier otherwise.
2509193326Sed    assert(isa<CXXMethodDecl>(FnDecl) &&
2510193326Sed      "Overloaded = not member, but not filtered.");
2511193326Sed    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2512193326Sed    Method->getParent()->addedAssignmentOperator(Context, Method);
2513193326Sed  }
2514193326Sed
2515193326Sed  return false;
2516193326Sed}
2517193326Sed
2518193326Sed/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2519193326Sed/// linkage specification, including the language and (if present)
2520193326Sed/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2521193326Sed/// the location of the language string literal, which is provided
2522193326Sed/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2523193326Sed/// the '{' brace. Otherwise, this linkage specification does not
2524193326Sed/// have any braces.
2525193326SedSema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2526193326Sed                                                     SourceLocation ExternLoc,
2527193326Sed                                                     SourceLocation LangLoc,
2528193326Sed                                                     const char *Lang,
2529193326Sed                                                     unsigned StrSize,
2530193326Sed                                                     SourceLocation LBraceLoc) {
2531193326Sed  LinkageSpecDecl::LanguageIDs Language;
2532193326Sed  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2533193326Sed    Language = LinkageSpecDecl::lang_c;
2534193326Sed  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2535193326Sed    Language = LinkageSpecDecl::lang_cxx;
2536193326Sed  else {
2537193326Sed    Diag(LangLoc, diag::err_bad_language);
2538193326Sed    return DeclPtrTy();
2539193326Sed  }
2540193326Sed
2541193326Sed  // FIXME: Add all the various semantics of linkage specifications
2542193326Sed
2543193326Sed  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2544193326Sed                                               LangLoc, Language,
2545193326Sed                                               LBraceLoc.isValid());
2546193326Sed  CurContext->addDecl(Context, D);
2547193326Sed  PushDeclContext(S, D);
2548193326Sed  return DeclPtrTy::make(D);
2549193326Sed}
2550193326Sed
2551193326Sed/// ActOnFinishLinkageSpecification - Completely the definition of
2552193326Sed/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2553193326Sed/// valid, it's the position of the closing '}' brace in a linkage
2554193326Sed/// specification that uses braces.
2555193326SedSema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2556193326Sed                                                      DeclPtrTy LinkageSpec,
2557193326Sed                                                      SourceLocation RBraceLoc) {
2558193326Sed  if (LinkageSpec)
2559193326Sed    PopDeclContext();
2560193326Sed  return LinkageSpec;
2561193326Sed}
2562193326Sed
2563193326Sed/// \brief Perform semantic analysis for the variable declaration that
2564193326Sed/// occurs within a C++ catch clause, returning the newly-created
2565193326Sed/// variable.
2566193326SedVarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2567193326Sed                                         IdentifierInfo *Name,
2568193326Sed                                         SourceLocation Loc,
2569193326Sed                                         SourceRange Range) {
2570193326Sed  bool Invalid = false;
2571193326Sed
2572193326Sed  // Arrays and functions decay.
2573193326Sed  if (ExDeclType->isArrayType())
2574193326Sed    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2575193326Sed  else if (ExDeclType->isFunctionType())
2576193326Sed    ExDeclType = Context.getPointerType(ExDeclType);
2577193326Sed
2578193326Sed  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2579193326Sed  // The exception-declaration shall not denote a pointer or reference to an
2580193326Sed  // incomplete type, other than [cv] void*.
2581193326Sed  // N2844 forbids rvalue references.
2582193326Sed  if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
2583193326Sed    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
2584193326Sed    Invalid = true;
2585193326Sed  }
2586193326Sed
2587193326Sed  QualType BaseType = ExDeclType;
2588193326Sed  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2589193326Sed  unsigned DK = diag::err_catch_incomplete;
2590193326Sed  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2591193326Sed    BaseType = Ptr->getPointeeType();
2592193326Sed    Mode = 1;
2593193326Sed    DK = diag::err_catch_incomplete_ptr;
2594193326Sed  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2595193326Sed    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
2596193326Sed    BaseType = Ref->getPointeeType();
2597193326Sed    Mode = 2;
2598193326Sed    DK = diag::err_catch_incomplete_ref;
2599193326Sed  }
2600193326Sed  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
2601193326Sed      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
2602193326Sed    Invalid = true;
2603193326Sed
2604193326Sed  if (!Invalid && !ExDeclType->isDependentType() &&
2605193326Sed      RequireNonAbstractType(Loc, ExDeclType,
2606193326Sed                             diag::err_abstract_type_in_decl,
2607193326Sed                             AbstractVariableType))
2608193326Sed    Invalid = true;
2609193326Sed
2610193326Sed  // FIXME: Need to test for ability to copy-construct and destroy the
2611193326Sed  // exception variable.
2612193326Sed
2613193326Sed  // FIXME: Need to check for abstract classes.
2614193326Sed
2615193326Sed  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
2616193326Sed                                    Name, ExDeclType, VarDecl::None,
2617193326Sed                                    Range.getBegin());
2618193326Sed
2619193326Sed  if (Invalid)
2620193326Sed    ExDecl->setInvalidDecl();
2621193326Sed
2622193326Sed  return ExDecl;
2623193326Sed}
2624193326Sed
2625193326Sed/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2626193326Sed/// handler.
2627193326SedSema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
2628193326Sed  QualType ExDeclType = GetTypeForDeclarator(D, S);
2629193326Sed
2630193326Sed  bool Invalid = D.isInvalidType();
2631193326Sed  IdentifierInfo *II = D.getIdentifier();
2632193326Sed  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2633193326Sed    // The scope should be freshly made just for us. There is just no way
2634193326Sed    // it contains any previous declaration.
2635193326Sed    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
2636193326Sed    if (PrevDecl->isTemplateParameter()) {
2637193326Sed      // Maybe we will complain about the shadowed template parameter.
2638193326Sed      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2639193326Sed    }
2640193326Sed  }
2641193326Sed
2642193326Sed  if (D.getCXXScopeSpec().isSet() && !Invalid) {
2643193326Sed    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2644193326Sed      << D.getCXXScopeSpec().getRange();
2645193326Sed    Invalid = true;
2646193326Sed  }
2647193326Sed
2648193326Sed  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
2649193326Sed                                              D.getIdentifier(),
2650193326Sed                                              D.getIdentifierLoc(),
2651193326Sed                                            D.getDeclSpec().getSourceRange());
2652193326Sed
2653193326Sed  if (Invalid)
2654193326Sed    ExDecl->setInvalidDecl();
2655193326Sed
2656193326Sed  // Add the exception declaration into this scope.
2657193326Sed  if (II)
2658193326Sed    PushOnScopeChains(ExDecl, S);
2659193326Sed  else
2660193326Sed    CurContext->addDecl(Context, ExDecl);
2661193326Sed
2662193326Sed  ProcessDeclAttributes(ExDecl, D);
2663193326Sed  return DeclPtrTy::make(ExDecl);
2664193326Sed}
2665193326Sed
2666193326SedSema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2667193326Sed                                                   ExprArg assertexpr,
2668193326Sed                                                   ExprArg assertmessageexpr) {
2669193326Sed  Expr *AssertExpr = (Expr *)assertexpr.get();
2670193326Sed  StringLiteral *AssertMessage =
2671193326Sed    cast<StringLiteral>((Expr *)assertmessageexpr.get());
2672193326Sed
2673193326Sed  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2674193326Sed    llvm::APSInt Value(32);
2675193326Sed    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2676193326Sed      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2677193326Sed        AssertExpr->getSourceRange();
2678193326Sed      return DeclPtrTy();
2679193326Sed    }
2680193326Sed
2681193326Sed    if (Value == 0) {
2682193326Sed      std::string str(AssertMessage->getStrData(),
2683193326Sed                      AssertMessage->getByteLength());
2684193326Sed      Diag(AssertLoc, diag::err_static_assert_failed)
2685193326Sed        << str << AssertExpr->getSourceRange();
2686193326Sed    }
2687193326Sed  }
2688193326Sed
2689193326Sed  assertexpr.release();
2690193326Sed  assertmessageexpr.release();
2691193326Sed  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2692193326Sed                                        AssertExpr, AssertMessage);
2693193326Sed
2694193326Sed  CurContext->addDecl(Context, Decl);
2695193326Sed  return DeclPtrTy::make(Decl);
2696193326Sed}
2697193326Sed
2698193326Sedbool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
2699193326Sed  if (!(S->getFlags() & Scope::ClassScope)) {
2700193326Sed    Diag(FriendLoc, diag::err_friend_decl_outside_class);
2701193326Sed    return true;
2702193326Sed  }
2703193326Sed
2704193326Sed  return false;
2705193326Sed}
2706193326Sed
2707193326Sedvoid Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
2708193326Sed  Decl *Dcl = dcl.getAs<Decl>();
2709193326Sed  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
2710193326Sed  if (!Fn) {
2711193326Sed    Diag(DelLoc, diag::err_deleted_non_function);
2712193326Sed    return;
2713193326Sed  }
2714193326Sed  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
2715193326Sed    Diag(DelLoc, diag::err_deleted_decl_not_first);
2716193326Sed    Diag(Prev->getLocation(), diag::note_previous_declaration);
2717193326Sed    // If the declaration wasn't the first, we delete the function anyway for
2718193326Sed    // recovery.
2719193326Sed  }
2720193326Sed  Fn->setDeleted();
2721193326Sed}
2722193326Sed
2723193326Sedstatic void SearchForReturnInStmt(Sema &Self, Stmt *S) {
2724193326Sed  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
2725193326Sed       ++CI) {
2726193326Sed    Stmt *SubStmt = *CI;
2727193326Sed    if (!SubStmt)
2728193326Sed      continue;
2729193326Sed    if (isa<ReturnStmt>(SubStmt))
2730193326Sed      Self.Diag(SubStmt->getSourceRange().getBegin(),
2731193326Sed           diag::err_return_in_constructor_handler);
2732193326Sed    if (!isa<Expr>(SubStmt))
2733193326Sed      SearchForReturnInStmt(Self, SubStmt);
2734193326Sed  }
2735193326Sed}
2736193326Sed
2737193326Sedvoid Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
2738193326Sed  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
2739193326Sed    CXXCatchStmt *Handler = TryBlock->getHandler(I);
2740193326Sed    SearchForReturnInStmt(*this, Handler);
2741193326Sed  }
2742193326Sed}
2743193326Sed
2744193326Sedbool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
2745193326Sed                                             const CXXMethodDecl *Old) {
2746193326Sed  QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
2747193326Sed  QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
2748193326Sed
2749193326Sed  QualType CNewTy = Context.getCanonicalType(NewTy);
2750193326Sed  QualType COldTy = Context.getCanonicalType(OldTy);
2751193326Sed
2752193326Sed  if (CNewTy == COldTy &&
2753193326Sed      CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
2754193326Sed    return false;
2755193326Sed
2756193326Sed  // Check if the return types are covariant
2757193326Sed  QualType NewClassTy, OldClassTy;
2758193326Sed
2759193326Sed  /// Both types must be pointers or references to classes.
2760193326Sed  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
2761193326Sed    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
2762193326Sed      NewClassTy = NewPT->getPointeeType();
2763193326Sed      OldClassTy = OldPT->getPointeeType();
2764193326Sed    }
2765193326Sed  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
2766193326Sed    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
2767193326Sed      NewClassTy = NewRT->getPointeeType();
2768193326Sed      OldClassTy = OldRT->getPointeeType();
2769193326Sed    }
2770193326Sed  }
2771193326Sed
2772193326Sed  // The return types aren't either both pointers or references to a class type.
2773193326Sed  if (NewClassTy.isNull()) {
2774193326Sed    Diag(New->getLocation(),
2775193326Sed         diag::err_different_return_type_for_overriding_virtual_function)
2776193326Sed      << New->getDeclName() << NewTy << OldTy;
2777193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2778193326Sed
2779193326Sed    return true;
2780193326Sed  }
2781193326Sed
2782193326Sed  if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
2783193326Sed    // Check if the new class derives from the old class.
2784193326Sed    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
2785193326Sed      Diag(New->getLocation(),
2786193326Sed           diag::err_covariant_return_not_derived)
2787193326Sed      << New->getDeclName() << NewTy << OldTy;
2788193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2789193326Sed      return true;
2790193326Sed    }
2791193326Sed
2792193326Sed    // Check if we the conversion from derived to base is valid.
2793193326Sed    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
2794193326Sed                      diag::err_covariant_return_inaccessible_base,
2795193326Sed                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
2796193326Sed                      // FIXME: Should this point to the return type?
2797193326Sed                      New->getLocation(), SourceRange(), New->getDeclName())) {
2798193326Sed      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2799193326Sed      return true;
2800193326Sed    }
2801193326Sed  }
2802193326Sed
2803193326Sed  // The qualifiers of the return types must be the same.
2804193326Sed  if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
2805193326Sed    Diag(New->getLocation(),
2806193326Sed         diag::err_covariant_return_type_different_qualifications)
2807193326Sed    << New->getDeclName() << NewTy << OldTy;
2808193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2809193326Sed    return true;
2810193326Sed  };
2811193326Sed
2812193326Sed
2813193326Sed  // The new class type must have the same or less qualifiers as the old type.
2814193326Sed  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
2815193326Sed    Diag(New->getLocation(),
2816193326Sed         diag::err_covariant_return_type_class_type_more_qualified)
2817193326Sed    << New->getDeclName() << NewTy << OldTy;
2818193326Sed    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2819193326Sed    return true;
2820193326Sed  };
2821193326Sed
2822193326Sed  return false;
2823193326Sed}
2824