DeclCXX.cpp revision c4c06ff08b812b1149b45c766e052b33688aa58f
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/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/TypeLoc.h"
21#include "clang/Basic/IdentifierTable.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Decl Allocation/Deallocation Method Implementations
28//===----------------------------------------------------------------------===//
29
30CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
31  : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
32    UserDeclaredCopyAssignment(false), UserDeclaredDestructor(false),
33    Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
34    Abstract(false), HasTrivialConstructor(true),
35    HasTrivialCopyConstructor(true), HasTrivialCopyAssignment(true),
36    HasTrivialDestructor(true), ComputedVisibleConversions(false),
37    DeclaredDefaultConstructor(false), DeclaredCopyConstructor(false),
38    DeclaredCopyAssignment(false), DeclaredDestructor(false),
39    NumBases(0), NumVBases(0), Bases(), VBases(),
40    Definition(D), FirstFriend(0) {
41}
42
43CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
44                             SourceLocation L, IdentifierInfo *Id,
45                             CXXRecordDecl *PrevDecl,
46                             SourceLocation TKL)
47  : RecordDecl(K, TK, DC, L, Id, PrevDecl, TKL),
48    DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
49    TemplateOrInstantiation() { }
50
51CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
52                                     SourceLocation L, IdentifierInfo *Id,
53                                     SourceLocation TKL,
54                                     CXXRecordDecl* PrevDecl,
55                                     bool DelayTypeCreation) {
56  CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id,
57                                           PrevDecl, TKL);
58
59  // FIXME: DelayTypeCreation seems like such a hack
60  if (!DelayTypeCreation)
61    C.getTypeDeclType(R, PrevDecl);
62  return R;
63}
64
65CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, EmptyShell Empty) {
66  return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(), 0, 0,
67                               SourceLocation());
68}
69
70void
71CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
72                        unsigned NumBases) {
73  ASTContext &C = getASTContext();
74
75  // C++ [dcl.init.aggr]p1:
76  //   An aggregate is an array or a class (clause 9) with [...]
77  //   no base classes [...].
78  data().Aggregate = false;
79
80  if (!data().Bases.isOffset() && data().NumBases > 0)
81    C.Deallocate(data().getBases());
82
83  // The set of seen virtual base types.
84  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
85
86  // The virtual bases of this class.
87  llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
88
89  data().Bases = new(C) CXXBaseSpecifier [NumBases];
90  data().NumBases = NumBases;
91  for (unsigned i = 0; i < NumBases; ++i) {
92    data().getBases()[i] = *Bases[i];
93    // Keep track of inherited vbases for this base class.
94    const CXXBaseSpecifier *Base = Bases[i];
95    QualType BaseType = Base->getType();
96    // Skip dependent types; we can't do any checking on them now.
97    if (BaseType->isDependentType())
98      continue;
99    CXXRecordDecl *BaseClassDecl
100      = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
101
102    // C++ [dcl.init.aggr]p1:
103    //   An aggregate is [...] a class with [...] no base classes [...].
104    data().Aggregate = false;
105
106    // C++ [class]p4:
107    //   A POD-struct is an aggregate class...
108    data().PlainOldData = false;
109
110    // A class with a non-empty base class is not empty.
111    // FIXME: Standard ref?
112    if (!BaseClassDecl->isEmpty())
113      data().Empty = false;
114
115    // C++ [class.virtual]p1:
116    //   A class that declares or inherits a virtual function is called a
117    //   polymorphic class.
118    if (BaseClassDecl->isPolymorphic())
119      data().Polymorphic = true;
120
121    // Now go through all virtual bases of this base and add them.
122    for (CXXRecordDecl::base_class_iterator VBase =
123          BaseClassDecl->vbases_begin(),
124         E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
125      // Add this base if it's not already in the list.
126      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
127        VBases.push_back(VBase);
128    }
129
130    if (Base->isVirtual()) {
131      // Add this base if it's not already in the list.
132      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
133          VBases.push_back(Base);
134
135      // C++0x [meta.unary.prop] is_empty:
136      //    T is a class type, but not a union type, with ... no virtual base
137      //    classes
138      data().Empty = false;
139
140      // C++ [class.ctor]p5:
141      //   A constructor is trivial if its class has no virtual base classes.
142      data().HasTrivialConstructor = false;
143
144      // C++ [class.copy]p6:
145      //   A copy constructor is trivial if its class has no virtual base
146      //   classes.
147      data().HasTrivialCopyConstructor = false;
148
149      // C++ [class.copy]p11:
150      //   A copy assignment operator is trivial if its class has no virtual
151      //   base classes.
152      data().HasTrivialCopyAssignment = false;
153    } else {
154      // C++ [class.ctor]p5:
155      //   A constructor is trivial if all the direct base classes of its
156      //   class have trivial constructors.
157      if (!BaseClassDecl->hasTrivialConstructor())
158        data().HasTrivialConstructor = false;
159
160      // C++ [class.copy]p6:
161      //   A copy constructor is trivial if all the direct base classes of its
162      //   class have trivial copy constructors.
163      if (!BaseClassDecl->hasTrivialCopyConstructor())
164        data().HasTrivialCopyConstructor = false;
165
166      // C++ [class.copy]p11:
167      //   A copy assignment operator is trivial if all the direct base classes
168      //   of its class have trivial copy assignment operators.
169      if (!BaseClassDecl->hasTrivialCopyAssignment())
170        data().HasTrivialCopyAssignment = false;
171    }
172
173    // C++ [class.ctor]p3:
174    //   A destructor is trivial if all the direct base classes of its class
175    //   have trivial destructors.
176    if (!BaseClassDecl->hasTrivialDestructor())
177      data().HasTrivialDestructor = false;
178  }
179
180  if (VBases.empty())
181    return;
182
183  // Create base specifier for any direct or indirect virtual bases.
184  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
185  data().NumVBases = VBases.size();
186  for (int I = 0, E = VBases.size(); I != E; ++I) {
187    TypeSourceInfo *VBaseTypeInfo = VBases[I]->getTypeSourceInfo();
188
189    // Skip dependent types; we can't do any checking on them now.
190    if (VBaseTypeInfo->getType()->isDependentType())
191      continue;
192
193    CXXRecordDecl *VBaseClassDecl = cast<CXXRecordDecl>(
194      VBaseTypeInfo->getType()->getAs<RecordType>()->getDecl());
195
196    data().getVBases()[I] =
197      CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true,
198                       VBaseClassDecl->getTagKind() == TTK_Class,
199                       VBases[I]->getAccessSpecifier(), VBaseTypeInfo);
200  }
201}
202
203/// Callback function for CXXRecordDecl::forallBases that acknowledges
204/// that it saw a base class.
205static bool SawBase(const CXXRecordDecl *, void *) {
206  return true;
207}
208
209bool CXXRecordDecl::hasAnyDependentBases() const {
210  if (!isDependentContext())
211    return false;
212
213  return !forallBases(SawBase, 0);
214}
215
216bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const {
217  return getCopyConstructor(Context, Qualifiers::Const) != 0;
218}
219
220/// \brief Perform a simplistic form of overload resolution that only considers
221/// cv-qualifiers on a single parameter, and return the best overload candidate
222/// (if there is one).
223static CXXMethodDecl *
224GetBestOverloadCandidateSimple(
225  const llvm::SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
226  if (Cands.empty())
227    return 0;
228  if (Cands.size() == 1)
229    return Cands[0].first;
230
231  unsigned Best = 0, N = Cands.size();
232  for (unsigned I = 1; I != N; ++I)
233    if (Cands[Best].second.isSupersetOf(Cands[I].second))
234      Best = I;
235
236  for (unsigned I = 1; I != N; ++I)
237    if (Cands[Best].second.isSupersetOf(Cands[I].second))
238      return 0;
239
240  return Cands[Best].first;
241}
242
243CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context,
244                                                      unsigned TypeQuals) const{
245  QualType ClassType
246    = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
247  DeclarationName ConstructorName
248    = Context.DeclarationNames.getCXXConstructorName(
249                                          Context.getCanonicalType(ClassType));
250  unsigned FoundTQs;
251  llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
252  DeclContext::lookup_const_iterator Con, ConEnd;
253  for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
254       Con != ConEnd; ++Con) {
255    // C++ [class.copy]p2:
256    //   A non-template constructor for class X is a copy constructor if [...]
257    if (isa<FunctionTemplateDecl>(*Con))
258      continue;
259
260    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
261    if (Constructor->isCopyConstructor(FoundTQs)) {
262      if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
263          (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
264        Found.push_back(std::make_pair(
265                                 const_cast<CXXConstructorDecl *>(Constructor),
266                                       Qualifiers::fromCVRMask(FoundTQs)));
267    }
268  }
269
270  return cast_or_null<CXXConstructorDecl>(
271                                        GetBestOverloadCandidateSimple(Found));
272}
273
274CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
275  ASTContext &Context = getASTContext();
276  QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
277  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
278
279  llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
280  DeclContext::lookup_const_iterator Op, OpEnd;
281  for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
282    // C++ [class.copy]p9:
283    //   A user-declared copy assignment operator is a non-static non-template
284    //   member function of class X with exactly one parameter of type X, X&,
285    //   const X&, volatile X& or const volatile X&.
286    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
287    if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
288      continue;
289
290    const FunctionProtoType *FnType
291      = Method->getType()->getAs<FunctionProtoType>();
292    assert(FnType && "Overloaded operator has no prototype.");
293    // Don't assert on this; an invalid decl might have been left in the AST.
294    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
295      continue;
296
297    QualType ArgType = FnType->getArgType(0);
298    Qualifiers Quals;
299    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
300      ArgType = Ref->getPointeeType();
301      // If we have a const argument and we have a reference to a non-const,
302      // this function does not match.
303      if (ArgIsConst && !ArgType.isConstQualified())
304        continue;
305
306      Quals = ArgType.getQualifiers();
307    } else {
308      // By-value copy-assignment operators are treated like const X&
309      // copy-assignment operators.
310      Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
311    }
312
313    if (!Context.hasSameUnqualifiedType(ArgType, Class))
314      continue;
315
316    // Save this copy-assignment operator. It might be "the one".
317    Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
318  }
319
320  // Use a simplistic form of overload resolution to find the candidate.
321  return GetBestOverloadCandidateSimple(Found);
322}
323
324void CXXRecordDecl::markedVirtualFunctionPure() {
325  // C++ [class.abstract]p2:
326  //   A class is abstract if it has at least one pure virtual function.
327  data().Abstract = true;
328}
329
330void CXXRecordDecl::addedMember(Decl *D) {
331  // Ignore friends and invalid declarations.
332  if (D->getFriendObjectKind() || D->isInvalidDecl())
333    return;
334
335  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
336  if (FunTmpl)
337    D = FunTmpl->getTemplatedDecl();
338
339  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
340    if (Method->isVirtual()) {
341      // C++ [dcl.init.aggr]p1:
342      //   An aggregate is an array or a class with [...] no virtual functions.
343      data().Aggregate = false;
344
345      // C++ [class]p4:
346      //   A POD-struct is an aggregate class...
347      data().PlainOldData = false;
348
349      // Virtual functions make the class non-empty.
350      // FIXME: Standard ref?
351      data().Empty = false;
352
353      // C++ [class.virtual]p1:
354      //   A class that declares or inherits a virtual function is called a
355      //   polymorphic class.
356      data().Polymorphic = true;
357
358      // None of the special member functions are trivial.
359      data().HasTrivialConstructor = false;
360      data().HasTrivialCopyConstructor = false;
361      data().HasTrivialCopyAssignment = false;
362      // FIXME: Destructor?
363    }
364  }
365
366  if (D->isImplicit()) {
367    // Notify that an implicit member was added after the definition
368    // was completed.
369    if (!isBeingDefined())
370      if (ASTMutationListener *L = getASTMutationListener())
371        L->AddedCXXImplicitMember(data().Definition, D);
372
373    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
374      // If this is the implicit default constructor, note that we have now
375      // declared it.
376      if (Constructor->isDefaultConstructor())
377        data().DeclaredDefaultConstructor = true;
378      // If this is the implicit copy constructor, note that we have now
379      // declared it.
380      else if (Constructor->isCopyConstructor())
381        data().DeclaredCopyConstructor = true;
382      return;
383    }
384
385    if (isa<CXXDestructorDecl>(D)) {
386      data().DeclaredDestructor = true;
387      return;
388    }
389
390    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
391      // If this is the implicit copy constructor, note that we have now
392      // declared it.
393      // FIXME: Move constructors
394      if (Method->getOverloadedOperator() == OO_Equal)
395        data().DeclaredCopyAssignment = true;
396      return;
397    }
398
399    // Any other implicit declarations are handled like normal declarations.
400  }
401
402  // Handle (user-declared) constructors.
403  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
404    // Note that we have a user-declared constructor.
405    data().UserDeclaredConstructor = true;
406
407    // Note that we have no need of an implicitly-declared default constructor.
408    data().DeclaredDefaultConstructor = true;
409
410    // C++ [dcl.init.aggr]p1:
411    //   An aggregate is an array or a class (clause 9) with no
412    //   user-declared constructors (12.1) [...].
413    data().Aggregate = false;
414
415    // C++ [class]p4:
416    //   A POD-struct is an aggregate class [...]
417    data().PlainOldData = false;
418
419    // C++ [class.ctor]p5:
420    //   A constructor is trivial if it is an implicitly-declared default
421    //   constructor.
422    // FIXME: C++0x: don't do this for "= default" default constructors.
423    data().HasTrivialConstructor = false;
424
425    // Note when we have a user-declared copy constructor, which will
426    // suppress the implicit declaration of a copy constructor.
427    if (!FunTmpl && Constructor->isCopyConstructor()) {
428      data().UserDeclaredCopyConstructor = true;
429      data().DeclaredCopyConstructor = true;
430
431      // C++ [class.copy]p6:
432      //   A copy constructor is trivial if it is implicitly declared.
433      // FIXME: C++0x: don't do this for "= default" copy constructors.
434      data().HasTrivialCopyConstructor = false;
435    }
436
437    return;
438  }
439
440  // Handle (user-declared) destructors.
441  if (isa<CXXDestructorDecl>(D)) {
442    data().DeclaredDestructor = true;
443    data().UserDeclaredDestructor = true;
444
445    // C++ [class]p4:
446    //   A POD-struct is an aggregate class that has [...] no user-defined
447    //   destructor.
448    data().PlainOldData = false;
449
450    // C++ [class.dtor]p3:
451    //   A destructor is trivial if it is an implicitly-declared destructor and
452    //   [...].
453    //
454    // FIXME: C++0x: don't do this for "= default" destructors
455    data().HasTrivialDestructor = false;
456
457    return;
458  }
459
460  // Handle (user-declared) member functions.
461  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
462    if (Method->getOverloadedOperator() == OO_Equal) {
463      // We're interested specifically in copy assignment operators.
464      const FunctionProtoType *FnType
465        = Method->getType()->getAs<FunctionProtoType>();
466      assert(FnType && "Overloaded operator has no proto function type.");
467      assert(FnType->getNumArgs() == 1 && !FnType->isVariadic());
468
469      // Copy assignment operators must be non-templates.
470      if (Method->getPrimaryTemplate() || FunTmpl)
471        return;
472
473      ASTContext &Context = getASTContext();
474      QualType ArgType = FnType->getArgType(0);
475      if (const LValueReferenceType *Ref =ArgType->getAs<LValueReferenceType>())
476        ArgType = Ref->getPointeeType();
477
478      ArgType = ArgType.getUnqualifiedType();
479      QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
480                                             const_cast<CXXRecordDecl*>(this)));
481
482      if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
483        return;
484
485      // This is a copy assignment operator.
486      // FIXME: Move assignment operators.
487
488      // Suppress the implicit declaration of a copy constructor.
489      data().UserDeclaredCopyAssignment = true;
490      data().DeclaredCopyAssignment = true;
491
492      // C++ [class.copy]p11:
493      //   A copy assignment operator is trivial if it is implicitly declared.
494      // FIXME: C++0x: don't do this for "= default" copy operators.
495      data().HasTrivialCopyAssignment = false;
496
497      // C++ [class]p4:
498      //   A POD-struct is an aggregate class that [...] has no user-defined copy
499      //   assignment operator [...].
500      data().PlainOldData = false;
501    }
502
503    // Keep the list of conversion functions up-to-date.
504    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
505      // We don't record specializations.
506      if (Conversion->getPrimaryTemplate())
507        return;
508
509      // FIXME: We intentionally don't use the decl's access here because it
510      // hasn't been set yet.  That's really just a misdesign in Sema.
511
512      if (FunTmpl) {
513        if (FunTmpl->getPreviousDeclaration())
514          data().Conversions.replace(FunTmpl->getPreviousDeclaration(),
515                                     FunTmpl);
516        else
517          data().Conversions.addDecl(FunTmpl);
518      } else {
519        if (Conversion->getPreviousDeclaration())
520          data().Conversions.replace(Conversion->getPreviousDeclaration(),
521                                     Conversion);
522        else
523          data().Conversions.addDecl(Conversion);
524      }
525    }
526
527    return;
528  }
529
530  // Handle non-static data members.
531  if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
532    // C++ [dcl.init.aggr]p1:
533    //   An aggregate is an array or a class (clause 9) with [...] no
534    //   private or protected non-static data members (clause 11).
535    //
536    // A POD must be an aggregate.
537    if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
538      data().Aggregate = false;
539      data().PlainOldData = false;
540    }
541
542    // C++ [class]p9:
543    //   A POD struct is a class that is both a trivial class and a
544    //   standard-layout class, and has no non-static data members of type
545    //   non-POD struct, non-POD union (or array of such types).
546    ASTContext &Context = getASTContext();
547    QualType T = Context.getBaseElementType(Field->getType());
548    if (!T->isPODType())
549      data().PlainOldData = false;
550    if (T->isReferenceType())
551      data().HasTrivialConstructor = false;
552
553    if (const RecordType *RecordTy = T->getAs<RecordType>()) {
554      CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
555      if (FieldRec->getDefinition()) {
556        if (!FieldRec->hasTrivialConstructor())
557          data().HasTrivialConstructor = false;
558        if (!FieldRec->hasTrivialCopyConstructor())
559          data().HasTrivialCopyConstructor = false;
560        if (!FieldRec->hasTrivialCopyAssignment())
561          data().HasTrivialCopyAssignment = false;
562        if (!FieldRec->hasTrivialDestructor())
563          data().HasTrivialDestructor = false;
564      }
565    }
566
567    // If this is not a zero-length bit-field, then the class is not empty.
568    if (data().Empty) {
569      if (!Field->getBitWidth())
570        data().Empty = false;
571      else if (!Field->getBitWidth()->isTypeDependent() &&
572               !Field->getBitWidth()->isValueDependent()) {
573        llvm::APSInt Bits;
574        if (Field->getBitWidth()->isIntegerConstantExpr(Bits, Context))
575          if (!!Bits)
576            data().Empty = false;
577      }
578    }
579  }
580
581  // Handle using declarations of conversion functions.
582  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
583    if (Shadow->getDeclName().getNameKind()
584          == DeclarationName::CXXConversionFunctionName)
585      data().Conversions.addDecl(Shadow, Shadow->getAccess());
586}
587
588static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
589  QualType T;
590  if (isa<UsingShadowDecl>(Conv))
591    Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
592  if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
593    T = ConvTemp->getTemplatedDecl()->getResultType();
594  else
595    T = cast<CXXConversionDecl>(Conv)->getConversionType();
596  return Context.getCanonicalType(T);
597}
598
599/// Collect the visible conversions of a base class.
600///
601/// \param Base a base class of the class we're considering
602/// \param InVirtual whether this base class is a virtual base (or a base
603///   of a virtual base)
604/// \param Access the access along the inheritance path to this base
605/// \param ParentHiddenTypes the conversions provided by the inheritors
606///   of this base
607/// \param Output the set to which to add conversions from non-virtual bases
608/// \param VOutput the set to which to add conversions from virtual bases
609/// \param HiddenVBaseCs the set of conversions which were hidden in a
610///   virtual base along some inheritance path
611static void CollectVisibleConversions(ASTContext &Context,
612                                      CXXRecordDecl *Record,
613                                      bool InVirtual,
614                                      AccessSpecifier Access,
615                  const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
616                                      UnresolvedSetImpl &Output,
617                                      UnresolvedSetImpl &VOutput,
618                           llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
619  // The set of types which have conversions in this class or its
620  // subclasses.  As an optimization, we don't copy the derived set
621  // unless it might change.
622  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
623  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
624
625  // Collect the direct conversions and figure out which conversions
626  // will be hidden in the subclasses.
627  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
628  if (!Cs.empty()) {
629    HiddenTypesBuffer = ParentHiddenTypes;
630    HiddenTypes = &HiddenTypesBuffer;
631
632    for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
633      bool Hidden =
634        !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
635
636      // If this conversion is hidden and we're in a virtual base,
637      // remember that it's hidden along some inheritance path.
638      if (Hidden && InVirtual)
639        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
640
641      // If this conversion isn't hidden, add it to the appropriate output.
642      else if (!Hidden) {
643        AccessSpecifier IAccess
644          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
645
646        if (InVirtual)
647          VOutput.addDecl(I.getDecl(), IAccess);
648        else
649          Output.addDecl(I.getDecl(), IAccess);
650      }
651    }
652  }
653
654  // Collect information recursively from any base classes.
655  for (CXXRecordDecl::base_class_iterator
656         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
657    const RecordType *RT = I->getType()->getAs<RecordType>();
658    if (!RT) continue;
659
660    AccessSpecifier BaseAccess
661      = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
662    bool BaseInVirtual = InVirtual || I->isVirtual();
663
664    CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
665    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
666                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
667  }
668}
669
670/// Collect the visible conversions of a class.
671///
672/// This would be extremely straightforward if it weren't for virtual
673/// bases.  It might be worth special-casing that, really.
674static void CollectVisibleConversions(ASTContext &Context,
675                                      CXXRecordDecl *Record,
676                                      UnresolvedSetImpl &Output) {
677  // The collection of all conversions in virtual bases that we've
678  // found.  These will be added to the output as long as they don't
679  // appear in the hidden-conversions set.
680  UnresolvedSet<8> VBaseCs;
681
682  // The set of conversions in virtual bases that we've determined to
683  // be hidden.
684  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
685
686  // The set of types hidden by classes derived from this one.
687  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
688
689  // Go ahead and collect the direct conversions and add them to the
690  // hidden-types set.
691  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
692  Output.append(Cs.begin(), Cs.end());
693  for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
694    HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
695
696  // Recursively collect conversions from base classes.
697  for (CXXRecordDecl::base_class_iterator
698         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
699    const RecordType *RT = I->getType()->getAs<RecordType>();
700    if (!RT) continue;
701
702    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
703                              I->isVirtual(), I->getAccessSpecifier(),
704                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
705  }
706
707  // Add any unhidden conversions provided by virtual bases.
708  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
709         I != E; ++I) {
710    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
711      Output.addDecl(I.getDecl(), I.getAccess());
712  }
713}
714
715/// getVisibleConversionFunctions - get all conversion functions visible
716/// in current class; including conversion function templates.
717const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
718  // If root class, all conversions are visible.
719  if (bases_begin() == bases_end())
720    return &data().Conversions;
721  // If visible conversion list is already evaluated, return it.
722  if (data().ComputedVisibleConversions)
723    return &data().VisibleConversions;
724  CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
725  data().ComputedVisibleConversions = true;
726  return &data().VisibleConversions;
727}
728
729#ifndef NDEBUG
730void CXXRecordDecl::CheckConversionFunction(NamedDecl *ConvDecl) {
731  assert(ConvDecl->getDeclContext() == this &&
732         "conversion function does not belong to this record");
733
734  ConvDecl = ConvDecl->getUnderlyingDecl();
735  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(ConvDecl)) {
736    assert(isa<CXXConversionDecl>(Temp->getTemplatedDecl()));
737  } else {
738    assert(isa<CXXConversionDecl>(ConvDecl));
739  }
740}
741#endif
742
743void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
744  // This operation is O(N) but extremely rare.  Sema only uses it to
745  // remove UsingShadowDecls in a class that were followed by a direct
746  // declaration, e.g.:
747  //   class A : B {
748  //     using B::operator int;
749  //     operator int();
750  //   };
751  // This is uncommon by itself and even more uncommon in conjunction
752  // with sufficiently large numbers of directly-declared conversions
753  // that asymptotic behavior matters.
754
755  UnresolvedSetImpl &Convs = *getConversionFunctions();
756  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
757    if (Convs[I].getDecl() == ConvDecl) {
758      Convs.erase(I);
759      assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
760             && "conversion was found multiple times in unresolved set");
761      return;
762    }
763  }
764
765  llvm_unreachable("conversion not found in set!");
766}
767
768CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
769  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
770    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
771
772  return 0;
773}
774
775MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
776  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
777}
778
779void
780CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
781                                             TemplateSpecializationKind TSK) {
782  assert(TemplateOrInstantiation.isNull() &&
783         "Previous template or instantiation?");
784  assert(!isa<ClassTemplateSpecializationDecl>(this));
785  TemplateOrInstantiation
786    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
787}
788
789TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
790  if (const ClassTemplateSpecializationDecl *Spec
791        = dyn_cast<ClassTemplateSpecializationDecl>(this))
792    return Spec->getSpecializationKind();
793
794  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
795    return MSInfo->getTemplateSpecializationKind();
796
797  return TSK_Undeclared;
798}
799
800void
801CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
802  if (ClassTemplateSpecializationDecl *Spec
803      = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
804    Spec->setSpecializationKind(TSK);
805    return;
806  }
807
808  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
809    MSInfo->setTemplateSpecializationKind(TSK);
810    return;
811  }
812
813  assert(false && "Not a class template or member class specialization");
814}
815
816CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
817  ASTContext &Context = getASTContext();
818  QualType ClassType = Context.getTypeDeclType(this);
819
820  DeclarationName Name
821    = Context.DeclarationNames.getCXXDestructorName(
822                                          Context.getCanonicalType(ClassType));
823
824  DeclContext::lookup_const_iterator I, E;
825  llvm::tie(I, E) = lookup(Name);
826  if (I == E)
827    return 0;
828
829  CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
830  assert(++I == E && "Found more than one destructor!");
831
832  return Dtor;
833}
834
835void CXXRecordDecl::completeDefinition() {
836  completeDefinition(0);
837}
838
839void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
840  RecordDecl::completeDefinition();
841
842  // If the class may be abstract (but hasn't been marked as such), check for
843  // any pure final overriders.
844  if (mayBeAbstract()) {
845    CXXFinalOverriderMap MyFinalOverriders;
846    if (!FinalOverriders) {
847      getFinalOverriders(MyFinalOverriders);
848      FinalOverriders = &MyFinalOverriders;
849    }
850
851    bool Done = false;
852    for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
853                                     MEnd = FinalOverriders->end();
854         M != MEnd && !Done; ++M) {
855      for (OverridingMethods::iterator SO = M->second.begin(),
856                                    SOEnd = M->second.end();
857           SO != SOEnd && !Done; ++SO) {
858        assert(SO->second.size() > 0 &&
859               "All virtual functions have overridding virtual functions");
860
861        // C++ [class.abstract]p4:
862        //   A class is abstract if it contains or inherits at least one
863        //   pure virtual function for which the final overrider is pure
864        //   virtual.
865        if (SO->second.front().Method->isPure()) {
866          data().Abstract = true;
867          Done = true;
868          break;
869        }
870      }
871    }
872  }
873
874  // Set access bits correctly on the directly-declared conversions.
875  for (UnresolvedSetIterator I = data().Conversions.begin(),
876                             E = data().Conversions.end();
877       I != E; ++I)
878    data().Conversions.setAccess(I, (*I)->getAccess());
879}
880
881bool CXXRecordDecl::mayBeAbstract() const {
882  if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
883      isDependentContext())
884    return false;
885
886  for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
887                                             BEnd = bases_end();
888       B != BEnd; ++B) {
889    CXXRecordDecl *BaseDecl
890      = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
891    if (BaseDecl->isAbstract())
892      return true;
893  }
894
895  return false;
896}
897
898CXXMethodDecl *
899CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
900                      const DeclarationNameInfo &NameInfo,
901                      QualType T, TypeSourceInfo *TInfo,
902                      bool isStatic, StorageClass SCAsWritten, bool isInline) {
903  return new (C) CXXMethodDecl(CXXMethod, RD, NameInfo, T, TInfo,
904                               isStatic, SCAsWritten, isInline);
905}
906
907bool CXXMethodDecl::isUsualDeallocationFunction() const {
908  if (getOverloadedOperator() != OO_Delete &&
909      getOverloadedOperator() != OO_Array_Delete)
910    return false;
911
912  // C++ [basic.stc.dynamic.deallocation]p2:
913  //   A template instance is never a usual deallocation function,
914  //   regardless of its signature.
915  if (getPrimaryTemplate())
916    return false;
917
918  // C++ [basic.stc.dynamic.deallocation]p2:
919  //   If a class T has a member deallocation function named operator delete
920  //   with exactly one parameter, then that function is a usual (non-placement)
921  //   deallocation function. [...]
922  if (getNumParams() == 1)
923    return true;
924
925  // C++ [basic.stc.dynamic.deallocation]p2:
926  //   [...] If class T does not declare such an operator delete but does
927  //   declare a member deallocation function named operator delete with
928  //   exactly two parameters, the second of which has type std::size_t (18.1),
929  //   then this function is a usual deallocation function.
930  ASTContext &Context = getASTContext();
931  if (getNumParams() != 2 ||
932      !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
933                                      Context.getSizeType()))
934    return false;
935
936  // This function is a usual deallocation function if there are no
937  // single-parameter deallocation functions of the same kind.
938  for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
939       R.first != R.second; ++R.first) {
940    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
941      if (FD->getNumParams() == 1)
942        return false;
943  }
944
945  return true;
946}
947
948bool CXXMethodDecl::isCopyAssignmentOperator() const {
949  // C++0x [class.copy]p19:
950  //  A user-declared copy assignment operator X::operator= is a non-static
951  //  non-template member function of class X with exactly one parameter of
952  //  type X, X&, const X&, volatile X& or const volatile X&.
953  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
954      /*non-static*/ isStatic() ||
955      /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
956      /*exactly one parameter*/getNumParams() != 1)
957    return false;
958
959  QualType ParamType = getParamDecl(0)->getType();
960  if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
961    ParamType = Ref->getPointeeType();
962
963  ASTContext &Context = getASTContext();
964  QualType ClassType
965    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
966  return Context.hasSameUnqualifiedType(ClassType, ParamType);
967}
968
969void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
970  assert(MD->isCanonicalDecl() && "Method is not canonical!");
971  assert(!MD->getParent()->isDependentContext() &&
972         "Can't add an overridden method to a class template!");
973
974  getASTContext().addOverriddenMethod(this, MD);
975}
976
977CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
978  return getASTContext().overridden_methods_begin(this);
979}
980
981CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
982  return getASTContext().overridden_methods_end(this);
983}
984
985unsigned CXXMethodDecl::size_overridden_methods() const {
986  return getASTContext().overridden_methods_size(this);
987}
988
989QualType CXXMethodDecl::getThisType(ASTContext &C) const {
990  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
991  // If the member function is declared const, the type of this is const X*,
992  // if the member function is declared volatile, the type of this is
993  // volatile X*, and if the member function is declared const volatile,
994  // the type of this is const volatile X*.
995
996  assert(isInstance() && "No 'this' for static methods!");
997
998  QualType ClassTy = C.getTypeDeclType(getParent());
999  ClassTy = C.getQualifiedType(ClassTy,
1000                               Qualifiers::fromCVRMask(getTypeQualifiers()));
1001  return C.getPointerType(ClassTy);
1002}
1003
1004bool CXXMethodDecl::hasInlineBody() const {
1005  // If this function is a template instantiation, look at the template from
1006  // which it was instantiated.
1007  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1008  if (!CheckFn)
1009    CheckFn = this;
1010
1011  const FunctionDecl *fn;
1012  return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1013}
1014
1015CXXBaseOrMemberInitializer::
1016CXXBaseOrMemberInitializer(ASTContext &Context,
1017                           TypeSourceInfo *TInfo, bool IsVirtual,
1018                           SourceLocation L, Expr *Init, SourceLocation R)
1019  : BaseOrMember(TInfo), Init(Init), AnonUnionMember(0),
1020    LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
1021    SourceOrderOrNumArrayIndices(0)
1022{
1023}
1024
1025CXXBaseOrMemberInitializer::
1026CXXBaseOrMemberInitializer(ASTContext &Context,
1027                           FieldDecl *Member, SourceLocation MemberLoc,
1028                           SourceLocation L, Expr *Init, SourceLocation R)
1029  : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
1030    AnonUnionMember(0), LParenLoc(L), RParenLoc(R), IsVirtual(false),
1031    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1032{
1033}
1034
1035CXXBaseOrMemberInitializer::
1036CXXBaseOrMemberInitializer(ASTContext &Context,
1037                           FieldDecl *Member, SourceLocation MemberLoc,
1038                           SourceLocation L, Expr *Init, SourceLocation R,
1039                           VarDecl **Indices,
1040                           unsigned NumIndices)
1041  : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
1042    AnonUnionMember(0), LParenLoc(L), RParenLoc(R), IsVirtual(false),
1043    IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1044{
1045  VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1046  memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1047}
1048
1049CXXBaseOrMemberInitializer *
1050CXXBaseOrMemberInitializer::Create(ASTContext &Context,
1051                                   FieldDecl *Member,
1052                                   SourceLocation MemberLoc,
1053                                   SourceLocation L,
1054                                   Expr *Init,
1055                                   SourceLocation R,
1056                                   VarDecl **Indices,
1057                                   unsigned NumIndices) {
1058  void *Mem = Context.Allocate(sizeof(CXXBaseOrMemberInitializer) +
1059                               sizeof(VarDecl *) * NumIndices,
1060                               llvm::alignof<CXXBaseOrMemberInitializer>());
1061  return new (Mem) CXXBaseOrMemberInitializer(Context, Member, MemberLoc,
1062                                              L, Init, R, Indices, NumIndices);
1063}
1064
1065TypeLoc CXXBaseOrMemberInitializer::getBaseClassLoc() const {
1066  if (isBaseInitializer())
1067    return BaseOrMember.get<TypeSourceInfo*>()->getTypeLoc();
1068  else
1069    return TypeLoc();
1070}
1071
1072Type *CXXBaseOrMemberInitializer::getBaseClass() {
1073  if (isBaseInitializer())
1074    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
1075  else
1076    return 0;
1077}
1078
1079const Type *CXXBaseOrMemberInitializer::getBaseClass() const {
1080  if (isBaseInitializer())
1081    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
1082  else
1083    return 0;
1084}
1085
1086SourceLocation CXXBaseOrMemberInitializer::getSourceLocation() const {
1087  if (isMemberInitializer())
1088    return getMemberLocation();
1089
1090  return getBaseClassLoc().getLocalSourceRange().getBegin();
1091}
1092
1093SourceRange CXXBaseOrMemberInitializer::getSourceRange() const {
1094  return SourceRange(getSourceLocation(), getRParenLoc());
1095}
1096
1097CXXConstructorDecl *
1098CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1099  return new (C) CXXConstructorDecl(0, DeclarationNameInfo(),
1100                                    QualType(), 0, false, false, false);
1101}
1102
1103CXXConstructorDecl *
1104CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1105                           const DeclarationNameInfo &NameInfo,
1106                           QualType T, TypeSourceInfo *TInfo,
1107                           bool isExplicit,
1108                           bool isInline,
1109                           bool isImplicitlyDeclared) {
1110  assert(NameInfo.getName().getNameKind()
1111         == DeclarationName::CXXConstructorName &&
1112         "Name must refer to a constructor");
1113  return new (C) CXXConstructorDecl(RD, NameInfo, T, TInfo, isExplicit,
1114                                    isInline, isImplicitlyDeclared);
1115}
1116
1117bool CXXConstructorDecl::isDefaultConstructor() const {
1118  // C++ [class.ctor]p5:
1119  //   A default constructor for a class X is a constructor of class
1120  //   X that can be called without an argument.
1121  return (getNumParams() == 0) ||
1122         (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1123}
1124
1125bool
1126CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1127  // C++ [class.copy]p2:
1128  //   A non-template constructor for class X is a copy constructor
1129  //   if its first parameter is of type X&, const X&, volatile X& or
1130  //   const volatile X&, and either there are no other parameters
1131  //   or else all other parameters have default arguments (8.3.6).
1132  if ((getNumParams() < 1) ||
1133      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1134      (getPrimaryTemplate() != 0) ||
1135      (getDescribedFunctionTemplate() != 0))
1136    return false;
1137
1138  const ParmVarDecl *Param = getParamDecl(0);
1139
1140  // Do we have a reference type? Rvalue references don't count.
1141  const LValueReferenceType *ParamRefType =
1142    Param->getType()->getAs<LValueReferenceType>();
1143  if (!ParamRefType)
1144    return false;
1145
1146  // Is it a reference to our class type?
1147  ASTContext &Context = getASTContext();
1148
1149  CanQualType PointeeType
1150    = Context.getCanonicalType(ParamRefType->getPointeeType());
1151  CanQualType ClassTy
1152    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1153  if (PointeeType.getUnqualifiedType() != ClassTy)
1154    return false;
1155
1156  // FIXME: other qualifiers?
1157
1158  // We have a copy constructor.
1159  TypeQuals = PointeeType.getCVRQualifiers();
1160  return true;
1161}
1162
1163bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1164  // C++ [class.conv.ctor]p1:
1165  //   A constructor declared without the function-specifier explicit
1166  //   that can be called with a single parameter specifies a
1167  //   conversion from the type of its first parameter to the type of
1168  //   its class. Such a constructor is called a converting
1169  //   constructor.
1170  if (isExplicit() && !AllowExplicit)
1171    return false;
1172
1173  return (getNumParams() == 0 &&
1174          getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1175         (getNumParams() == 1) ||
1176         (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
1177}
1178
1179bool CXXConstructorDecl::isCopyConstructorLikeSpecialization() const {
1180  if ((getNumParams() < 1) ||
1181      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1182      (getPrimaryTemplate() == 0) ||
1183      (getDescribedFunctionTemplate() != 0))
1184    return false;
1185
1186  const ParmVarDecl *Param = getParamDecl(0);
1187
1188  ASTContext &Context = getASTContext();
1189  CanQualType ParamType = Context.getCanonicalType(Param->getType());
1190
1191  // Strip off the lvalue reference, if any.
1192  if (CanQual<LValueReferenceType> ParamRefType
1193                                    = ParamType->getAs<LValueReferenceType>())
1194    ParamType = ParamRefType->getPointeeType();
1195
1196
1197  // Is it the same as our our class type?
1198  CanQualType ClassTy
1199    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1200  if (ParamType.getUnqualifiedType() != ClassTy)
1201    return false;
1202
1203  return true;
1204}
1205
1206CXXDestructorDecl *
1207CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1208  return new (C) CXXDestructorDecl(0, DeclarationNameInfo(),
1209                                   QualType(), 0, false, false);
1210}
1211
1212CXXDestructorDecl *
1213CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1214                          const DeclarationNameInfo &NameInfo,
1215                          QualType T, TypeSourceInfo *TInfo,
1216                          bool isInline,
1217                          bool isImplicitlyDeclared) {
1218  assert(NameInfo.getName().getNameKind()
1219         == DeclarationName::CXXDestructorName &&
1220         "Name must refer to a destructor");
1221  return new (C) CXXDestructorDecl(RD, NameInfo, T, TInfo, isInline,
1222                                   isImplicitlyDeclared);
1223}
1224
1225CXXConversionDecl *
1226CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
1227  return new (C) CXXConversionDecl(0, DeclarationNameInfo(),
1228                                   QualType(), 0, false, false);
1229}
1230
1231CXXConversionDecl *
1232CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1233                          const DeclarationNameInfo &NameInfo,
1234                          QualType T, TypeSourceInfo *TInfo,
1235                          bool isInline, bool isExplicit) {
1236  assert(NameInfo.getName().getNameKind()
1237         == DeclarationName::CXXConversionFunctionName &&
1238         "Name must refer to a conversion function");
1239  return new (C) CXXConversionDecl(RD, NameInfo, T, TInfo,
1240                                   isInline, isExplicit);
1241}
1242
1243LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1244                                         DeclContext *DC,
1245                                         SourceLocation L,
1246                                         LanguageIDs Lang, bool Braces) {
1247  return new (C) LinkageSpecDecl(DC, L, Lang, Braces);
1248}
1249
1250UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1251                                               SourceLocation L,
1252                                               SourceLocation NamespaceLoc,
1253                                               SourceRange QualifierRange,
1254                                               NestedNameSpecifier *Qualifier,
1255                                               SourceLocation IdentLoc,
1256                                               NamedDecl *Used,
1257                                               DeclContext *CommonAncestor) {
1258  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1259    Used = NS->getOriginalNamespace();
1260  return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange,
1261                                    Qualifier, IdentLoc, Used, CommonAncestor);
1262}
1263
1264NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1265  if (NamespaceAliasDecl *NA =
1266        dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1267    return NA->getNamespace();
1268  return cast_or_null<NamespaceDecl>(NominatedNamespace);
1269}
1270
1271NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1272                                               SourceLocation UsingLoc,
1273                                               SourceLocation AliasLoc,
1274                                               IdentifierInfo *Alias,
1275                                               SourceRange QualifierRange,
1276                                               NestedNameSpecifier *Qualifier,
1277                                               SourceLocation IdentLoc,
1278                                               NamedDecl *Namespace) {
1279  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1280    Namespace = NS->getOriginalNamespace();
1281  return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias, QualifierRange,
1282                                    Qualifier, IdentLoc, Namespace);
1283}
1284
1285UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC,
1286                             SourceRange NNR, SourceLocation UL,
1287                             NestedNameSpecifier* TargetNNS,
1288                             const DeclarationNameInfo &NameInfo,
1289                             bool IsTypeNameArg) {
1290  return new (C) UsingDecl(DC, NNR, UL, TargetNNS, NameInfo, IsTypeNameArg);
1291}
1292
1293UnresolvedUsingValueDecl *
1294UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1295                                 SourceLocation UsingLoc,
1296                                 SourceRange TargetNNR,
1297                                 NestedNameSpecifier *TargetNNS,
1298                                 const DeclarationNameInfo &NameInfo) {
1299  return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1300                                          TargetNNR, TargetNNS, NameInfo);
1301}
1302
1303UnresolvedUsingTypenameDecl *
1304UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1305                                    SourceLocation UsingLoc,
1306                                    SourceLocation TypenameLoc,
1307                                    SourceRange TargetNNR,
1308                                    NestedNameSpecifier *TargetNNS,
1309                                    SourceLocation TargetNameLoc,
1310                                    DeclarationName TargetName) {
1311  return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1312                                             TargetNNR, TargetNNS,
1313                                             TargetNameLoc,
1314                                             TargetName.getAsIdentifierInfo());
1315}
1316
1317StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1318                                           SourceLocation L, Expr *AssertExpr,
1319                                           StringLiteral *Message) {
1320  return new (C) StaticAssertDecl(DC, L, AssertExpr, Message);
1321}
1322
1323static const char *getAccessName(AccessSpecifier AS) {
1324  switch (AS) {
1325    default:
1326    case AS_none:
1327      assert("Invalid access specifier!");
1328      return 0;
1329    case AS_public:
1330      return "public";
1331    case AS_private:
1332      return "private";
1333    case AS_protected:
1334      return "protected";
1335  }
1336}
1337
1338const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1339                                           AccessSpecifier AS) {
1340  return DB << getAccessName(AS);
1341}
1342