1 //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ related Decl classes.
12 //===----------------------------------------------------------------------===//
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;
24 //===----------------------------------------------------------------------===//
25 // Decl Allocation/Deallocation Method Implementations
26 //===----------------------------------------------------------------------===//
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) {
41 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
42 SourceLocation L, IdentifierInfo *Id,
43 CXXRecordDecl *PrevDecl,
45 : RecordDecl(K, TK, DC, L, Id, PrevDecl, TKL),
46 DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
47 TemplateOrInstantiation() { }
49 CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
50 SourceLocation L, IdentifierInfo *Id,
52 CXXRecordDecl* PrevDecl,
53 bool DelayTypeCreation) {
54 CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id,
57 // FIXME: DelayTypeCreation seems like such a hack
58 if (!DelayTypeCreation)
59 C.getTypeDeclType(R, PrevDecl);
63 CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, EmptyShell Empty) {
64 return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(), 0, 0,
68 CXXRecordDecl::~CXXRecordDecl() {
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());
77 this->RecordDecl::Destroy(C);
81 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
83 ASTContext &C = getASTContext();
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;
91 C.Deallocate(data().Bases);
93 // The set of seen virtual base types.
94 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
96 // The virtual bases of this class.
97 llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
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())
109 CXXRecordDecl *BaseClassDecl
110 = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
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);
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);
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();
138 // Skip dependent types; we can't do any checking on them now.
139 if (VBaseType->isDependentType())
142 CXXRecordDecl *VBaseClassDecl
143 = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
146 CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true,
147 VBaseClassDecl->getTagKind() == TTK_Class,
148 VBases[I]->getAccessSpecifier(), VBaseType);
152 /// Callback function for CXXRecordDecl::forallBases that acknowledges
153 /// that it saw a base class.
154 static bool SawBase(const CXXRecordDecl *, void *) {
158 bool CXXRecordDecl::hasAnyDependentBases() const {
159 if (!isDependentContext())
162 return !forallBases(SawBase, 0);
165 bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const {
166 return getCopyConstructor(Context, Qualifiers::Const) != 0;
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) {
177 if (Cands.size() == 1)
178 return Cands[0].first;
180 unsigned Best = 0, N = Cands.size();
181 for (unsigned I = 1; I != N; ++I)
182 if (Cands[Best].second.isSupersetOf(Cands[I].second))
185 for (unsigned I = 1; I != N; ++I)
186 if (Cands[Best].second.isSupersetOf(Cands[I].second))
189 return Cands[Best].first;
192 CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context,
193 unsigned TypeQuals) const{
195 = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
196 DeclarationName ConstructorName
197 = Context.DeclarationNames.getCXXConstructorName(
198 Context.getCanonicalType(ClassType));
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))
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)));
219 return cast_or_null<CXXConstructorDecl>(
220 GetBestOverloadCandidateSimple(Found));
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);
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())
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())
246 QualType ArgType = FnType->getArgType(0);
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())
255 Quals = ArgType.getQualifiers();
257 // By-value copy-assignment operators are treated like const X&
258 // copy-assignment operators.
259 Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
262 if (!Context.hasSameUnqualifiedType(ArgType, Class))
265 // Save this copy-assignment operator. It might be "the one".
266 Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
269 // Use a simplistic form of overload resolution to find the candidate.
270 return GetBestOverloadCandidateSimple(Found);
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;
280 // Note that we have no need of an implicitly-declared default constructor.
281 data().DeclaredDefaultConstructor = true;
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;
289 // A POD-struct is an aggregate class [...]
290 data().PlainOldData = false;
292 // C++ [class.ctor]p5:
293 // A constructor is trivial if it is an implicitly-declared default
295 // FIXME: C++0x: don't do this for "= default" default constructors.
296 data().HasTrivialConstructor = false;
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;
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;
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());
319 // Copy assignment operators must be non-templates.
320 if (OpDecl->getPrimaryTemplate() || OpDecl->getDescribedFunctionTemplate())
323 QualType ArgType = FnType->getArgType(0);
324 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>())
325 ArgType = Ref->getPointeeType();
327 ArgType = ArgType.getUnqualifiedType();
328 QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
329 const_cast<CXXRecordDecl*>(this)));
331 if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
334 // This is a copy assignment operator.
335 // Note on the decl that it is a copy assignment operator.
336 OpDecl->setCopyAssignment(true);
338 // Suppress the implicit declaration of a copy constructor.
339 data().UserDeclaredCopyAssignment = true;
340 data().DeclaredCopyAssignment = true;
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;
348 // A POD-struct is an aggregate class that [...] has no user-defined copy
349 // assignment operator [...].
350 data().PlainOldData = false;
353 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
355 if (isa<UsingShadowDecl>(Conv))
356 Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
357 if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
358 T = ConvTemp->getTemplatedDecl()->getResultType();
360 T = cast<CXXConversionDecl>(Conv)->getConversionType();
361 return Context.getCanonicalType(T);
364 /// Collect the visible conversions of a base class.
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
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,
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;
390 // Collect the direct conversions and figure out which conversions
391 // will be hidden in the subclasses.
392 UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
394 HiddenTypesBuffer = ParentHiddenTypes;
395 HiddenTypes = &HiddenTypesBuffer;
397 for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
399 !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
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()));
406 // If this conversion isn't hidden, add it to the appropriate output.
408 AccessSpecifier IAccess
409 = CXXRecordDecl::MergeAccess(Access, I.getAccess());
412 VOutput.addDecl(I.getDecl(), IAccess);
414 Output.addDecl(I.getDecl(), IAccess);
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>();
425 AccessSpecifier BaseAccess
426 = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
427 bool BaseInVirtual = InVirtual || I->isVirtual();
429 CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
430 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
431 *HiddenTypes, Output, VOutput, HiddenVBaseCs);
435 /// Collect the visible conversions of a class.
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;
447 // The set of conversions in virtual bases that we've determined to
449 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
451 // The set of types hidden by classes derived from this one.
452 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
454 // Go ahead and collect the direct conversions and add them to the
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()));
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>();
467 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
468 I->isVirtual(), I->getAccessSpecifier(),
469 HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
472 // Add any unhidden conversions provided by virtual bases.
473 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
475 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
476 Output.addDecl(I.getDecl(), I.getAccess());
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;
495 void CXXRecordDecl::CheckConversionFunction(NamedDecl *ConvDecl) {
496 assert(ConvDecl->getDeclContext() == this &&
497 "conversion function does not belong to this record");
499 ConvDecl = ConvDecl->getUnderlyingDecl();
500 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(ConvDecl)) {
501 assert(isa<CXXConversionDecl>(Temp->getTemplatedDecl()));
503 assert(isa<CXXConversionDecl>(ConvDecl));
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.:
513 // using B::operator int;
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.
520 UnresolvedSetImpl &Convs = *getConversionFunctions();
521 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
522 if (Convs[I].getDecl() == ConvDecl) {
524 assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
525 && "conversion was found multiple times in unresolved set");
530 llvm_unreachable("conversion not found in set!");
533 void CXXRecordDecl::setMethodAsVirtual(FunctionDecl *Method) {
534 Method->setVirtualAsWritten(true);
538 setPolymorphic(true);
539 setHasTrivialConstructor(false);
540 setHasTrivialCopyConstructor(false);
541 setHasTrivialCopyAssignment(false);
544 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
545 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
546 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
551 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
552 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
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);
565 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
566 if (const ClassTemplateSpecializationDecl *Spec
567 = dyn_cast<ClassTemplateSpecializationDecl>(this))
568 return Spec->getSpecializationKind();
570 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
571 return MSInfo->getTemplateSpecializationKind();
573 return TSK_Undeclared;
577 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
578 if (ClassTemplateSpecializationDecl *Spec
579 = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
580 Spec->setSpecializationKind(TSK);
584 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
585 MSInfo->setTemplateSpecializationKind(TSK);
589 assert(false && "Not a class template or member class specialization");
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()));
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))
607 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
608 if (Constructor->isDefaultConstructor())
614 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
615 ASTContext &Context = getASTContext();
616 QualType ClassType = Context.getTypeDeclType(this);
619 = Context.DeclarationNames.getCXXDestructorName(
620 Context.getCanonicalType(ClassType));
622 DeclContext::lookup_const_iterator I, E;
623 llvm::tie(I, E) = lookup(Name);
624 assert(I != E && "Did not find a destructor!");
626 CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
627 assert(++I == E && "Found more than one destructor!");
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);
641 bool CXXMethodDecl::isUsualDeallocationFunction() const {
642 if (getOverloadedOperator() != OO_Delete &&
643 getOverloadedOperator() != OO_Array_Delete)
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())
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)
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()))
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)
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)
693 QualType ParamType = getParamDecl(0)->getType();
694 if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
695 ParamType = Ref->getPointeeType();
697 ASTContext &Context = getASTContext();
699 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
700 return Context.hasSameUnqualifiedType(ClassType, ParamType);
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!");
708 getASTContext().addOverriddenMethod(this, MD);
711 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
712 return getASTContext().overridden_methods_begin(this);
715 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
716 return getASTContext().overridden_methods_end(this);
719 unsigned CXXMethodDecl::size_overridden_methods() const {
720 return getASTContext().overridden_methods_size(this);
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*.
730 assert(isInstance() && "No 'this' for static methods!");
732 QualType ClassTy = C.getTypeDeclType(getParent());
733 ClassTy = C.getQualifiedType(ClassTy,
734 Qualifiers::fromCVRMask(getTypeQualifiers()));
735 return C.getPointerType(ClassTy);
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();
745 const FunctionDecl *fn;
746 return CheckFn->hasBody(fn) && !fn->isOutOfLine();
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)
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)
769 CXXBaseOrMemberInitializer::
770 CXXBaseOrMemberInitializer(ASTContext &Context,
771 FieldDecl *Member, SourceLocation MemberLoc,
772 SourceLocation L, Expr *Init, SourceLocation R,
775 : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
776 AnonUnionMember(0), LParenLoc(L), RParenLoc(R), IsVirtual(false),
777 IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
779 VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
780 memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
783 CXXBaseOrMemberInitializer *
784 CXXBaseOrMemberInitializer::Create(ASTContext &Context,
786 SourceLocation MemberLoc,
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);
799 void CXXBaseOrMemberInitializer::Destroy(ASTContext &Context) {
801 Init->Destroy(Context);
802 // FIXME: Destroy indices
803 this->~CXXBaseOrMemberInitializer();
806 TypeLoc CXXBaseOrMemberInitializer::getBaseClassLoc() const {
807 if (isBaseInitializer())
808 return BaseOrMember.get<TypeSourceInfo*>()->getTypeLoc();
813 Type *CXXBaseOrMemberInitializer::getBaseClass() {
814 if (isBaseInitializer())
815 return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
820 const Type *CXXBaseOrMemberInitializer::getBaseClass() const {
821 if (isBaseInitializer())
822 return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
827 SourceLocation CXXBaseOrMemberInitializer::getSourceLocation() const {
828 if (isMemberInitializer())
829 return getMemberLocation();
831 return getBaseClassLoc().getLocalSourceRange().getBegin();
834 SourceRange CXXBaseOrMemberInitializer::getSourceRange() const {
835 return SourceRange(getSourceLocation(), getRParenLoc());
839 CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
840 return new (C) CXXConstructorDecl(0, SourceLocation(), DeclarationName(),
841 QualType(), 0, false, false, false);
845 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
846 SourceLocation L, DeclarationName N,
847 QualType T, TypeSourceInfo *TInfo,
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);
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());
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))
878 const ParmVarDecl *Param = getParamDecl(0);
880 // Do we have a reference type? Rvalue references don't count.
881 const LValueReferenceType *ParamRefType =
882 Param->getType()->getAs<LValueReferenceType>();
886 // Is it a reference to our class type?
887 ASTContext &Context = getASTContext();
889 CanQualType PointeeType
890 = Context.getCanonicalType(ParamRefType->getPointeeType());
892 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
893 if (PointeeType.getUnqualifiedType() != ClassTy)
896 // FIXME: other qualifiers?
898 // We have a copy constructor.
899 TypeQuals = PointeeType.getCVRQualifiers();
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
910 if (isExplicit() && !AllowExplicit)
913 return (getNumParams() == 0 &&
914 getType()->getAs<FunctionProtoType>()->isVariadic()) ||
915 (getNumParams() == 1) ||
916 (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
919 bool CXXConstructorDecl::isCopyConstructorLikeSpecialization() const {
920 if ((getNumParams() < 1) ||
921 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
922 (getPrimaryTemplate() == 0) ||
923 (getDescribedFunctionTemplate() != 0))
926 const ParmVarDecl *Param = getParamDecl(0);
928 ASTContext &Context = getASTContext();
929 CanQualType ParamType = Context.getCanonicalType(Param->getType());
931 // Strip off the lvalue reference, if any.
932 if (CanQual<LValueReferenceType> ParamRefType
933 = ParamType->getAs<LValueReferenceType>())
934 ParamType = ParamRefType->getPointeeType();
937 // Is it the same as our our class type?
939 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
940 if (ParamType.getUnqualifiedType() != ClassTy)
947 CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
948 return new (C) CXXDestructorDecl(0, SourceLocation(), DeclarationName(),
949 QualType(), false, false);
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);
963 CXXConstructorDecl::Destroy(ASTContext& C) {
964 C.Deallocate(BaseOrMemberInitializers);
965 CXXMethodDecl::Destroy(C);
969 CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
970 return new (C) CXXConversionDecl(0, SourceLocation(), DeclarationName(),
971 QualType(), 0, false, false);
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);
984 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
987 LanguageIDs Lang, bool Braces) {
988 return new (C) LinkageSpecDecl(DC, L, Lang, Braces);
991 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
993 SourceLocation NamespaceLoc,
994 SourceRange QualifierRange,
995 NestedNameSpecifier *Qualifier,
996 SourceLocation IdentLoc,
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);
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);
1012 void UsingDirectiveDecl::setNominatedNamespace(NamedDecl* ND) {
1013 assert((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
1014 "expected a NamespaceDecl or NamespaceAliasDecl");
1015 NominatedNamespace = ND;
1018 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
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);
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);
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);
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,
1062 TargetName.getAsIdentifierInfo());
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);
1071 void StaticAssertDecl::Destroy(ASTContext& C) {
1072 AssertExpr->Destroy(C);
1073 Message->Destroy(C);
1077 StaticAssertDecl::~StaticAssertDecl() {
1080 static const char *getAccessName(AccessSpecifier AS) {
1084 assert("Invalid access specifier!");
1095 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1096 AccessSpecifier AS) {
1097 return DB << getAccessName(AS);