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