DeclCXX.cpp revision 1d110e05e0ff48c1c7a483d6b7fd094cdf28316a
1//===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ related Decl classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Decl Allocation/Deallocation Method Implementations
26//===----------------------------------------------------------------------===//
27
28CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
29  : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
30    UserDeclaredCopyAssignment(false), UserDeclaredDestructor(false),
31    Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
32    Abstract(false), HasTrivialConstructor(true),
33    HasTrivialCopyConstructor(true), HasTrivialCopyAssignment(true),
34    HasTrivialDestructor(true), ComputedVisibleConversions(false),
35    Bases(0), NumBases(0), VBases(0), NumVBases(0),
36    Definition(D), FirstFriend(0) {
37}
38
39CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
40                             SourceLocation L, IdentifierInfo *Id,
41                             CXXRecordDecl *PrevDecl,
42                             SourceLocation TKL)
43  : RecordDecl(K, TK, DC, L, Id, PrevDecl, TKL),
44    DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
45    TemplateOrInstantiation() { }
46
47CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
48                                     SourceLocation L, IdentifierInfo *Id,
49                                     SourceLocation TKL,
50                                     CXXRecordDecl* PrevDecl,
51                                     bool DelayTypeCreation) {
52  CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id,
53                                           PrevDecl, TKL);
54
55  // FIXME: DelayTypeCreation seems like such a hack
56  if (!DelayTypeCreation)
57    C.getTypeDeclType(R, PrevDecl);
58  return R;
59}
60
61CXXRecordDecl::~CXXRecordDecl() {
62}
63
64void CXXRecordDecl::Destroy(ASTContext &C) {
65  if (data().Definition == this) {
66    C.Deallocate(data().Bases);
67    C.Deallocate(data().VBases);
68    C.Deallocate(&data());
69  }
70  this->RecordDecl::Destroy(C);
71}
72
73void
74CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
75                        unsigned NumBases) {
76  ASTContext &C = getASTContext();
77
78  // C++ [dcl.init.aggr]p1:
79  //   An aggregate is an array or a class (clause 9) with [...]
80  //   no base classes [...].
81  data().Aggregate = false;
82
83  if (data().Bases)
84    C.Deallocate(data().Bases);
85
86  // The set of seen virtual base types.
87  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
88
89  // The virtual bases of this class.
90  llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
91
92  data().Bases = new(C) CXXBaseSpecifier [NumBases];
93  data().NumBases = NumBases;
94  for (unsigned i = 0; i < NumBases; ++i) {
95    data().Bases[i] = *Bases[i];
96    // Keep track of inherited vbases for this base class.
97    const CXXBaseSpecifier *Base = Bases[i];
98    QualType BaseType = Base->getType();
99    // Skip dependent types; we can't do any checking on them now.
100    if (BaseType->isDependentType())
101      continue;
102    CXXRecordDecl *BaseClassDecl
103      = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
104
105    // Now go through all virtual bases of this base and add them.
106    for (CXXRecordDecl::base_class_iterator VBase =
107          BaseClassDecl->vbases_begin(),
108         E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
109      // Add this base if it's not already in the list.
110      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
111        VBases.push_back(VBase);
112    }
113
114    if (Base->isVirtual()) {
115      // Add this base if it's not already in the list.
116      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
117          VBases.push_back(Base);
118    }
119
120  }
121
122  if (VBases.empty())
123    return;
124
125  // Create base specifier for any direct or indirect virtual bases.
126  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
127  data().NumVBases = VBases.size();
128  for (int I = 0, E = VBases.size(); I != E; ++I) {
129    QualType VBaseType = VBases[I]->getType();
130
131    // Skip dependent types; we can't do any checking on them now.
132    if (VBaseType->isDependentType())
133      continue;
134
135    CXXRecordDecl *VBaseClassDecl
136      = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
137
138    data().VBases[I] =
139      CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true,
140                       VBaseClassDecl->getTagKind() == TTK_Class,
141                       VBases[I]->getAccessSpecifier(), VBaseType);
142  }
143}
144
145/// Callback function for CXXRecordDecl::forallBases that acknowledges
146/// that it saw a base class.
147static bool SawBase(const CXXRecordDecl *, void *) {
148  return true;
149}
150
151bool CXXRecordDecl::hasAnyDependentBases() const {
152  if (!isDependentContext())
153    return false;
154
155  return !forallBases(SawBase, 0);
156}
157
158bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const {
159  return getCopyConstructor(Context, Qualifiers::Const) != 0;
160}
161
162CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context,
163                                                      unsigned TypeQuals) const{
164  QualType ClassType
165    = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
166  DeclarationName ConstructorName
167    = Context.DeclarationNames.getCXXConstructorName(
168                                          Context.getCanonicalType(ClassType));
169  unsigned FoundTQs;
170  DeclContext::lookup_const_iterator Con, ConEnd;
171  for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
172       Con != ConEnd; ++Con) {
173    // C++ [class.copy]p2:
174    //   A non-template constructor for class X is a copy constructor if [...]
175    if (isa<FunctionTemplateDecl>(*Con))
176      continue;
177
178    if (cast<CXXConstructorDecl>(*Con)->isCopyConstructor(FoundTQs)) {
179      if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
180          (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
181        return cast<CXXConstructorDecl>(*Con);
182
183    }
184  }
185  return 0;
186}
187
188bool CXXRecordDecl::hasConstCopyAssignment(ASTContext &Context,
189                                           const CXXMethodDecl *& MD) const {
190  QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
191    const_cast<CXXRecordDecl*>(this)));
192  DeclarationName OpName =Context.DeclarationNames.getCXXOperatorName(OO_Equal);
193
194  DeclContext::lookup_const_iterator Op, OpEnd;
195  for (llvm::tie(Op, OpEnd) = this->lookup(OpName);
196       Op != OpEnd; ++Op) {
197    // C++ [class.copy]p9:
198    //   A user-declared copy assignment operator is a non-static non-template
199    //   member function of class X with exactly one parameter of type X, X&,
200    //   const X&, volatile X& or const volatile X&.
201    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
202    if (!Method)
203      continue;
204
205    if (Method->isStatic())
206      continue;
207    if (Method->getPrimaryTemplate())
208      continue;
209    const FunctionProtoType *FnType =
210      Method->getType()->getAs<FunctionProtoType>();
211    assert(FnType && "Overloaded operator has no prototype.");
212    // Don't assert on this; an invalid decl might have been left in the AST.
213    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
214      continue;
215    bool AcceptsConst = true;
216    QualType ArgType = FnType->getArgType(0);
217    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
218      ArgType = Ref->getPointeeType();
219      // Is it a non-const lvalue reference?
220      if (!ArgType.isConstQualified())
221        AcceptsConst = false;
222    }
223    if (!Context.hasSameUnqualifiedType(ArgType, ClassType))
224      continue;
225    MD = Method;
226    // We have a single argument of type cv X or cv X&, i.e. we've found the
227    // copy assignment operator. Return whether it accepts const arguments.
228    return AcceptsConst;
229  }
230  assert(isInvalidDecl() &&
231         "No copy assignment operator declared in valid code.");
232  return false;
233}
234
235void
236CXXRecordDecl::addedConstructor(ASTContext &Context,
237                                CXXConstructorDecl *ConDecl) {
238  assert(!ConDecl->isImplicit() && "addedConstructor - not for implicit decl");
239  // Note that we have a user-declared constructor.
240  data().UserDeclaredConstructor = true;
241
242  // C++ [dcl.init.aggr]p1:
243  //   An aggregate is an array or a class (clause 9) with no
244  //   user-declared constructors (12.1) [...].
245  data().Aggregate = false;
246
247  // C++ [class]p4:
248  //   A POD-struct is an aggregate class [...]
249  data().PlainOldData = false;
250
251  // C++ [class.ctor]p5:
252  //   A constructor is trivial if it is an implicitly-declared default
253  //   constructor.
254  // FIXME: C++0x: don't do this for "= default" default constructors.
255  data().HasTrivialConstructor = false;
256
257  // Note when we have a user-declared copy constructor, which will
258  // suppress the implicit declaration of a copy constructor.
259  if (ConDecl->isCopyConstructor()) {
260    data().UserDeclaredCopyConstructor = true;
261
262    // C++ [class.copy]p6:
263    //   A copy constructor is trivial if it is implicitly declared.
264    // FIXME: C++0x: don't do this for "= default" copy constructors.
265    data().HasTrivialCopyConstructor = false;
266  }
267}
268
269void CXXRecordDecl::addedAssignmentOperator(ASTContext &Context,
270                                            CXXMethodDecl *OpDecl) {
271  // We're interested specifically in copy assignment operators.
272  const FunctionProtoType *FnType = OpDecl->getType()->getAs<FunctionProtoType>();
273  assert(FnType && "Overloaded operator has no proto function type.");
274  assert(FnType->getNumArgs() == 1 && !FnType->isVariadic());
275
276  // Copy assignment operators must be non-templates.
277  if (OpDecl->getPrimaryTemplate() || OpDecl->getDescribedFunctionTemplate())
278    return;
279
280  QualType ArgType = FnType->getArgType(0);
281  if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>())
282    ArgType = Ref->getPointeeType();
283
284  ArgType = ArgType.getUnqualifiedType();
285  QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
286    const_cast<CXXRecordDecl*>(this)));
287
288  if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
289    return;
290
291  // This is a copy assignment operator.
292  // Note on the decl that it is a copy assignment operator.
293  OpDecl->setCopyAssignment(true);
294
295  // Suppress the implicit declaration of a copy constructor.
296  data().UserDeclaredCopyAssignment = true;
297
298  // C++ [class.copy]p11:
299  //   A copy assignment operator is trivial if it is implicitly declared.
300  // FIXME: C++0x: don't do this for "= default" copy operators.
301  data().HasTrivialCopyAssignment = false;
302
303  // C++ [class]p4:
304  //   A POD-struct is an aggregate class that [...] has no user-defined copy
305  //   assignment operator [...].
306  data().PlainOldData = false;
307}
308
309static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
310  QualType T;
311  if (isa<UsingShadowDecl>(Conv))
312    Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
313  if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
314    T = ConvTemp->getTemplatedDecl()->getResultType();
315  else
316    T = cast<CXXConversionDecl>(Conv)->getConversionType();
317  return Context.getCanonicalType(T);
318}
319
320/// Collect the visible conversions of a base class.
321///
322/// \param Base a base class of the class we're considering
323/// \param InVirtual whether this base class is a virtual base (or a base
324///   of a virtual base)
325/// \param Access the access along the inheritance path to this base
326/// \param ParentHiddenTypes the conversions provided by the inheritors
327///   of this base
328/// \param Output the set to which to add conversions from non-virtual bases
329/// \param VOutput the set to which to add conversions from virtual bases
330/// \param HiddenVBaseCs the set of conversions which were hidden in a
331///   virtual base along some inheritance path
332static void CollectVisibleConversions(ASTContext &Context,
333                                      CXXRecordDecl *Record,
334                                      bool InVirtual,
335                                      AccessSpecifier Access,
336                  const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
337                                      UnresolvedSetImpl &Output,
338                                      UnresolvedSetImpl &VOutput,
339                           llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
340  // The set of types which have conversions in this class or its
341  // subclasses.  As an optimization, we don't copy the derived set
342  // unless it might change.
343  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
344  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
345
346  // Collect the direct conversions and figure out which conversions
347  // will be hidden in the subclasses.
348  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
349  if (!Cs.empty()) {
350    HiddenTypesBuffer = ParentHiddenTypes;
351    HiddenTypes = &HiddenTypesBuffer;
352
353    for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
354      bool Hidden =
355        !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
356
357      // If this conversion is hidden and we're in a virtual base,
358      // remember that it's hidden along some inheritance path.
359      if (Hidden && InVirtual)
360        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
361
362      // If this conversion isn't hidden, add it to the appropriate output.
363      else if (!Hidden) {
364        AccessSpecifier IAccess
365          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
366
367        if (InVirtual)
368          VOutput.addDecl(I.getDecl(), IAccess);
369        else
370          Output.addDecl(I.getDecl(), IAccess);
371      }
372    }
373  }
374
375  // Collect information recursively from any base classes.
376  for (CXXRecordDecl::base_class_iterator
377         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
378    const RecordType *RT = I->getType()->getAs<RecordType>();
379    if (!RT) continue;
380
381    AccessSpecifier BaseAccess
382      = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
383    bool BaseInVirtual = InVirtual || I->isVirtual();
384
385    CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
386    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
387                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
388  }
389}
390
391/// Collect the visible conversions of a class.
392///
393/// This would be extremely straightforward if it weren't for virtual
394/// bases.  It might be worth special-casing that, really.
395static void CollectVisibleConversions(ASTContext &Context,
396                                      CXXRecordDecl *Record,
397                                      UnresolvedSetImpl &Output) {
398  // The collection of all conversions in virtual bases that we've
399  // found.  These will be added to the output as long as they don't
400  // appear in the hidden-conversions set.
401  UnresolvedSet<8> VBaseCs;
402
403  // The set of conversions in virtual bases that we've determined to
404  // be hidden.
405  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
406
407  // The set of types hidden by classes derived from this one.
408  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
409
410  // Go ahead and collect the direct conversions and add them to the
411  // hidden-types set.
412  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
413  Output.append(Cs.begin(), Cs.end());
414  for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
415    HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
416
417  // Recursively collect conversions from base classes.
418  for (CXXRecordDecl::base_class_iterator
419         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
420    const RecordType *RT = I->getType()->getAs<RecordType>();
421    if (!RT) continue;
422
423    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
424                              I->isVirtual(), I->getAccessSpecifier(),
425                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
426  }
427
428  // Add any unhidden conversions provided by virtual bases.
429  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
430         I != E; ++I) {
431    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
432      Output.addDecl(I.getDecl(), I.getAccess());
433  }
434}
435
436/// getVisibleConversionFunctions - get all conversion functions visible
437/// in current class; including conversion function templates.
438const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
439  // If root class, all conversions are visible.
440  if (bases_begin() == bases_end())
441    return &data().Conversions;
442  // If visible conversion list is already evaluated, return it.
443  if (data().ComputedVisibleConversions)
444    return &data().VisibleConversions;
445  CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
446  data().ComputedVisibleConversions = true;
447  return &data().VisibleConversions;
448}
449
450#ifndef NDEBUG
451void CXXRecordDecl::CheckConversionFunction(NamedDecl *ConvDecl) {
452  assert(ConvDecl->getDeclContext() == this &&
453         "conversion function does not belong to this record");
454
455  ConvDecl = ConvDecl->getUnderlyingDecl();
456  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(ConvDecl)) {
457    assert(isa<CXXConversionDecl>(Temp->getTemplatedDecl()));
458  } else {
459    assert(isa<CXXConversionDecl>(ConvDecl));
460  }
461}
462#endif
463
464void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
465  // This operation is O(N) but extremely rare.  Sema only uses it to
466  // remove UsingShadowDecls in a class that were followed by a direct
467  // declaration, e.g.:
468  //   class A : B {
469  //     using B::operator int;
470  //     operator int();
471  //   };
472  // This is uncommon by itself and even more uncommon in conjunction
473  // with sufficiently large numbers of directly-declared conversions
474  // that asymptotic behavior matters.
475
476  UnresolvedSetImpl &Convs = *getConversionFunctions();
477  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
478    if (Convs[I].getDecl() == ConvDecl) {
479      Convs.erase(I);
480      assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
481             && "conversion was found multiple times in unresolved set");
482      return;
483    }
484  }
485
486  llvm_unreachable("conversion not found in set!");
487}
488
489void CXXRecordDecl::setMethodAsVirtual(FunctionDecl *Method) {
490  Method->setVirtualAsWritten(true);
491  setAggregate(false);
492  setPOD(false);
493  setEmpty(false);
494  setPolymorphic(true);
495  setHasTrivialConstructor(false);
496  setHasTrivialCopyConstructor(false);
497  setHasTrivialCopyAssignment(false);
498}
499
500CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
501  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
502    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
503
504  return 0;
505}
506
507MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
508  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
509}
510
511void
512CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
513                                             TemplateSpecializationKind TSK) {
514  assert(TemplateOrInstantiation.isNull() &&
515         "Previous template or instantiation?");
516  assert(!isa<ClassTemplateSpecializationDecl>(this));
517  TemplateOrInstantiation
518    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
519}
520
521TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
522  if (const ClassTemplateSpecializationDecl *Spec
523        = dyn_cast<ClassTemplateSpecializationDecl>(this))
524    return Spec->getSpecializationKind();
525
526  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
527    return MSInfo->getTemplateSpecializationKind();
528
529  return TSK_Undeclared;
530}
531
532void
533CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
534  if (ClassTemplateSpecializationDecl *Spec
535      = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
536    Spec->setSpecializationKind(TSK);
537    return;
538  }
539
540  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
541    MSInfo->setTemplateSpecializationKind(TSK);
542    return;
543  }
544
545  assert(false && "Not a class template or member class specialization");
546}
547
548CXXConstructorDecl *
549CXXRecordDecl::getDefaultConstructor(ASTContext &Context) {
550  QualType ClassType = Context.getTypeDeclType(this);
551  DeclarationName ConstructorName
552    = Context.DeclarationNames.getCXXConstructorName(
553                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
554
555  DeclContext::lookup_const_iterator Con, ConEnd;
556  for (llvm::tie(Con, ConEnd) = lookup(ConstructorName);
557       Con != ConEnd; ++Con) {
558    // FIXME: In C++0x, a constructor template can be a default constructor.
559    if (isa<FunctionTemplateDecl>(*Con))
560      continue;
561
562    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
563    if (Constructor->isDefaultConstructor())
564      return Constructor;
565  }
566  return 0;
567}
568
569CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
570  ASTContext &Context = getASTContext();
571  QualType ClassType = Context.getTypeDeclType(this);
572
573  DeclarationName Name
574    = Context.DeclarationNames.getCXXDestructorName(
575                                          Context.getCanonicalType(ClassType));
576
577  DeclContext::lookup_const_iterator I, E;
578  llvm::tie(I, E) = lookup(Name);
579  assert(I != E && "Did not find a destructor!");
580
581  CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
582  assert(++I == E && "Found more than one destructor!");
583
584  return Dtor;
585}
586
587CXXMethodDecl *
588CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
589                      SourceLocation L, DeclarationName N,
590                      QualType T, TypeSourceInfo *TInfo,
591                      bool isStatic, StorageClass SCAsWritten, bool isInline) {
592  return new (C) CXXMethodDecl(CXXMethod, RD, L, N, T, TInfo,
593                               isStatic, SCAsWritten, isInline);
594}
595
596bool CXXMethodDecl::isUsualDeallocationFunction() const {
597  if (getOverloadedOperator() != OO_Delete &&
598      getOverloadedOperator() != OO_Array_Delete)
599    return false;
600
601  // C++ [basic.stc.dynamic.deallocation]p2:
602  //   A template instance is never a usual deallocation function,
603  //   regardless of its signature.
604  if (getPrimaryTemplate())
605    return false;
606
607  // C++ [basic.stc.dynamic.deallocation]p2:
608  //   If a class T has a member deallocation function named operator delete
609  //   with exactly one parameter, then that function is a usual (non-placement)
610  //   deallocation function. [...]
611  if (getNumParams() == 1)
612    return true;
613
614  // C++ [basic.stc.dynamic.deallocation]p2:
615  //   [...] If class T does not declare such an operator delete but does
616  //   declare a member deallocation function named operator delete with
617  //   exactly two parameters, the second of which has type std::size_t (18.1),
618  //   then this function is a usual deallocation function.
619  ASTContext &Context = getASTContext();
620  if (getNumParams() != 2 ||
621      !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
622                                      Context.getSizeType()))
623    return false;
624
625  // This function is a usual deallocation function if there are no
626  // single-parameter deallocation functions of the same kind.
627  for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
628       R.first != R.second; ++R.first) {
629    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
630      if (FD->getNumParams() == 1)
631        return false;
632  }
633
634  return true;
635}
636
637bool CXXMethodDecl::isCopyAssignmentOperator() const {
638  // C++0x [class.copy]p19:
639  //  A user-declared copy assignment operator X::operator= is a non-static
640  //  non-template member function of class X with exactly one parameter of
641  //  type X, X&, const X&, volatile X& or const volatile X&.
642  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
643      /*non-static*/ isStatic() ||
644      /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
645      /*exactly one parameter*/getNumParams() != 1)
646    return false;
647
648  QualType ParamType = getParamDecl(0)->getType();
649  if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
650    ParamType = Ref->getPointeeType();
651
652  ASTContext &Context = getASTContext();
653  QualType ClassType
654    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
655  return Context.hasSameUnqualifiedType(ClassType, ParamType);
656}
657
658void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
659  assert(MD->isCanonicalDecl() && "Method is not canonical!");
660  assert(!MD->getParent()->isDependentContext() &&
661         "Can't add an overridden method to a class template!");
662
663  getASTContext().addOverriddenMethod(this, MD);
664}
665
666CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
667  return getASTContext().overridden_methods_begin(this);
668}
669
670CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
671  return getASTContext().overridden_methods_end(this);
672}
673
674QualType CXXMethodDecl::getThisType(ASTContext &C) const {
675  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
676  // If the member function is declared const, the type of this is const X*,
677  // if the member function is declared volatile, the type of this is
678  // volatile X*, and if the member function is declared const volatile,
679  // the type of this is const volatile X*.
680
681  assert(isInstance() && "No 'this' for static methods!");
682
683  QualType ClassTy = C.getTypeDeclType(getParent());
684  ClassTy = C.getQualifiedType(ClassTy,
685                               Qualifiers::fromCVRMask(getTypeQualifiers()));
686  return C.getPointerType(ClassTy);
687}
688
689bool CXXMethodDecl::hasInlineBody() const {
690  // If this function is a template instantiation, look at the template from
691  // which it was instantiated.
692  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
693  if (!CheckFn)
694    CheckFn = this;
695
696  const FunctionDecl *fn;
697  return CheckFn->getBody(fn) && !fn->isOutOfLine();
698}
699
700CXXBaseOrMemberInitializer::
701CXXBaseOrMemberInitializer(ASTContext &Context,
702                           TypeSourceInfo *TInfo, bool IsVirtual,
703                           SourceLocation L, Expr *Init, SourceLocation R)
704  : BaseOrMember(TInfo), Init(Init), AnonUnionMember(0),
705    LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
706    SourceOrderOrNumArrayIndices(0)
707{
708}
709
710CXXBaseOrMemberInitializer::
711CXXBaseOrMemberInitializer(ASTContext &Context,
712                           FieldDecl *Member, SourceLocation MemberLoc,
713                           SourceLocation L, Expr *Init, SourceLocation R)
714  : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
715    AnonUnionMember(0), LParenLoc(L), RParenLoc(R), IsVirtual(false),
716    IsWritten(false), SourceOrderOrNumArrayIndices(0)
717{
718}
719
720CXXBaseOrMemberInitializer::
721CXXBaseOrMemberInitializer(ASTContext &Context,
722                           FieldDecl *Member, SourceLocation MemberLoc,
723                           SourceLocation L, Expr *Init, SourceLocation R,
724                           VarDecl **Indices,
725                           unsigned NumIndices)
726  : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
727    AnonUnionMember(0), LParenLoc(L), RParenLoc(R), IsVirtual(false),
728    IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
729{
730  VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
731  memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
732}
733
734CXXBaseOrMemberInitializer *
735CXXBaseOrMemberInitializer::Create(ASTContext &Context,
736                                   FieldDecl *Member,
737                                   SourceLocation MemberLoc,
738                                   SourceLocation L,
739                                   Expr *Init,
740                                   SourceLocation R,
741                                   VarDecl **Indices,
742                                   unsigned NumIndices) {
743  void *Mem = Context.Allocate(sizeof(CXXBaseOrMemberInitializer) +
744                               sizeof(VarDecl *) * NumIndices,
745                               llvm::alignof<CXXBaseOrMemberInitializer>());
746  return new (Mem) CXXBaseOrMemberInitializer(Context, Member, MemberLoc,
747                                              L, Init, R, Indices, NumIndices);
748}
749
750void CXXBaseOrMemberInitializer::Destroy(ASTContext &Context) {
751  if (Init)
752    Init->Destroy(Context);
753  // FIXME: Destroy indices
754  this->~CXXBaseOrMemberInitializer();
755}
756
757TypeLoc CXXBaseOrMemberInitializer::getBaseClassLoc() const {
758  if (isBaseInitializer())
759    return BaseOrMember.get<TypeSourceInfo*>()->getTypeLoc();
760  else
761    return TypeLoc();
762}
763
764Type *CXXBaseOrMemberInitializer::getBaseClass() {
765  if (isBaseInitializer())
766    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
767  else
768    return 0;
769}
770
771const Type *CXXBaseOrMemberInitializer::getBaseClass() const {
772  if (isBaseInitializer())
773    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
774  else
775    return 0;
776}
777
778SourceLocation CXXBaseOrMemberInitializer::getSourceLocation() const {
779  if (isMemberInitializer())
780    return getMemberLocation();
781
782  return getBaseClassLoc().getLocalSourceRange().getBegin();
783}
784
785SourceRange CXXBaseOrMemberInitializer::getSourceRange() const {
786  return SourceRange(getSourceLocation(), getRParenLoc());
787}
788
789CXXConstructorDecl *
790CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
791  return new (C) CXXConstructorDecl(0, SourceLocation(), DeclarationName(),
792                                    QualType(), 0, false, false, false);
793}
794
795CXXConstructorDecl *
796CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
797                           SourceLocation L, DeclarationName N,
798                           QualType T, TypeSourceInfo *TInfo,
799                           bool isExplicit,
800                           bool isInline,
801                           bool isImplicitlyDeclared) {
802  assert(N.getNameKind() == DeclarationName::CXXConstructorName &&
803         "Name must refer to a constructor");
804  return new (C) CXXConstructorDecl(RD, L, N, T, TInfo, isExplicit,
805                                    isInline, isImplicitlyDeclared);
806}
807
808bool CXXConstructorDecl::isDefaultConstructor() const {
809  // C++ [class.ctor]p5:
810  //   A default constructor for a class X is a constructor of class
811  //   X that can be called without an argument.
812  return (getNumParams() == 0) ||
813         (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
814}
815
816bool
817CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
818  // C++ [class.copy]p2:
819  //   A non-template constructor for class X is a copy constructor
820  //   if its first parameter is of type X&, const X&, volatile X& or
821  //   const volatile X&, and either there are no other parameters
822  //   or else all other parameters have default arguments (8.3.6).
823  if ((getNumParams() < 1) ||
824      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
825      (getPrimaryTemplate() != 0) ||
826      (getDescribedFunctionTemplate() != 0))
827    return false;
828
829  const ParmVarDecl *Param = getParamDecl(0);
830
831  // Do we have a reference type? Rvalue references don't count.
832  const LValueReferenceType *ParamRefType =
833    Param->getType()->getAs<LValueReferenceType>();
834  if (!ParamRefType)
835    return false;
836
837  // Is it a reference to our class type?
838  ASTContext &Context = getASTContext();
839
840  CanQualType PointeeType
841    = Context.getCanonicalType(ParamRefType->getPointeeType());
842  CanQualType ClassTy
843    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
844  if (PointeeType.getUnqualifiedType() != ClassTy)
845    return false;
846
847  // FIXME: other qualifiers?
848
849  // We have a copy constructor.
850  TypeQuals = PointeeType.getCVRQualifiers();
851  return true;
852}
853
854bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
855  // C++ [class.conv.ctor]p1:
856  //   A constructor declared without the function-specifier explicit
857  //   that can be called with a single parameter specifies a
858  //   conversion from the type of its first parameter to the type of
859  //   its class. Such a constructor is called a converting
860  //   constructor.
861  if (isExplicit() && !AllowExplicit)
862    return false;
863
864  return (getNumParams() == 0 &&
865          getType()->getAs<FunctionProtoType>()->isVariadic()) ||
866         (getNumParams() == 1) ||
867         (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
868}
869
870bool CXXConstructorDecl::isCopyConstructorLikeSpecialization() const {
871  if ((getNumParams() < 1) ||
872      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
873      (getPrimaryTemplate() == 0) ||
874      (getDescribedFunctionTemplate() != 0))
875    return false;
876
877  const ParmVarDecl *Param = getParamDecl(0);
878
879  ASTContext &Context = getASTContext();
880  CanQualType ParamType = Context.getCanonicalType(Param->getType());
881
882  // Strip off the lvalue reference, if any.
883  if (CanQual<LValueReferenceType> ParamRefType
884                                    = ParamType->getAs<LValueReferenceType>())
885    ParamType = ParamRefType->getPointeeType();
886
887
888  // Is it the same as our our class type?
889  CanQualType ClassTy
890    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
891  if (ParamType.getUnqualifiedType() != ClassTy)
892    return false;
893
894  return true;
895}
896
897CXXDestructorDecl *
898CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
899  return new (C) CXXDestructorDecl(0, SourceLocation(), DeclarationName(),
900                                   QualType(), false, false);
901}
902
903CXXDestructorDecl *
904CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
905                          SourceLocation L, DeclarationName N,
906                          QualType T, bool isInline,
907                          bool isImplicitlyDeclared) {
908  assert(N.getNameKind() == DeclarationName::CXXDestructorName &&
909         "Name must refer to a destructor");
910  return new (C) CXXDestructorDecl(RD, L, N, T, isInline, isImplicitlyDeclared);
911}
912
913void
914CXXConstructorDecl::Destroy(ASTContext& C) {
915  C.Deallocate(BaseOrMemberInitializers);
916  CXXMethodDecl::Destroy(C);
917}
918
919CXXConversionDecl *
920CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
921  return new (C) CXXConversionDecl(0, SourceLocation(), DeclarationName(),
922                                   QualType(), 0, false, false);
923}
924
925CXXConversionDecl *
926CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
927                          SourceLocation L, DeclarationName N,
928                          QualType T, TypeSourceInfo *TInfo,
929                          bool isInline, bool isExplicit) {
930  assert(N.getNameKind() == DeclarationName::CXXConversionFunctionName &&
931         "Name must refer to a conversion function");
932  return new (C) CXXConversionDecl(RD, L, N, T, TInfo, isInline, isExplicit);
933}
934
935LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
936                                         DeclContext *DC,
937                                         SourceLocation L,
938                                         LanguageIDs Lang, bool Braces) {
939  return new (C) LinkageSpecDecl(DC, L, Lang, Braces);
940}
941
942UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
943                                               SourceLocation L,
944                                               SourceLocation NamespaceLoc,
945                                               SourceRange QualifierRange,
946                                               NestedNameSpecifier *Qualifier,
947                                               SourceLocation IdentLoc,
948                                               NamedDecl *Used,
949                                               DeclContext *CommonAncestor) {
950  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
951    Used = NS->getOriginalNamespace();
952  return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange,
953                                    Qualifier, IdentLoc, Used, CommonAncestor);
954}
955
956NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
957  if (NamespaceAliasDecl *NA =
958        dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
959    return NA->getNamespace();
960  return cast_or_null<NamespaceDecl>(NominatedNamespace);
961}
962
963void UsingDirectiveDecl::setNominatedNamespace(NamedDecl* ND) {
964  assert((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
965    "expected a NamespaceDecl or NamespaceAliasDecl");
966  NominatedNamespace = ND;
967}
968
969NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
970                                               SourceLocation L,
971                                               SourceLocation AliasLoc,
972                                               IdentifierInfo *Alias,
973                                               SourceRange QualifierRange,
974                                               NestedNameSpecifier *Qualifier,
975                                               SourceLocation IdentLoc,
976                                               NamedDecl *Namespace) {
977  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
978    Namespace = NS->getOriginalNamespace();
979  return new (C) NamespaceAliasDecl(DC, L, AliasLoc, Alias, QualifierRange,
980                                    Qualifier, IdentLoc, Namespace);
981}
982
983UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC,
984      SourceLocation L, SourceRange NNR, SourceLocation UL,
985      NestedNameSpecifier* TargetNNS, DeclarationName Name,
986      bool IsTypeNameArg) {
987  return new (C) UsingDecl(DC, L, NNR, UL, TargetNNS, Name, IsTypeNameArg);
988}
989
990UnresolvedUsingValueDecl *
991UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
992                                 SourceLocation UsingLoc,
993                                 SourceRange TargetNNR,
994                                 NestedNameSpecifier *TargetNNS,
995                                 SourceLocation TargetNameLoc,
996                                 DeclarationName TargetName) {
997  return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
998                                          TargetNNR, TargetNNS,
999                                          TargetNameLoc, TargetName);
1000}
1001
1002UnresolvedUsingTypenameDecl *
1003UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1004                                    SourceLocation UsingLoc,
1005                                    SourceLocation TypenameLoc,
1006                                    SourceRange TargetNNR,
1007                                    NestedNameSpecifier *TargetNNS,
1008                                    SourceLocation TargetNameLoc,
1009                                    DeclarationName TargetName) {
1010  return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1011                                             TargetNNR, TargetNNS,
1012                                             TargetNameLoc,
1013                                             TargetName.getAsIdentifierInfo());
1014}
1015
1016StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1017                                           SourceLocation L, Expr *AssertExpr,
1018                                           StringLiteral *Message) {
1019  return new (C) StaticAssertDecl(DC, L, AssertExpr, Message);
1020}
1021
1022void StaticAssertDecl::Destroy(ASTContext& C) {
1023  AssertExpr->Destroy(C);
1024  Message->Destroy(C);
1025  Decl::Destroy(C);
1026}
1027
1028StaticAssertDecl::~StaticAssertDecl() {
1029}
1030
1031static const char *getAccessName(AccessSpecifier AS) {
1032  switch (AS) {
1033    default:
1034    case AS_none:
1035      assert("Invalid access specifier!");
1036      return 0;
1037    case AS_public:
1038      return "public";
1039    case AS_private:
1040      return "private";
1041    case AS_protected:
1042      return "protected";
1043  }
1044}
1045
1046const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1047                                           AccessSpecifier AS) {
1048  return DB << getAccessName(AS);
1049}
1050
1051
1052