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