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/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"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // Decl Allocation/Deallocation Method Implementations
28 //===----------------------------------------------------------------------===//
30 CXXRecordDecl::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), IsStandardLayout(true), HasNoNonEmptyBases(true),
35 HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
36 HasTrivialConstructor(true), HasConstExprNonCopyMoveConstructor(false),
37 HasTrivialCopyConstructor(true), HasTrivialMoveConstructor(true),
38 HasTrivialCopyAssignment(true), HasTrivialMoveAssignment(true),
39 HasTrivialDestructor(true), HasNonLiteralTypeFieldsOrBases(false),
40 ComputedVisibleConversions(false),
41 DeclaredDefaultConstructor(false), DeclaredCopyConstructor(false),
42 DeclaredCopyAssignment(false), DeclaredDestructor(false),
43 NumBases(0), NumVBases(0), Bases(), VBases(),
44 Definition(D), FirstFriend(0) {
47 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
48 SourceLocation StartLoc, SourceLocation IdLoc,
49 IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
50 : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
51 DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
52 TemplateOrInstantiation() { }
54 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
55 DeclContext *DC, SourceLocation StartLoc,
56 SourceLocation IdLoc, IdentifierInfo *Id,
57 CXXRecordDecl* PrevDecl,
58 bool DelayTypeCreation) {
59 CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
62 // FIXME: DelayTypeCreation seems like such a hack
63 if (!DelayTypeCreation)
64 C.getTypeDeclType(R, PrevDecl);
68 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
69 return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(),
70 SourceLocation(), 0, 0);
74 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
76 ASTContext &C = getASTContext();
78 // C++ [dcl.init.aggr]p1:
79 // An aggregate is an array or a class (clause 9) with [...]
80 // no base classes [...].
81 data().Aggregate = false;
83 if (!data().Bases.isOffset() && data().NumBases > 0)
84 C.Deallocate(data().getBases());
86 // The set of seen virtual base types.
87 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
89 // The virtual bases of this class.
90 llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
92 data().Bases = new(C) CXXBaseSpecifier [NumBases];
93 data().NumBases = NumBases;
94 for (unsigned i = 0; i < NumBases; ++i) {
95 data().getBases()[i] = *Bases[i];
96 // Keep track of inherited vbases for this base class.
97 const CXXBaseSpecifier *Base = Bases[i];
98 QualType BaseType = Base->getType();
99 // Skip dependent types; we can't do any checking on them now.
100 if (BaseType->isDependentType())
102 CXXRecordDecl *BaseClassDecl
103 = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
105 // C++ [dcl.init.aggr]p1:
106 // An aggregate is [...] a class with [...] no base classes [...].
107 data().Aggregate = false;
110 // A POD-struct is an aggregate class...
111 data().PlainOldData = false;
113 // A class with a non-empty base class is not empty.
114 // FIXME: Standard ref?
115 if (!BaseClassDecl->isEmpty()) {
118 // A standard-layout class is a class that:
120 // -- either has no non-static data members in the most derived
121 // class and at most one base class with non-static data members,
122 // or has no base classes with non-static data members, and
123 // If this is the second non-empty base, then neither of these two
124 // clauses can be true.
125 data().IsStandardLayout = false;
128 data().Empty = false;
129 data().HasNoNonEmptyBases = false;
132 // C++ [class.virtual]p1:
133 // A class that declares or inherits a virtual function is called a
134 // polymorphic class.
135 if (BaseClassDecl->isPolymorphic())
136 data().Polymorphic = true;
139 // A standard-layout class is a class that: [...]
140 // -- has no non-standard-layout base classes
141 if (!BaseClassDecl->isStandardLayout())
142 data().IsStandardLayout = false;
144 // Record if this base is the first non-literal field or base.
145 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
146 data().HasNonLiteralTypeFieldsOrBases = true;
148 // Now go through all virtual bases of this base and add them.
149 for (CXXRecordDecl::base_class_iterator VBase =
150 BaseClassDecl->vbases_begin(),
151 E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
152 // Add this base if it's not already in the list.
153 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
154 VBases.push_back(VBase);
157 if (Base->isVirtual()) {
158 // Add this base if it's not already in the list.
159 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
160 VBases.push_back(Base);
162 // C++0x [meta.unary.prop] is_empty:
163 // T is a class type, but not a union type, with ... no virtual base
165 data().Empty = false;
167 // C++ [class.ctor]p5:
168 // A constructor is trivial if its class has no virtual base classes.
169 data().HasTrivialConstructor = false;
171 // C++0x [class.copy]p13:
172 // A copy/move constructor for class X is trivial if it is neither
173 // user-provided nor deleted and if
174 // -- class X has no virtual functions and no virtual base classes, and
175 data().HasTrivialCopyConstructor = false;
176 data().HasTrivialMoveConstructor = false;
178 // C++0x [class.copy]p27:
179 // A copy/move assignment operator for class X is trivial if it is
180 // neither user-provided nor deleted and if
181 // -- class X has no virtual functions and no virtual base classes, and
182 data().HasTrivialCopyAssignment = false;
183 data().HasTrivialMoveAssignment = false;
186 // A standard-layout class is a class that: [...]
187 // -- has [...] no virtual base classes
188 data().IsStandardLayout = false;
190 // C++ [class.ctor]p5:
191 // A constructor is trivial if all the direct base classes of its
192 // class have trivial constructors.
193 if (!BaseClassDecl->hasTrivialConstructor())
194 data().HasTrivialConstructor = false;
196 // C++0x [class.copy]p13:
197 // A copy/move constructor for class X is trivial if [...]
199 // -- the constructor selected to copy/move each direct base class
200 // subobject is trivial, and
201 // FIXME: C++0x: We need to only consider the selected constructor
202 // instead of all of them.
203 if (!BaseClassDecl->hasTrivialCopyConstructor())
204 data().HasTrivialCopyConstructor = false;
205 if (!BaseClassDecl->hasTrivialMoveConstructor())
206 data().HasTrivialMoveConstructor = false;
208 // C++0x [class.copy]p27:
209 // A copy/move assignment operator for class X is trivial if [...]
211 // -- the assignment operator selected to copy/move each direct base
212 // class subobject is trivial, and
213 // FIXME: C++0x: We need to only consider the selected operator instead
215 if (!BaseClassDecl->hasTrivialCopyAssignment())
216 data().HasTrivialCopyAssignment = false;
217 if (!BaseClassDecl->hasTrivialMoveAssignment())
218 data().HasTrivialMoveAssignment = false;
221 // C++ [class.ctor]p3:
222 // A destructor is trivial if all the direct base classes of its class
223 // have trivial destructors.
224 if (!BaseClassDecl->hasTrivialDestructor())
225 data().HasTrivialDestructor = false;
231 // Create base specifier for any direct or indirect virtual bases.
232 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
233 data().NumVBases = VBases.size();
234 for (int I = 0, E = VBases.size(); I != E; ++I) {
235 TypeSourceInfo *VBaseTypeInfo = VBases[I]->getTypeSourceInfo();
237 // Skip dependent types; we can't do any checking on them now.
238 if (VBaseTypeInfo->getType()->isDependentType())
241 CXXRecordDecl *VBaseClassDecl = cast<CXXRecordDecl>(
242 VBaseTypeInfo->getType()->getAs<RecordType>()->getDecl());
244 data().getVBases()[I] =
245 CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true,
246 VBaseClassDecl->getTagKind() == TTK_Class,
247 VBases[I]->getAccessSpecifier(), VBaseTypeInfo,
252 /// Callback function for CXXRecordDecl::forallBases that acknowledges
253 /// that it saw a base class.
254 static bool SawBase(const CXXRecordDecl *, void *) {
258 bool CXXRecordDecl::hasAnyDependentBases() const {
259 if (!isDependentContext())
262 return !forallBases(SawBase, 0);
265 bool CXXRecordDecl::hasConstCopyConstructor(const ASTContext &Context) const {
266 return getCopyConstructor(Context, Qualifiers::Const) != 0;
269 bool CXXRecordDecl::isTriviallyCopyable() const {
271 // A trivially copyable class is a class that:
272 // -- has no non-trivial copy constructors,
273 if (!hasTrivialCopyConstructor()) return false;
274 // -- has no non-trivial move constructors,
275 if (!hasTrivialMoveConstructor()) return false;
276 // -- has no non-trivial copy assignment operators,
277 if (!hasTrivialCopyAssignment()) return false;
278 // -- has no non-trivial move assignment operators, and
279 if (!hasTrivialMoveAssignment()) return false;
280 // -- has a trivial destructor.
281 if (!hasTrivialDestructor()) return false;
286 /// \brief Perform a simplistic form of overload resolution that only considers
287 /// cv-qualifiers on a single parameter, and return the best overload candidate
288 /// (if there is one).
289 static CXXMethodDecl *
290 GetBestOverloadCandidateSimple(
291 const llvm::SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
294 if (Cands.size() == 1)
295 return Cands[0].first;
297 unsigned Best = 0, N = Cands.size();
298 for (unsigned I = 1; I != N; ++I)
299 if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
302 for (unsigned I = 1; I != N; ++I)
303 if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
306 return Cands[Best].first;
309 CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(const ASTContext &Context,
310 unsigned TypeQuals) const{
312 = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
313 DeclarationName ConstructorName
314 = Context.DeclarationNames.getCXXConstructorName(
315 Context.getCanonicalType(ClassType));
317 llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
318 DeclContext::lookup_const_iterator Con, ConEnd;
319 for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
320 Con != ConEnd; ++Con) {
321 // C++ [class.copy]p2:
322 // A non-template constructor for class X is a copy constructor if [...]
323 if (isa<FunctionTemplateDecl>(*Con))
326 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
327 if (Constructor->isCopyConstructor(FoundTQs)) {
328 if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
329 (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
330 Found.push_back(std::make_pair(
331 const_cast<CXXConstructorDecl *>(Constructor),
332 Qualifiers::fromCVRMask(FoundTQs)));
336 return cast_or_null<CXXConstructorDecl>(
337 GetBestOverloadCandidateSimple(Found));
340 CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
341 ASTContext &Context = getASTContext();
342 QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
343 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
345 llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
346 DeclContext::lookup_const_iterator Op, OpEnd;
347 for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
348 // C++ [class.copy]p9:
349 // A user-declared copy assignment operator is a non-static non-template
350 // member function of class X with exactly one parameter of type X, X&,
351 // const X&, volatile X& or const volatile X&.
352 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
353 if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
356 const FunctionProtoType *FnType
357 = Method->getType()->getAs<FunctionProtoType>();
358 assert(FnType && "Overloaded operator has no prototype.");
359 // Don't assert on this; an invalid decl might have been left in the AST.
360 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
363 QualType ArgType = FnType->getArgType(0);
365 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
366 ArgType = Ref->getPointeeType();
367 // If we have a const argument and we have a reference to a non-const,
368 // this function does not match.
369 if (ArgIsConst && !ArgType.isConstQualified())
372 Quals = ArgType.getQualifiers();
374 // By-value copy-assignment operators are treated like const X&
375 // copy-assignment operators.
376 Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
379 if (!Context.hasSameUnqualifiedType(ArgType, Class))
382 // Save this copy-assignment operator. It might be "the one".
383 Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
386 // Use a simplistic form of overload resolution to find the candidate.
387 return GetBestOverloadCandidateSimple(Found);
390 void CXXRecordDecl::markedVirtualFunctionPure() {
391 // C++ [class.abstract]p2:
392 // A class is abstract if it has at least one pure virtual function.
393 data().Abstract = true;
396 void CXXRecordDecl::addedMember(Decl *D) {
397 // Ignore friends and invalid declarations.
398 if (D->getFriendObjectKind() || D->isInvalidDecl())
401 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
403 D = FunTmpl->getTemplatedDecl();
405 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
406 if (Method->isVirtual()) {
407 // C++ [dcl.init.aggr]p1:
408 // An aggregate is an array or a class with [...] no virtual functions.
409 data().Aggregate = false;
412 // A POD-struct is an aggregate class...
413 data().PlainOldData = false;
415 // Virtual functions make the class non-empty.
416 // FIXME: Standard ref?
417 data().Empty = false;
419 // C++ [class.virtual]p1:
420 // A class that declares or inherits a virtual function is called a
421 // polymorphic class.
422 data().Polymorphic = true;
424 // None of the special member functions are trivial.
425 data().HasTrivialConstructor = false;
427 // C++0x [class.copy]p13:
428 // A copy/move constructor for class X is trivial if [...]
429 // -- class X has no virtual functions [...]
430 data().HasTrivialCopyConstructor = false;
431 data().HasTrivialMoveConstructor = false;
433 // C++0x [class.copy]p27:
434 // A copy/move assignment operator for class X is trivial if [...]
435 // -- class X has no virtual functions [...]
436 data().HasTrivialCopyAssignment = false;
437 data().HasTrivialMoveAssignment = false;
438 // FIXME: Destructor?
441 // A standard-layout class is a class that: [...]
442 // -- has no virtual functions
443 data().IsStandardLayout = false;
447 if (D->isImplicit()) {
448 // Notify that an implicit member was added after the definition
450 if (!isBeingDefined())
451 if (ASTMutationListener *L = getASTMutationListener())
452 L->AddedCXXImplicitMember(data().Definition, D);
454 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
455 // If this is the implicit default constructor, note that we have now
457 if (Constructor->isDefaultConstructor())
458 data().DeclaredDefaultConstructor = true;
459 // If this is the implicit copy constructor, note that we have now
461 else if (Constructor->isCopyConstructor())
462 data().DeclaredCopyConstructor = true;
466 if (isa<CXXDestructorDecl>(D)) {
467 data().DeclaredDestructor = true;
471 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
472 // If this is the implicit copy constructor, note that we have now
474 // FIXME: Move constructors
475 if (Method->getOverloadedOperator() == OO_Equal)
476 data().DeclaredCopyAssignment = true;
480 // Any other implicit declarations are handled like normal declarations.
483 // Handle (user-declared) constructors.
484 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
485 // Note that we have a user-declared constructor.
486 data().UserDeclaredConstructor = true;
488 // Note that we have no need of an implicitly-declared default constructor.
489 data().DeclaredDefaultConstructor = true;
491 // C++ [dcl.init.aggr]p1:
492 // An aggregate is an array or a class (clause 9) with no
493 // user-declared constructors (12.1) [...].
494 data().Aggregate = false;
497 // A POD-struct is an aggregate class [...]
498 data().PlainOldData = false;
500 // C++ [class.ctor]p5:
501 // A constructor is trivial if it is an implicitly-declared default
503 // FIXME: C++0x: don't do this for "= default" default constructors.
504 data().HasTrivialConstructor = false;
506 // Note when we have a user-declared copy or move constructor, which will
507 // suppress the implicit declaration of those constructors.
509 if (Constructor->isCopyConstructor()) {
510 data().UserDeclaredCopyConstructor = true;
511 data().DeclaredCopyConstructor = true;
513 // C++0x [class.copy]p13:
514 // A copy/move constructor for class X is trivial if it is neither
515 // user-provided nor deleted
516 // FIXME: C++0x: don't do this for "= default" copy constructors.
517 data().HasTrivialCopyConstructor = false;
518 } else if (Constructor->isMoveConstructor()) {
519 // C++0x [class.copy]p13:
520 // A copy/move constructor for class X is trivial if it is neither
521 // user-provided nor deleted
522 // FIXME: C++0x: don't do this for "= default" move constructors.
523 data().HasTrivialMoveConstructor = false;
526 if (Constructor->isConstExpr() &&
527 !Constructor->isCopyOrMoveConstructor()) {
528 // Record if we see any constexpr constructors which are niether copy
529 // nor move constructors.
530 data().HasConstExprNonCopyMoveConstructor = true;
536 // Handle (user-declared) destructors.
537 if (isa<CXXDestructorDecl>(D)) {
538 data().DeclaredDestructor = true;
539 data().UserDeclaredDestructor = true;
542 // A POD-struct is an aggregate class that has [...] no user-defined
544 data().PlainOldData = false;
546 // C++ [class.dtor]p3:
547 // A destructor is trivial if it is an implicitly-declared destructor and
550 // FIXME: C++0x: don't do this for "= default" destructors
551 data().HasTrivialDestructor = false;
556 // Handle (user-declared) member functions.
557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
558 if (Method->getOverloadedOperator() == OO_Equal) {
559 // We're interested specifically in copy assignment operators.
560 const FunctionProtoType *FnType
561 = Method->getType()->getAs<FunctionProtoType>();
562 assert(FnType && "Overloaded operator has no proto function type.");
563 assert(FnType->getNumArgs() == 1 && !FnType->isVariadic());
565 // Copy assignment operators must be non-templates.
566 if (Method->getPrimaryTemplate() || FunTmpl)
569 ASTContext &Context = getASTContext();
570 QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
571 const_cast<CXXRecordDecl*>(this)));
573 bool isRValueRefArg = false;
574 QualType ArgType = FnType->getArgType(0);
575 if (const LValueReferenceType *Ref =
576 ArgType->getAs<LValueReferenceType>()) {
577 ArgType = Ref->getPointeeType();
578 } else if (const RValueReferenceType *Ref =
579 ArgType->getAs<RValueReferenceType>()) {
580 ArgType = Ref->getPointeeType();
581 isRValueRefArg = true;
583 if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
587 // A POD-struct is an aggregate class that [...] has no user-defined
588 // copy assignment operator [...].
589 // FIXME: This should be probably determined dynamically in terms of
590 // other more precise attributes to correctly model how it is specified
591 // in C++0x. Setting it here happens to do the right thing.
592 data().PlainOldData = false;
594 if (!isRValueRefArg) {
595 // This is a copy assignment operator.
597 // Suppress the implicit declaration of a copy constructor.
598 data().UserDeclaredCopyAssignment = true;
599 data().DeclaredCopyAssignment = true;
601 // C++0x [class.copy]p27:
602 // A copy/move assignment operator for class X is trivial if it is
603 // neither user-provided nor deleted [...]
604 // FIXME: C++0x: don't do this for "= default" copy operators.
605 data().HasTrivialCopyAssignment = false;
607 // This is a move assignment operator.
609 // C++0x [class.copy]p27:
610 // A copy/move assignment operator for class X is trivial if it is
611 // neither user-provided nor deleted [...]
612 // FIXME: C++0x: don't do this for "= default" copy operators.
613 data().HasTrivialMoveAssignment = false;
617 // Keep the list of conversion functions up-to-date.
618 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
619 // We don't record specializations.
620 if (Conversion->getPrimaryTemplate())
623 // FIXME: We intentionally don't use the decl's access here because it
624 // hasn't been set yet. That's really just a misdesign in Sema.
627 if (FunTmpl->getPreviousDeclaration())
628 data().Conversions.replace(FunTmpl->getPreviousDeclaration(),
631 data().Conversions.addDecl(FunTmpl);
633 if (Conversion->getPreviousDeclaration())
634 data().Conversions.replace(Conversion->getPreviousDeclaration(),
637 data().Conversions.addDecl(Conversion);
644 // Handle non-static data members.
645 if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
646 // C++ [dcl.init.aggr]p1:
647 // An aggregate is an array or a class (clause 9) with [...] no
648 // private or protected non-static data members (clause 11).
650 // A POD must be an aggregate.
651 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
652 data().Aggregate = false;
653 data().PlainOldData = false;
657 // A standard-layout class is a class that:
659 // -- has the same access control for all non-static data members,
660 switch (D->getAccess()) {
661 case AS_private: data().HasPrivateFields = true; break;
662 case AS_protected: data().HasProtectedFields = true; break;
663 case AS_public: data().HasPublicFields = true; break;
664 case AS_none: assert(0 && "Invalid access specifier");
666 if ((data().HasPrivateFields + data().HasProtectedFields +
667 data().HasPublicFields) > 1)
668 data().IsStandardLayout = false;
671 // A POD struct is a class that is both a trivial class and a
672 // standard-layout class, and has no non-static data members of type
673 // non-POD struct, non-POD union (or array of such types).
674 ASTContext &Context = getASTContext();
675 QualType T = Context.getBaseElementType(Field->getType());
677 data().PlainOldData = false;
678 if (T->isReferenceType()) {
679 data().HasTrivialConstructor = false;
682 // A standard-layout class is a class that:
683 // -- has no non-static data members of type [...] reference,
684 data().IsStandardLayout = false;
687 // Record if this field is the first non-literal field or base.
688 if (!hasNonLiteralTypeFieldsOrBases() && !T->isLiteralType())
689 data().HasNonLiteralTypeFieldsOrBases = true;
691 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
692 CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
693 if (FieldRec->getDefinition()) {
694 if (!FieldRec->hasTrivialConstructor())
695 data().HasTrivialConstructor = false;
697 // C++0x [class.copy]p13:
698 // A copy/move constructor for class X is trivial if [...]
700 // -- for each non-static data member of X that is of class type (or
701 // an array thereof), the constructor selected to copy/move that
702 // member is trivial;
703 // FIXME: C++0x: We don't correctly model 'selected' constructors.
704 if (!FieldRec->hasTrivialCopyConstructor())
705 data().HasTrivialCopyConstructor = false;
706 if (!FieldRec->hasTrivialMoveConstructor())
707 data().HasTrivialMoveConstructor = false;
709 // C++0x [class.copy]p27:
710 // A copy/move assignment operator for class X is trivial if [...]
712 // -- for each non-static data member of X that is of class type (or
713 // an array thereof), the assignment operator selected to
714 // copy/move that member is trivial;
715 // FIXME: C++0x: We don't correctly model 'selected' operators.
716 if (!FieldRec->hasTrivialCopyAssignment())
717 data().HasTrivialCopyAssignment = false;
718 if (!FieldRec->hasTrivialMoveAssignment())
719 data().HasTrivialMoveAssignment = false;
721 if (!FieldRec->hasTrivialDestructor())
722 data().HasTrivialDestructor = false;
725 // A standard-layout class is a class that:
726 // -- has no non-static data members of type non-standard-layout
727 // class (or array of such types) [...]
728 if (!FieldRec->isStandardLayout())
729 data().IsStandardLayout = false;
732 // A standard-layout class is a class that:
734 // -- has no base classes of the same type as the first non-static
736 // We don't want to expend bits in the state of the record decl
737 // tracking whether this is the first non-static data member so we
738 // cheat a bit and use some of the existing state: the empty bit.
739 // Virtual bases and virtual methods make a class non-empty, but they
740 // also make it non-standard-layout so we needn't check here.
741 // A non-empty base class may leave the class standard-layout, but not
742 // if we have arrived here, and have at least on non-static data
743 // member. If IsStandardLayout remains true, then the first non-static
744 // data member must come through here with Empty still true, and Empty
745 // will subsequently be set to false below.
746 if (data().IsStandardLayout && data().Empty) {
747 for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
750 if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
751 data().IsStandardLayout = false;
760 // A standard-layout class is a class that:
762 // -- either has no non-static data members in the most derived
763 // class and at most one base class with non-static data members,
764 // or has no base classes with non-static data members, and
765 // At this point we know that we have a non-static data member, so the last
767 if (!data().HasNoNonEmptyBases)
768 data().IsStandardLayout = false;
770 // If this is not a zero-length bit-field, then the class is not empty.
772 if (!Field->getBitWidth())
773 data().Empty = false;
774 else if (!Field->getBitWidth()->isTypeDependent() &&
775 !Field->getBitWidth()->isValueDependent()) {
777 if (Field->getBitWidth()->isIntegerConstantExpr(Bits, Context))
779 data().Empty = false;
784 // Handle using declarations of conversion functions.
785 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
786 if (Shadow->getDeclName().getNameKind()
787 == DeclarationName::CXXConversionFunctionName)
788 data().Conversions.addDecl(Shadow, Shadow->getAccess());
791 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
793 if (isa<UsingShadowDecl>(Conv))
794 Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
795 if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
796 T = ConvTemp->getTemplatedDecl()->getResultType();
798 T = cast<CXXConversionDecl>(Conv)->getConversionType();
799 return Context.getCanonicalType(T);
802 /// Collect the visible conversions of a base class.
804 /// \param Base a base class of the class we're considering
805 /// \param InVirtual whether this base class is a virtual base (or a base
806 /// of a virtual base)
807 /// \param Access the access along the inheritance path to this base
808 /// \param ParentHiddenTypes the conversions provided by the inheritors
810 /// \param Output the set to which to add conversions from non-virtual bases
811 /// \param VOutput the set to which to add conversions from virtual bases
812 /// \param HiddenVBaseCs the set of conversions which were hidden in a
813 /// virtual base along some inheritance path
814 static void CollectVisibleConversions(ASTContext &Context,
815 CXXRecordDecl *Record,
817 AccessSpecifier Access,
818 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
819 UnresolvedSetImpl &Output,
820 UnresolvedSetImpl &VOutput,
821 llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
822 // The set of types which have conversions in this class or its
823 // subclasses. As an optimization, we don't copy the derived set
824 // unless it might change.
825 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
826 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
828 // Collect the direct conversions and figure out which conversions
829 // will be hidden in the subclasses.
830 UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
832 HiddenTypesBuffer = ParentHiddenTypes;
833 HiddenTypes = &HiddenTypesBuffer;
835 for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
837 !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
839 // If this conversion is hidden and we're in a virtual base,
840 // remember that it's hidden along some inheritance path.
841 if (Hidden && InVirtual)
842 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
844 // If this conversion isn't hidden, add it to the appropriate output.
846 AccessSpecifier IAccess
847 = CXXRecordDecl::MergeAccess(Access, I.getAccess());
850 VOutput.addDecl(I.getDecl(), IAccess);
852 Output.addDecl(I.getDecl(), IAccess);
857 // Collect information recursively from any base classes.
858 for (CXXRecordDecl::base_class_iterator
859 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
860 const RecordType *RT = I->getType()->getAs<RecordType>();
863 AccessSpecifier BaseAccess
864 = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
865 bool BaseInVirtual = InVirtual || I->isVirtual();
867 CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
868 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
869 *HiddenTypes, Output, VOutput, HiddenVBaseCs);
873 /// Collect the visible conversions of a class.
875 /// This would be extremely straightforward if it weren't for virtual
876 /// bases. It might be worth special-casing that, really.
877 static void CollectVisibleConversions(ASTContext &Context,
878 CXXRecordDecl *Record,
879 UnresolvedSetImpl &Output) {
880 // The collection of all conversions in virtual bases that we've
881 // found. These will be added to the output as long as they don't
882 // appear in the hidden-conversions set.
883 UnresolvedSet<8> VBaseCs;
885 // The set of conversions in virtual bases that we've determined to
887 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
889 // The set of types hidden by classes derived from this one.
890 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
892 // Go ahead and collect the direct conversions and add them to the
894 UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
895 Output.append(Cs.begin(), Cs.end());
896 for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
897 HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
899 // Recursively collect conversions from base classes.
900 for (CXXRecordDecl::base_class_iterator
901 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
902 const RecordType *RT = I->getType()->getAs<RecordType>();
905 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
906 I->isVirtual(), I->getAccessSpecifier(),
907 HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
910 // Add any unhidden conversions provided by virtual bases.
911 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
913 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
914 Output.addDecl(I.getDecl(), I.getAccess());
918 /// getVisibleConversionFunctions - get all conversion functions visible
919 /// in current class; including conversion function templates.
920 const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
921 // If root class, all conversions are visible.
922 if (bases_begin() == bases_end())
923 return &data().Conversions;
924 // If visible conversion list is already evaluated, return it.
925 if (data().ComputedVisibleConversions)
926 return &data().VisibleConversions;
927 CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
928 data().ComputedVisibleConversions = true;
929 return &data().VisibleConversions;
932 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
933 // This operation is O(N) but extremely rare. Sema only uses it to
934 // remove UsingShadowDecls in a class that were followed by a direct
935 // declaration, e.g.:
937 // using B::operator int;
940 // This is uncommon by itself and even more uncommon in conjunction
941 // with sufficiently large numbers of directly-declared conversions
942 // that asymptotic behavior matters.
944 UnresolvedSetImpl &Convs = *getConversionFunctions();
945 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
946 if (Convs[I].getDecl() == ConvDecl) {
948 assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
949 && "conversion was found multiple times in unresolved set");
954 llvm_unreachable("conversion not found in set!");
957 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
958 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
959 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
964 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
965 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
969 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
970 TemplateSpecializationKind TSK) {
971 assert(TemplateOrInstantiation.isNull() &&
972 "Previous template or instantiation?");
973 assert(!isa<ClassTemplateSpecializationDecl>(this));
974 TemplateOrInstantiation
975 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
978 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
979 if (const ClassTemplateSpecializationDecl *Spec
980 = dyn_cast<ClassTemplateSpecializationDecl>(this))
981 return Spec->getSpecializationKind();
983 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
984 return MSInfo->getTemplateSpecializationKind();
986 return TSK_Undeclared;
990 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
991 if (ClassTemplateSpecializationDecl *Spec
992 = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
993 Spec->setSpecializationKind(TSK);
997 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
998 MSInfo->setTemplateSpecializationKind(TSK);
1002 assert(false && "Not a class template or member class specialization");
1005 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1006 ASTContext &Context = getASTContext();
1007 QualType ClassType = Context.getTypeDeclType(this);
1009 DeclarationName Name
1010 = Context.DeclarationNames.getCXXDestructorName(
1011 Context.getCanonicalType(ClassType));
1013 DeclContext::lookup_const_iterator I, E;
1014 llvm::tie(I, E) = lookup(Name);
1018 CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
1022 void CXXRecordDecl::completeDefinition() {
1023 completeDefinition(0);
1026 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1027 RecordDecl::completeDefinition();
1029 // If the class may be abstract (but hasn't been marked as such), check for
1030 // any pure final overriders.
1031 if (mayBeAbstract()) {
1032 CXXFinalOverriderMap MyFinalOverriders;
1033 if (!FinalOverriders) {
1034 getFinalOverriders(MyFinalOverriders);
1035 FinalOverriders = &MyFinalOverriders;
1039 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1040 MEnd = FinalOverriders->end();
1041 M != MEnd && !Done; ++M) {
1042 for (OverridingMethods::iterator SO = M->second.begin(),
1043 SOEnd = M->second.end();
1044 SO != SOEnd && !Done; ++SO) {
1045 assert(SO->second.size() > 0 &&
1046 "All virtual functions have overridding virtual functions");
1048 // C++ [class.abstract]p4:
1049 // A class is abstract if it contains or inherits at least one
1050 // pure virtual function for which the final overrider is pure
1052 if (SO->second.front().Method->isPure()) {
1053 data().Abstract = true;
1061 // Set access bits correctly on the directly-declared conversions.
1062 for (UnresolvedSetIterator I = data().Conversions.begin(),
1063 E = data().Conversions.end();
1065 data().Conversions.setAccess(I, (*I)->getAccess());
1068 bool CXXRecordDecl::mayBeAbstract() const {
1069 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1070 isDependentContext())
1073 for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1076 CXXRecordDecl *BaseDecl
1077 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1078 if (BaseDecl->isAbstract())
1086 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1087 SourceLocation StartLoc,
1088 const DeclarationNameInfo &NameInfo,
1089 QualType T, TypeSourceInfo *TInfo,
1090 bool isStatic, StorageClass SCAsWritten, bool isInline,
1091 SourceLocation EndLocation) {
1092 return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1093 isStatic, SCAsWritten, isInline, EndLocation);
1096 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1097 if (getOverloadedOperator() != OO_Delete &&
1098 getOverloadedOperator() != OO_Array_Delete)
1101 // C++ [basic.stc.dynamic.deallocation]p2:
1102 // A template instance is never a usual deallocation function,
1103 // regardless of its signature.
1104 if (getPrimaryTemplate())
1107 // C++ [basic.stc.dynamic.deallocation]p2:
1108 // If a class T has a member deallocation function named operator delete
1109 // with exactly one parameter, then that function is a usual (non-placement)
1110 // deallocation function. [...]
1111 if (getNumParams() == 1)
1114 // C++ [basic.stc.dynamic.deallocation]p2:
1115 // [...] If class T does not declare such an operator delete but does
1116 // declare a member deallocation function named operator delete with
1117 // exactly two parameters, the second of which has type std::size_t (18.1),
1118 // then this function is a usual deallocation function.
1119 ASTContext &Context = getASTContext();
1120 if (getNumParams() != 2 ||
1121 !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1122 Context.getSizeType()))
1125 // This function is a usual deallocation function if there are no
1126 // single-parameter deallocation functions of the same kind.
1127 for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1128 R.first != R.second; ++R.first) {
1129 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
1130 if (FD->getNumParams() == 1)
1137 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1138 // C++0x [class.copy]p19:
1139 // A user-declared copy assignment operator X::operator= is a non-static
1140 // non-template member function of class X with exactly one parameter of
1141 // type X, X&, const X&, volatile X& or const volatile X&.
1142 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1143 /*non-static*/ isStatic() ||
1144 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
1145 /*exactly one parameter*/getNumParams() != 1)
1148 QualType ParamType = getParamDecl(0)->getType();
1149 if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1150 ParamType = Ref->getPointeeType();
1152 ASTContext &Context = getASTContext();
1154 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1155 return Context.hasSameUnqualifiedType(ClassType, ParamType);
1158 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1159 assert(MD->isCanonicalDecl() && "Method is not canonical!");
1160 assert(!MD->getParent()->isDependentContext() &&
1161 "Can't add an overridden method to a class template!");
1163 getASTContext().addOverriddenMethod(this, MD);
1166 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1167 return getASTContext().overridden_methods_begin(this);
1170 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1171 return getASTContext().overridden_methods_end(this);
1174 unsigned CXXMethodDecl::size_overridden_methods() const {
1175 return getASTContext().overridden_methods_size(this);
1178 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1179 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1180 // If the member function is declared const, the type of this is const X*,
1181 // if the member function is declared volatile, the type of this is
1182 // volatile X*, and if the member function is declared const volatile,
1183 // the type of this is const volatile X*.
1185 assert(isInstance() && "No 'this' for static methods!");
1187 QualType ClassTy = C.getTypeDeclType(getParent());
1188 ClassTy = C.getQualifiedType(ClassTy,
1189 Qualifiers::fromCVRMask(getTypeQualifiers()));
1190 return C.getPointerType(ClassTy);
1193 bool CXXMethodDecl::hasInlineBody() const {
1194 // If this function is a template instantiation, look at the template from
1195 // which it was instantiated.
1196 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1200 const FunctionDecl *fn;
1201 return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1204 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1205 TypeSourceInfo *TInfo, bool IsVirtual,
1206 SourceLocation L, Expr *Init,
1208 SourceLocation EllipsisLoc)
1209 : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1210 LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
1211 SourceOrderOrNumArrayIndices(0)
1215 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1217 SourceLocation MemberLoc,
1218 SourceLocation L, Expr *Init,
1220 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1221 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1222 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1226 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1227 IndirectFieldDecl *Member,
1228 SourceLocation MemberLoc,
1229 SourceLocation L, Expr *Init,
1231 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1232 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1233 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1237 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1238 SourceLocation D, SourceLocation L,
1239 CXXConstructorDecl *Target, Expr *Init,
1241 : Initializee(Target), MemberOrEllipsisLocation(D), Init(Init),
1242 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1243 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1247 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1249 SourceLocation MemberLoc,
1250 SourceLocation L, Expr *Init,
1253 unsigned NumIndices)
1254 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1255 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1256 IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1258 VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1259 memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1262 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1264 SourceLocation MemberLoc,
1265 SourceLocation L, Expr *Init,
1268 unsigned NumIndices) {
1269 void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1270 sizeof(VarDecl *) * NumIndices,
1271 llvm::alignOf<CXXCtorInitializer>());
1272 return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1273 Indices, NumIndices);
1276 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1277 if (isBaseInitializer())
1278 return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1283 const Type *CXXCtorInitializer::getBaseClass() const {
1284 if (isBaseInitializer())
1285 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1290 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1291 if (isAnyMemberInitializer() || isDelegatingInitializer())
1292 return getMemberLocation();
1294 return getBaseClassLoc().getLocalSourceRange().getBegin();
1297 SourceRange CXXCtorInitializer::getSourceRange() const {
1298 return SourceRange(getSourceLocation(), getRParenLoc());
1301 CXXConstructorDecl *
1302 CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1303 return new (C) CXXConstructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1304 QualType(), 0, false, false, false);
1307 CXXConstructorDecl *
1308 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1309 SourceLocation StartLoc,
1310 const DeclarationNameInfo &NameInfo,
1311 QualType T, TypeSourceInfo *TInfo,
1314 bool isImplicitlyDeclared) {
1315 assert(NameInfo.getName().getNameKind()
1316 == DeclarationName::CXXConstructorName &&
1317 "Name must refer to a constructor");
1318 return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1319 isExplicit, isInline, isImplicitlyDeclared);
1322 bool CXXConstructorDecl::isDefaultConstructor() const {
1323 // C++ [class.ctor]p5:
1324 // A default constructor for a class X is a constructor of class
1325 // X that can be called without an argument.
1326 return (getNumParams() == 0) ||
1327 (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1331 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1332 return isCopyOrMoveConstructor(TypeQuals) &&
1333 getParamDecl(0)->getType()->isLValueReferenceType();
1336 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1337 return isCopyOrMoveConstructor(TypeQuals) &&
1338 getParamDecl(0)->getType()->isRValueReferenceType();
1341 /// \brief Determine whether this is a copy or move constructor.
1342 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1343 // C++ [class.copy]p2:
1344 // A non-template constructor for class X is a copy constructor
1345 // if its first parameter is of type X&, const X&, volatile X& or
1346 // const volatile X&, and either there are no other parameters
1347 // or else all other parameters have default arguments (8.3.6).
1348 // C++0x [class.copy]p3:
1349 // A non-template constructor for class X is a move constructor if its
1350 // first parameter is of type X&&, const X&&, volatile X&&, or
1351 // const volatile X&&, and either there are no other parameters or else
1352 // all other parameters have default arguments.
1353 if ((getNumParams() < 1) ||
1354 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1355 (getPrimaryTemplate() != 0) ||
1356 (getDescribedFunctionTemplate() != 0))
1359 const ParmVarDecl *Param = getParamDecl(0);
1361 // Do we have a reference type?
1362 const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1366 // Is it a reference to our class type?
1367 ASTContext &Context = getASTContext();
1369 CanQualType PointeeType
1370 = Context.getCanonicalType(ParamRefType->getPointeeType());
1372 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1373 if (PointeeType.getUnqualifiedType() != ClassTy)
1376 // FIXME: other qualifiers?
1378 // We have a copy or move constructor.
1379 TypeQuals = PointeeType.getCVRQualifiers();
1383 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1384 // C++ [class.conv.ctor]p1:
1385 // A constructor declared without the function-specifier explicit
1386 // that can be called with a single parameter specifies a
1387 // conversion from the type of its first parameter to the type of
1388 // its class. Such a constructor is called a converting
1390 if (isExplicit() && !AllowExplicit)
1393 return (getNumParams() == 0 &&
1394 getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1395 (getNumParams() == 1) ||
1396 (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
1399 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1400 if ((getNumParams() < 1) ||
1401 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1402 (getPrimaryTemplate() == 0) ||
1403 (getDescribedFunctionTemplate() != 0))
1406 const ParmVarDecl *Param = getParamDecl(0);
1408 ASTContext &Context = getASTContext();
1409 CanQualType ParamType = Context.getCanonicalType(Param->getType());
1411 // Is it the same as our our class type?
1413 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1414 if (ParamType.getUnqualifiedType() != ClassTy)
1420 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1421 // Hack: we store the inherited constructor in the overridden method table
1422 method_iterator It = begin_overridden_methods();
1423 if (It == end_overridden_methods())
1426 return cast<CXXConstructorDecl>(*It);
1430 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1431 // Hack: we store the inherited constructor in the overridden method table
1432 assert(size_overridden_methods() == 0 && "Base ctor already set.");
1433 addOverriddenMethod(BaseCtor);
1437 CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1438 return new (C) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1439 QualType(), 0, false, false);
1443 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1444 SourceLocation StartLoc,
1445 const DeclarationNameInfo &NameInfo,
1446 QualType T, TypeSourceInfo *TInfo,
1448 bool isImplicitlyDeclared) {
1449 assert(NameInfo.getName().getNameKind()
1450 == DeclarationName::CXXDestructorName &&
1451 "Name must refer to a destructor");
1452 return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1453 isImplicitlyDeclared);
1457 CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
1458 return new (C) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1459 QualType(), 0, false, false,
1464 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1465 SourceLocation StartLoc,
1466 const DeclarationNameInfo &NameInfo,
1467 QualType T, TypeSourceInfo *TInfo,
1468 bool isInline, bool isExplicit,
1469 SourceLocation EndLocation) {
1470 assert(NameInfo.getName().getNameKind()
1471 == DeclarationName::CXXConversionFunctionName &&
1472 "Name must refer to a conversion function");
1473 return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1474 isInline, isExplicit, EndLocation);
1477 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1479 SourceLocation ExternLoc,
1480 SourceLocation LangLoc,
1482 SourceLocation RBraceLoc) {
1483 return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
1486 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1488 SourceLocation NamespaceLoc,
1489 NestedNameSpecifierLoc QualifierLoc,
1490 SourceLocation IdentLoc,
1492 DeclContext *CommonAncestor) {
1493 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1494 Used = NS->getOriginalNamespace();
1495 return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1496 IdentLoc, Used, CommonAncestor);
1499 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1500 if (NamespaceAliasDecl *NA =
1501 dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1502 return NA->getNamespace();
1503 return cast_or_null<NamespaceDecl>(NominatedNamespace);
1506 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1507 SourceLocation UsingLoc,
1508 SourceLocation AliasLoc,
1509 IdentifierInfo *Alias,
1510 NestedNameSpecifierLoc QualifierLoc,
1511 SourceLocation IdentLoc,
1512 NamedDecl *Namespace) {
1513 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1514 Namespace = NS->getOriginalNamespace();
1515 return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias,
1516 QualifierLoc, IdentLoc, Namespace);
1519 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1520 const UsingShadowDecl *Shadow = this;
1521 while (const UsingShadowDecl *NextShadow =
1522 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1523 Shadow = NextShadow;
1524 return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1527 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1528 assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1529 "declaration already in set");
1530 assert(S->getUsingDecl() == this);
1532 if (FirstUsingShadow)
1533 S->UsingOrNextShadow = FirstUsingShadow;
1534 FirstUsingShadow = S;
1537 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1538 assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1539 "declaration not in set");
1540 assert(S->getUsingDecl() == this);
1542 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1544 if (FirstUsingShadow == S) {
1545 FirstUsingShadow = dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow);
1546 S->UsingOrNextShadow = this;
1550 UsingShadowDecl *Prev = FirstUsingShadow;
1551 while (Prev->UsingOrNextShadow != S)
1552 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1553 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1554 S->UsingOrNextShadow = this;
1557 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1558 NestedNameSpecifierLoc QualifierLoc,
1559 const DeclarationNameInfo &NameInfo,
1560 bool IsTypeNameArg) {
1561 return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1564 UnresolvedUsingValueDecl *
1565 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1566 SourceLocation UsingLoc,
1567 NestedNameSpecifierLoc QualifierLoc,
1568 const DeclarationNameInfo &NameInfo) {
1569 return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1570 QualifierLoc, NameInfo);
1573 UnresolvedUsingTypenameDecl *
1574 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1575 SourceLocation UsingLoc,
1576 SourceLocation TypenameLoc,
1577 NestedNameSpecifierLoc QualifierLoc,
1578 SourceLocation TargetNameLoc,
1579 DeclarationName TargetName) {
1580 return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1581 QualifierLoc, TargetNameLoc,
1582 TargetName.getAsIdentifierInfo());
1585 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1586 SourceLocation StaticAssertLoc,
1588 StringLiteral *Message,
1589 SourceLocation RParenLoc) {
1590 return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
1594 static const char *getAccessName(AccessSpecifier AS) {
1598 assert("Invalid access specifier!");
1609 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1610 AccessSpecifier AS) {
1611 return DB << getAccessName(AS);