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 UserDeclaredMoveConstructor(false), UserDeclaredCopyAssignment(false),
33 UserDeclaredMoveAssignment(false), UserDeclaredDestructor(false),
34 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
35 Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
36 HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
37 HasMutableFields(false), HasTrivialDefaultConstructor(true),
38 HasConstExprNonCopyMoveConstructor(false), HasTrivialCopyConstructor(true),
39 HasTrivialMoveConstructor(true), HasTrivialCopyAssignment(true),
40 HasTrivialMoveAssignment(true), HasTrivialDestructor(true),
41 HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
42 UserProvidedDefaultConstructor(false), DeclaredDefaultConstructor(false),
43 DeclaredCopyConstructor(false), DeclaredMoveConstructor(false),
44 DeclaredCopyAssignment(false), DeclaredMoveAssignment(false),
45 DeclaredDestructor(false), NumBases(0), NumVBases(0), Bases(), VBases(),
46 Definition(D), FirstFriend(0) {
49 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
50 SourceLocation StartLoc, SourceLocation IdLoc,
51 IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
52 : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
53 DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
54 TemplateOrInstantiation() { }
56 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
57 DeclContext *DC, SourceLocation StartLoc,
58 SourceLocation IdLoc, IdentifierInfo *Id,
59 CXXRecordDecl* PrevDecl,
60 bool DelayTypeCreation) {
61 CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
64 // FIXME: DelayTypeCreation seems like such a hack
65 if (!DelayTypeCreation)
66 C.getTypeDeclType(R, PrevDecl);
70 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
71 return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(),
72 SourceLocation(), 0, 0);
76 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
78 ASTContext &C = getASTContext();
80 // C++ [dcl.init.aggr]p1:
81 // An aggregate is an array or a class (clause 9) with [...]
82 // no base classes [...].
83 data().Aggregate = false;
85 if (!data().Bases.isOffset() && data().NumBases > 0)
86 C.Deallocate(data().getBases());
88 // The set of seen virtual base types.
89 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
91 // The virtual bases of this class.
92 llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
94 data().Bases = new(C) CXXBaseSpecifier [NumBases];
95 data().NumBases = NumBases;
96 for (unsigned i = 0; i < NumBases; ++i) {
97 data().getBases()[i] = *Bases[i];
98 // Keep track of inherited vbases for this base class.
99 const CXXBaseSpecifier *Base = Bases[i];
100 QualType BaseType = Base->getType();
101 // Skip dependent types; we can't do any checking on them now.
102 if (BaseType->isDependentType())
104 CXXRecordDecl *BaseClassDecl
105 = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
107 // C++ [dcl.init.aggr]p1:
108 // An aggregate is [...] a class with [...] no base classes [...].
109 data().Aggregate = false;
112 // A POD-struct is an aggregate class...
113 data().PlainOldData = false;
115 // A class with a non-empty base class is not empty.
116 // FIXME: Standard ref?
117 if (!BaseClassDecl->isEmpty()) {
120 // A standard-layout class is a class that:
122 // -- either has no non-static data members in the most derived
123 // class and at most one base class with non-static data members,
124 // or has no base classes with non-static data members, and
125 // If this is the second non-empty base, then neither of these two
126 // clauses can be true.
127 data().IsStandardLayout = false;
130 data().Empty = false;
131 data().HasNoNonEmptyBases = false;
134 // C++ [class.virtual]p1:
135 // A class that declares or inherits a virtual function is called a
136 // polymorphic class.
137 if (BaseClassDecl->isPolymorphic())
138 data().Polymorphic = true;
141 // A standard-layout class is a class that: [...]
142 // -- has no non-standard-layout base classes
143 if (!BaseClassDecl->isStandardLayout())
144 data().IsStandardLayout = false;
146 // Record if this base is the first non-literal field or base.
147 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
148 data().HasNonLiteralTypeFieldsOrBases = true;
150 // Now go through all virtual bases of this base and add them.
151 for (CXXRecordDecl::base_class_iterator VBase =
152 BaseClassDecl->vbases_begin(),
153 E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
154 // Add this base if it's not already in the list.
155 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
156 VBases.push_back(VBase);
159 if (Base->isVirtual()) {
160 // Add this base if it's not already in the list.
161 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
162 VBases.push_back(Base);
164 // C++0x [meta.unary.prop] is_empty:
165 // T is a class type, but not a union type, with ... no virtual base
167 data().Empty = false;
169 // C++ [class.ctor]p5:
170 // A default constructor is trivial [...] if:
171 // -- its class has [...] no virtual bases
172 data().HasTrivialDefaultConstructor = false;
174 // C++0x [class.copy]p13:
175 // A copy/move constructor for class X is trivial if it is neither
176 // user-provided nor deleted and if
177 // -- class X has no virtual functions and no virtual base classes, and
178 data().HasTrivialCopyConstructor = false;
179 data().HasTrivialMoveConstructor = false;
181 // C++0x [class.copy]p27:
182 // A copy/move assignment operator for class X is trivial if it is
183 // neither user-provided nor deleted and if
184 // -- class X has no virtual functions and no virtual base classes, and
185 data().HasTrivialCopyAssignment = false;
186 data().HasTrivialMoveAssignment = false;
189 // A standard-layout class is a class that: [...]
190 // -- has [...] no virtual base classes
191 data().IsStandardLayout = false;
193 // C++ [class.ctor]p5:
194 // A default constructor is trivial [...] if:
195 // -- all the direct base classes of its class have trivial default
197 if (!BaseClassDecl->hasTrivialDefaultConstructor())
198 data().HasTrivialDefaultConstructor = false;
200 // C++0x [class.copy]p13:
201 // A copy/move constructor for class X is trivial if [...]
203 // -- the constructor selected to copy/move each direct base class
204 // subobject is trivial, and
205 // FIXME: C++0x: We need to only consider the selected constructor
206 // instead of all of them.
207 if (!BaseClassDecl->hasTrivialCopyConstructor())
208 data().HasTrivialCopyConstructor = false;
209 if (!BaseClassDecl->hasTrivialMoveConstructor())
210 data().HasTrivialMoveConstructor = false;
212 // C++0x [class.copy]p27:
213 // A copy/move assignment operator for class X is trivial if [...]
215 // -- the assignment operator selected to copy/move each direct base
216 // class subobject is trivial, and
217 // FIXME: C++0x: We need to only consider the selected operator instead
219 if (!BaseClassDecl->hasTrivialCopyAssignment())
220 data().HasTrivialCopyAssignment = false;
221 if (!BaseClassDecl->hasTrivialMoveAssignment())
222 data().HasTrivialMoveAssignment = false;
225 // C++ [class.ctor]p3:
226 // A destructor is trivial if all the direct base classes of its class
227 // have trivial destructors.
228 if (!BaseClassDecl->hasTrivialDestructor())
229 data().HasTrivialDestructor = false;
231 // A class has an Objective-C object member if... or any of its bases
232 // has an Objective-C object member.
233 if (BaseClassDecl->hasObjectMember())
234 setHasObjectMember(true);
236 // Keep track of the presence of mutable fields.
237 if (BaseClassDecl->hasMutableFields())
238 data().HasMutableFields = true;
244 // Create base specifier for any direct or indirect virtual bases.
245 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
246 data().NumVBases = VBases.size();
247 for (int I = 0, E = VBases.size(); I != E; ++I)
248 data().getVBases()[I] = *VBases[I];
251 /// Callback function for CXXRecordDecl::forallBases that acknowledges
252 /// that it saw a base class.
253 static bool SawBase(const CXXRecordDecl *, void *) {
257 bool CXXRecordDecl::hasAnyDependentBases() const {
258 if (!isDependentContext())
261 return !forallBases(SawBase, 0);
264 bool CXXRecordDecl::hasConstCopyConstructor() const {
265 return getCopyConstructor(Qualifiers::Const) != 0;
268 bool CXXRecordDecl::isTriviallyCopyable() const {
270 // A trivially copyable class is a class that:
271 // -- has no non-trivial copy constructors,
272 if (!hasTrivialCopyConstructor()) return false;
273 // -- has no non-trivial move constructors,
274 if (!hasTrivialMoveConstructor()) return false;
275 // -- has no non-trivial copy assignment operators,
276 if (!hasTrivialCopyAssignment()) return false;
277 // -- has no non-trivial move assignment operators, and
278 if (!hasTrivialMoveAssignment()) return false;
279 // -- has a trivial destructor.
280 if (!hasTrivialDestructor()) return false;
285 /// \brief Perform a simplistic form of overload resolution that only considers
286 /// cv-qualifiers on a single parameter, and return the best overload candidate
287 /// (if there is one).
288 static CXXMethodDecl *
289 GetBestOverloadCandidateSimple(
290 const llvm::SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
293 if (Cands.size() == 1)
294 return Cands[0].first;
296 unsigned Best = 0, N = Cands.size();
297 for (unsigned I = 1; I != N; ++I)
298 if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
301 for (unsigned I = 1; I != N; ++I)
302 if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
305 return Cands[Best].first;
308 CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(unsigned TypeQuals) const{
309 ASTContext &Context = getASTContext();
311 = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
312 DeclarationName ConstructorName
313 = Context.DeclarationNames.getCXXConstructorName(
314 Context.getCanonicalType(ClassType));
316 llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
317 DeclContext::lookup_const_iterator Con, ConEnd;
318 for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
319 Con != ConEnd; ++Con) {
320 // C++ [class.copy]p2:
321 // A non-template constructor for class X is a copy constructor if [...]
322 if (isa<FunctionTemplateDecl>(*Con))
325 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
326 if (Constructor->isCopyConstructor(FoundTQs)) {
327 if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
328 (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
329 Found.push_back(std::make_pair(
330 const_cast<CXXConstructorDecl *>(Constructor),
331 Qualifiers::fromCVRMask(FoundTQs)));
335 return cast_or_null<CXXConstructorDecl>(
336 GetBestOverloadCandidateSimple(Found));
339 CXXConstructorDecl *CXXRecordDecl::getMoveConstructor() const {
340 for (ctor_iterator I = ctor_begin(), E = ctor_end(); I != E; ++I)
341 if (I->isMoveConstructor())
347 CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
348 ASTContext &Context = getASTContext();
349 QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
350 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
352 llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
353 DeclContext::lookup_const_iterator Op, OpEnd;
354 for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
355 // C++ [class.copy]p9:
356 // A user-declared copy assignment operator is a non-static non-template
357 // member function of class X with exactly one parameter of type X, X&,
358 // const X&, volatile X& or const volatile X&.
359 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
360 if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
363 const FunctionProtoType *FnType
364 = Method->getType()->getAs<FunctionProtoType>();
365 assert(FnType && "Overloaded operator has no prototype.");
366 // Don't assert on this; an invalid decl might have been left in the AST.
367 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
370 QualType ArgType = FnType->getArgType(0);
372 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
373 ArgType = Ref->getPointeeType();
374 // If we have a const argument and we have a reference to a non-const,
375 // this function does not match.
376 if (ArgIsConst && !ArgType.isConstQualified())
379 Quals = ArgType.getQualifiers();
381 // By-value copy-assignment operators are treated like const X&
382 // copy-assignment operators.
383 Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
386 if (!Context.hasSameUnqualifiedType(ArgType, Class))
389 // Save this copy-assignment operator. It might be "the one".
390 Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
393 // Use a simplistic form of overload resolution to find the candidate.
394 return GetBestOverloadCandidateSimple(Found);
397 CXXMethodDecl *CXXRecordDecl::getMoveAssignmentOperator() const {
398 for (method_iterator I = method_begin(), E = method_end(); I != E; ++I)
399 if (I->isMoveAssignmentOperator())
405 void CXXRecordDecl::markedVirtualFunctionPure() {
406 // C++ [class.abstract]p2:
407 // A class is abstract if it has at least one pure virtual function.
408 data().Abstract = true;
411 void CXXRecordDecl::addedMember(Decl *D) {
412 // Ignore friends and invalid declarations.
413 if (D->getFriendObjectKind() || D->isInvalidDecl())
416 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
418 D = FunTmpl->getTemplatedDecl();
420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
421 if (Method->isVirtual()) {
422 // C++ [dcl.init.aggr]p1:
423 // An aggregate is an array or a class with [...] no virtual functions.
424 data().Aggregate = false;
427 // A POD-struct is an aggregate class...
428 data().PlainOldData = false;
430 // Virtual functions make the class non-empty.
431 // FIXME: Standard ref?
432 data().Empty = false;
434 // C++ [class.virtual]p1:
435 // A class that declares or inherits a virtual function is called a
436 // polymorphic class.
437 data().Polymorphic = true;
439 // C++0x [class.ctor]p5
440 // A default constructor is trivial [...] if:
441 // -- its class has no virtual functions [...]
442 data().HasTrivialDefaultConstructor = false;
444 // C++0x [class.copy]p13:
445 // A copy/move constructor for class X is trivial if [...]
446 // -- class X has no virtual functions [...]
447 data().HasTrivialCopyConstructor = false;
448 data().HasTrivialMoveConstructor = false;
450 // C++0x [class.copy]p27:
451 // A copy/move assignment operator for class X is trivial if [...]
452 // -- class X has no virtual functions [...]
453 data().HasTrivialCopyAssignment = false;
454 data().HasTrivialMoveAssignment = false;
455 // FIXME: Destructor?
458 // A standard-layout class is a class that: [...]
459 // -- has no virtual functions
460 data().IsStandardLayout = false;
464 if (D->isImplicit()) {
465 // Notify that an implicit member was added after the definition
467 if (!isBeingDefined())
468 if (ASTMutationListener *L = getASTMutationListener())
469 L->AddedCXXImplicitMember(data().Definition, D);
471 // If this is a special member function, note that it was added and then
473 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
474 if (Constructor->isDefaultConstructor())
475 data().DeclaredDefaultConstructor = true;
476 else if (Constructor->isCopyConstructor())
477 data().DeclaredCopyConstructor = true;
478 else if (Constructor->isMoveConstructor())
479 data().DeclaredMoveConstructor = true;
481 goto NotASpecialMember;
483 } else if (isa<CXXDestructorDecl>(D)) {
484 data().DeclaredDestructor = true;
486 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
487 if (Method->isCopyAssignmentOperator())
488 data().DeclaredCopyAssignment = true;
489 else if (Method->isMoveAssignmentOperator())
490 data().DeclaredMoveAssignment = true;
492 goto NotASpecialMember;
497 // Any other implicit declarations are handled like normal declarations.
500 // Handle (user-declared) constructors.
501 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
502 // Note that we have a user-declared constructor.
503 data().UserDeclaredConstructor = true;
505 // FIXME: Under C++0x, /only/ special member functions may be user-provided.
506 // This is probably a defect.
507 bool UserProvided = false;
509 // C++0x [class.ctor]p5:
510 // A default constructor is trivial if it is not user-provided [...]
511 if (Constructor->isDefaultConstructor()) {
512 data().DeclaredDefaultConstructor = true;
513 if (Constructor->isUserProvided()) {
514 data().HasTrivialDefaultConstructor = false;
515 data().UserProvidedDefaultConstructor = true;
520 // Note when we have a user-declared copy or move constructor, which will
521 // suppress the implicit declaration of those constructors.
523 if (Constructor->isCopyConstructor()) {
524 data().UserDeclaredCopyConstructor = true;
525 data().DeclaredCopyConstructor = true;
527 // C++0x [class.copy]p13:
528 // A copy/move constructor for class X is trivial if it is not
529 // user-provided [...]
530 if (Constructor->isUserProvided()) {
531 data().HasTrivialCopyConstructor = false;
534 } else if (Constructor->isMoveConstructor()) {
535 data().UserDeclaredMoveConstructor = true;
536 data().DeclaredMoveConstructor = true;
538 // C++0x [class.copy]p13:
539 // A copy/move constructor for class X is trivial if it is not
540 // user-provided [...]
541 if (Constructor->isUserProvided()) {
542 data().HasTrivialMoveConstructor = false;
547 if (Constructor->isConstExpr() &&
548 !Constructor->isCopyOrMoveConstructor()) {
549 // Record if we see any constexpr constructors which are niether copy
550 // nor move constructors.
551 data().HasConstExprNonCopyMoveConstructor = true;
554 // C++ [dcl.init.aggr]p1:
555 // An aggregate is an array or a class with no user-declared
556 // constructors [...].
557 // C++0x [dcl.init.aggr]p1:
558 // An aggregate is an array or a class with no user-provided
559 // constructors [...].
560 if (!getASTContext().getLangOptions().CPlusPlus0x || UserProvided)
561 data().Aggregate = false;
564 // A POD-struct is an aggregate class [...]
565 // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
566 // type is technically an aggregate in C++0x since it wouldn't be in 03.
567 data().PlainOldData = false;
572 // Handle (user-declared) destructors.
573 if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
574 data().DeclaredDestructor = true;
575 data().UserDeclaredDestructor = true;
578 // A POD-struct is an aggregate class that has [...] no user-defined
580 // This bit is the C++03 POD bit, not the 0x one.
581 data().PlainOldData = false;
583 // C++0x [class.dtor]p5:
584 // A destructor is trivial if it is not user-provided and [...]
585 if (DD->isUserProvided())
586 data().HasTrivialDestructor = false;
591 // Handle (user-declared) member functions.
592 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
593 if (Method->isCopyAssignmentOperator()) {
595 // A POD-struct is an aggregate class that [...] has no user-defined
596 // copy assignment operator [...].
597 // This is the C++03 bit only.
598 data().PlainOldData = false;
600 // This is a copy assignment operator.
602 // Suppress the implicit declaration of a copy constructor.
603 data().UserDeclaredCopyAssignment = true;
604 data().DeclaredCopyAssignment = true;
606 // C++0x [class.copy]p27:
607 // A copy/move assignment operator for class X is trivial if it is
608 // neither user-provided nor deleted [...]
609 if (Method->isUserProvided())
610 data().HasTrivialCopyAssignment = false;
615 if (Method->isMoveAssignmentOperator()) {
616 // This is an extension in C++03 mode, but we'll keep consistency by
617 // taking a move assignment operator to induce non-POD-ness
618 data().PlainOldData = false;
620 // This is a move assignment operator.
621 data().UserDeclaredMoveAssignment = true;
622 data().DeclaredMoveAssignment = true;
624 // C++0x [class.copy]p27:
625 // A copy/move assignment operator for class X is trivial if it is
626 // neither user-provided nor deleted [...]
627 if (Method->isUserProvided())
628 data().HasTrivialMoveAssignment = false;
631 // Keep the list of conversion functions up-to-date.
632 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
633 // We don't record specializations.
634 if (Conversion->getPrimaryTemplate())
637 // FIXME: We intentionally don't use the decl's access here because it
638 // hasn't been set yet. That's really just a misdesign in Sema.
641 if (FunTmpl->getPreviousDeclaration())
642 data().Conversions.replace(FunTmpl->getPreviousDeclaration(),
645 data().Conversions.addDecl(FunTmpl);
647 if (Conversion->getPreviousDeclaration())
648 data().Conversions.replace(Conversion->getPreviousDeclaration(),
651 data().Conversions.addDecl(Conversion);
658 // Handle non-static data members.
659 if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
660 // C++ [dcl.init.aggr]p1:
661 // An aggregate is an array or a class (clause 9) with [...] no
662 // private or protected non-static data members (clause 11).
664 // A POD must be an aggregate.
665 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
666 data().Aggregate = false;
667 data().PlainOldData = false;
671 // A standard-layout class is a class that:
673 // -- has the same access control for all non-static data members,
674 switch (D->getAccess()) {
675 case AS_private: data().HasPrivateFields = true; break;
676 case AS_protected: data().HasProtectedFields = true; break;
677 case AS_public: data().HasPublicFields = true; break;
678 case AS_none: assert(0 && "Invalid access specifier");
680 if ((data().HasPrivateFields + data().HasProtectedFields +
681 data().HasPublicFields) > 1)
682 data().IsStandardLayout = false;
684 // Keep track of the presence of mutable fields.
685 if (Field->isMutable())
686 data().HasMutableFields = true;
689 // A POD struct is a class that is both a trivial class and a
690 // standard-layout class, and has no non-static data members of type
691 // non-POD struct, non-POD union (or array of such types).
693 // Automatic Reference Counting: the presence of a member of Objective-C pointer type
694 // that does not explicitly have no lifetime makes the class a non-POD.
695 // However, we delay setting PlainOldData to false in this case so that
696 // Sema has a chance to diagnostic causes where the same class will be
697 // non-POD with Automatic Reference Counting but a POD without Instant Objects.
698 // In this case, the class will become a non-POD class when we complete
700 ASTContext &Context = getASTContext();
701 QualType T = Context.getBaseElementType(Field->getType());
702 if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
703 if (!Context.getLangOptions().ObjCAutoRefCount ||
704 T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
705 setHasObjectMember(true);
706 } else if (!T.isPODType(Context))
707 data().PlainOldData = false;
709 if (T->isReferenceType()) {
710 data().HasTrivialDefaultConstructor = false;
713 // A standard-layout class is a class that:
714 // -- has no non-static data members of type [...] reference,
715 data().IsStandardLayout = false;
718 // Record if this field is the first non-literal field or base.
719 if (!hasNonLiteralTypeFieldsOrBases() && !T->isLiteralType())
720 data().HasNonLiteralTypeFieldsOrBases = true;
722 if (Field->hasInClassInitializer()) {
724 // A default constructor is trivial if [...] no non-static data member
725 // of its class has a brace-or-equal-initializer.
726 data().HasTrivialDefaultConstructor = false;
728 // C++0x [dcl.init.aggr]p1:
729 // An aggregate is a [...] class with [...] no
730 // brace-or-equal-initializers for non-static data members.
731 data().Aggregate = false;
734 // A POD struct is [...] a trivial class.
735 data().PlainOldData = false;
738 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
739 CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
740 if (FieldRec->getDefinition()) {
741 // C++0x [class.ctor]p5:
742 // A defulat constructor is trivial [...] if:
743 // -- for all the non-static data members of its class that are of
744 // class type (or array thereof), each such class has a trivial
745 // default constructor.
746 if (!FieldRec->hasTrivialDefaultConstructor())
747 data().HasTrivialDefaultConstructor = false;
749 // C++0x [class.copy]p13:
750 // A copy/move constructor for class X is trivial if [...]
752 // -- for each non-static data member of X that is of class type (or
753 // an array thereof), the constructor selected to copy/move that
754 // member is trivial;
755 // FIXME: C++0x: We don't correctly model 'selected' constructors.
756 if (!FieldRec->hasTrivialCopyConstructor())
757 data().HasTrivialCopyConstructor = false;
758 if (!FieldRec->hasTrivialMoveConstructor())
759 data().HasTrivialMoveConstructor = false;
761 // C++0x [class.copy]p27:
762 // A copy/move assignment operator for class X is trivial if [...]
764 // -- for each non-static data member of X that is of class type (or
765 // an array thereof), the assignment operator selected to
766 // copy/move that member is trivial;
767 // FIXME: C++0x: We don't correctly model 'selected' operators.
768 if (!FieldRec->hasTrivialCopyAssignment())
769 data().HasTrivialCopyAssignment = false;
770 if (!FieldRec->hasTrivialMoveAssignment())
771 data().HasTrivialMoveAssignment = false;
773 if (!FieldRec->hasTrivialDestructor())
774 data().HasTrivialDestructor = false;
775 if (FieldRec->hasObjectMember())
776 setHasObjectMember(true);
779 // A standard-layout class is a class that:
780 // -- has no non-static data members of type non-standard-layout
781 // class (or array of such types) [...]
782 if (!FieldRec->isStandardLayout())
783 data().IsStandardLayout = false;
786 // A standard-layout class is a class that:
788 // -- has no base classes of the same type as the first non-static
790 // We don't want to expend bits in the state of the record decl
791 // tracking whether this is the first non-static data member so we
792 // cheat a bit and use some of the existing state: the empty bit.
793 // Virtual bases and virtual methods make a class non-empty, but they
794 // also make it non-standard-layout so we needn't check here.
795 // A non-empty base class may leave the class standard-layout, but not
796 // if we have arrived here, and have at least on non-static data
797 // member. If IsStandardLayout remains true, then the first non-static
798 // data member must come through here with Empty still true, and Empty
799 // will subsequently be set to false below.
800 if (data().IsStandardLayout && data().Empty) {
801 for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
804 if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
805 data().IsStandardLayout = false;
811 // Keep track of the presence of mutable fields.
812 if (FieldRec->hasMutableFields())
813 data().HasMutableFields = true;
818 // A standard-layout class is a class that:
820 // -- either has no non-static data members in the most derived
821 // class and at most one base class with non-static data members,
822 // or has no base classes with non-static data members, and
823 // At this point we know that we have a non-static data member, so the last
825 if (!data().HasNoNonEmptyBases)
826 data().IsStandardLayout = false;
828 // If this is not a zero-length bit-field, then the class is not empty.
830 if (!Field->getBitWidth())
831 data().Empty = false;
832 else if (!Field->getBitWidth()->isTypeDependent() &&
833 !Field->getBitWidth()->isValueDependent()) {
835 if (Field->getBitWidth()->isIntegerConstantExpr(Bits, Context))
837 data().Empty = false;
842 // Handle using declarations of conversion functions.
843 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
844 if (Shadow->getDeclName().getNameKind()
845 == DeclarationName::CXXConversionFunctionName)
846 data().Conversions.addDecl(Shadow, Shadow->getAccess());
849 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
851 if (isa<UsingShadowDecl>(Conv))
852 Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
853 if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
854 T = ConvTemp->getTemplatedDecl()->getResultType();
856 T = cast<CXXConversionDecl>(Conv)->getConversionType();
857 return Context.getCanonicalType(T);
860 /// Collect the visible conversions of a base class.
862 /// \param Base a base class of the class we're considering
863 /// \param InVirtual whether this base class is a virtual base (or a base
864 /// of a virtual base)
865 /// \param Access the access along the inheritance path to this base
866 /// \param ParentHiddenTypes the conversions provided by the inheritors
868 /// \param Output the set to which to add conversions from non-virtual bases
869 /// \param VOutput the set to which to add conversions from virtual bases
870 /// \param HiddenVBaseCs the set of conversions which were hidden in a
871 /// virtual base along some inheritance path
872 static void CollectVisibleConversions(ASTContext &Context,
873 CXXRecordDecl *Record,
875 AccessSpecifier Access,
876 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
877 UnresolvedSetImpl &Output,
878 UnresolvedSetImpl &VOutput,
879 llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
880 // The set of types which have conversions in this class or its
881 // subclasses. As an optimization, we don't copy the derived set
882 // unless it might change.
883 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
884 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
886 // Collect the direct conversions and figure out which conversions
887 // will be hidden in the subclasses.
888 UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
890 HiddenTypesBuffer = ParentHiddenTypes;
891 HiddenTypes = &HiddenTypesBuffer;
893 for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
895 !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
897 // If this conversion is hidden and we're in a virtual base,
898 // remember that it's hidden along some inheritance path.
899 if (Hidden && InVirtual)
900 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
902 // If this conversion isn't hidden, add it to the appropriate output.
904 AccessSpecifier IAccess
905 = CXXRecordDecl::MergeAccess(Access, I.getAccess());
908 VOutput.addDecl(I.getDecl(), IAccess);
910 Output.addDecl(I.getDecl(), IAccess);
915 // Collect information recursively from any base classes.
916 for (CXXRecordDecl::base_class_iterator
917 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
918 const RecordType *RT = I->getType()->getAs<RecordType>();
921 AccessSpecifier BaseAccess
922 = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
923 bool BaseInVirtual = InVirtual || I->isVirtual();
925 CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
926 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
927 *HiddenTypes, Output, VOutput, HiddenVBaseCs);
931 /// Collect the visible conversions of a class.
933 /// This would be extremely straightforward if it weren't for virtual
934 /// bases. It might be worth special-casing that, really.
935 static void CollectVisibleConversions(ASTContext &Context,
936 CXXRecordDecl *Record,
937 UnresolvedSetImpl &Output) {
938 // The collection of all conversions in virtual bases that we've
939 // found. These will be added to the output as long as they don't
940 // appear in the hidden-conversions set.
941 UnresolvedSet<8> VBaseCs;
943 // The set of conversions in virtual bases that we've determined to
945 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
947 // The set of types hidden by classes derived from this one.
948 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
950 // Go ahead and collect the direct conversions and add them to the
952 UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
953 Output.append(Cs.begin(), Cs.end());
954 for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
955 HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
957 // Recursively collect conversions from base classes.
958 for (CXXRecordDecl::base_class_iterator
959 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
960 const RecordType *RT = I->getType()->getAs<RecordType>();
963 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
964 I->isVirtual(), I->getAccessSpecifier(),
965 HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
968 // Add any unhidden conversions provided by virtual bases.
969 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
971 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
972 Output.addDecl(I.getDecl(), I.getAccess());
976 /// getVisibleConversionFunctions - get all conversion functions visible
977 /// in current class; including conversion function templates.
978 const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
979 // If root class, all conversions are visible.
980 if (bases_begin() == bases_end())
981 return &data().Conversions;
982 // If visible conversion list is already evaluated, return it.
983 if (data().ComputedVisibleConversions)
984 return &data().VisibleConversions;
985 CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
986 data().ComputedVisibleConversions = true;
987 return &data().VisibleConversions;
990 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
991 // This operation is O(N) but extremely rare. Sema only uses it to
992 // remove UsingShadowDecls in a class that were followed by a direct
993 // declaration, e.g.:
995 // using B::operator int;
998 // This is uncommon by itself and even more uncommon in conjunction
999 // with sufficiently large numbers of directly-declared conversions
1000 // that asymptotic behavior matters.
1002 UnresolvedSetImpl &Convs = *getConversionFunctions();
1003 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1004 if (Convs[I].getDecl() == ConvDecl) {
1006 assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1007 && "conversion was found multiple times in unresolved set");
1012 llvm_unreachable("conversion not found in set!");
1015 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1016 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1017 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1022 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1023 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1027 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1028 TemplateSpecializationKind TSK) {
1029 assert(TemplateOrInstantiation.isNull() &&
1030 "Previous template or instantiation?");
1031 assert(!isa<ClassTemplateSpecializationDecl>(this));
1032 TemplateOrInstantiation
1033 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1036 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1037 if (const ClassTemplateSpecializationDecl *Spec
1038 = dyn_cast<ClassTemplateSpecializationDecl>(this))
1039 return Spec->getSpecializationKind();
1041 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1042 return MSInfo->getTemplateSpecializationKind();
1044 return TSK_Undeclared;
1048 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1049 if (ClassTemplateSpecializationDecl *Spec
1050 = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1051 Spec->setSpecializationKind(TSK);
1055 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1056 MSInfo->setTemplateSpecializationKind(TSK);
1060 assert(false && "Not a class template or member class specialization");
1063 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1064 ASTContext &Context = getASTContext();
1065 QualType ClassType = Context.getTypeDeclType(this);
1067 DeclarationName Name
1068 = Context.DeclarationNames.getCXXDestructorName(
1069 Context.getCanonicalType(ClassType));
1071 DeclContext::lookup_const_iterator I, E;
1072 llvm::tie(I, E) = lookup(Name);
1076 CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
1080 void CXXRecordDecl::completeDefinition() {
1081 completeDefinition(0);
1084 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1085 RecordDecl::completeDefinition();
1087 if (hasObjectMember() && getASTContext().getLangOptions().ObjCAutoRefCount) {
1088 // Objective-C Automatic Reference Counting:
1089 // If a class has a non-static data member of Objective-C pointer
1090 // type (or array thereof), it is a non-POD type and its
1091 // default constructor (if any), copy constructor, copy assignment
1092 // operator, and destructor are non-trivial.
1093 struct DefinitionData &Data = data();
1094 Data.PlainOldData = false;
1095 Data.HasTrivialDefaultConstructor = false;
1096 Data.HasTrivialCopyConstructor = false;
1097 Data.HasTrivialCopyAssignment = false;
1098 Data.HasTrivialDestructor = false;
1101 // If the class may be abstract (but hasn't been marked as such), check for
1102 // any pure final overriders.
1103 if (mayBeAbstract()) {
1104 CXXFinalOverriderMap MyFinalOverriders;
1105 if (!FinalOverriders) {
1106 getFinalOverriders(MyFinalOverriders);
1107 FinalOverriders = &MyFinalOverriders;
1111 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1112 MEnd = FinalOverriders->end();
1113 M != MEnd && !Done; ++M) {
1114 for (OverridingMethods::iterator SO = M->second.begin(),
1115 SOEnd = M->second.end();
1116 SO != SOEnd && !Done; ++SO) {
1117 assert(SO->second.size() > 0 &&
1118 "All virtual functions have overridding virtual functions");
1120 // C++ [class.abstract]p4:
1121 // A class is abstract if it contains or inherits at least one
1122 // pure virtual function for which the final overrider is pure
1124 if (SO->second.front().Method->isPure()) {
1125 data().Abstract = true;
1133 // Set access bits correctly on the directly-declared conversions.
1134 for (UnresolvedSetIterator I = data().Conversions.begin(),
1135 E = data().Conversions.end();
1137 data().Conversions.setAccess(I, (*I)->getAccess());
1140 bool CXXRecordDecl::mayBeAbstract() const {
1141 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1142 isDependentContext())
1145 for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1148 CXXRecordDecl *BaseDecl
1149 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1150 if (BaseDecl->isAbstract())
1158 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1159 SourceLocation StartLoc,
1160 const DeclarationNameInfo &NameInfo,
1161 QualType T, TypeSourceInfo *TInfo,
1162 bool isStatic, StorageClass SCAsWritten, bool isInline,
1163 SourceLocation EndLocation) {
1164 return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1165 isStatic, SCAsWritten, isInline, EndLocation);
1168 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1169 if (getOverloadedOperator() != OO_Delete &&
1170 getOverloadedOperator() != OO_Array_Delete)
1173 // C++ [basic.stc.dynamic.deallocation]p2:
1174 // A template instance is never a usual deallocation function,
1175 // regardless of its signature.
1176 if (getPrimaryTemplate())
1179 // C++ [basic.stc.dynamic.deallocation]p2:
1180 // If a class T has a member deallocation function named operator delete
1181 // with exactly one parameter, then that function is a usual (non-placement)
1182 // deallocation function. [...]
1183 if (getNumParams() == 1)
1186 // C++ [basic.stc.dynamic.deallocation]p2:
1187 // [...] If class T does not declare such an operator delete but does
1188 // declare a member deallocation function named operator delete with
1189 // exactly two parameters, the second of which has type std::size_t (18.1),
1190 // then this function is a usual deallocation function.
1191 ASTContext &Context = getASTContext();
1192 if (getNumParams() != 2 ||
1193 !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1194 Context.getSizeType()))
1197 // This function is a usual deallocation function if there are no
1198 // single-parameter deallocation functions of the same kind.
1199 for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1200 R.first != R.second; ++R.first) {
1201 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
1202 if (FD->getNumParams() == 1)
1209 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1210 // C++0x [class.copy]p17:
1211 // A user-declared copy assignment operator X::operator= is a non-static
1212 // non-template member function of class X with exactly one parameter of
1213 // type X, X&, const X&, volatile X& or const volatile X&.
1214 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1215 /*non-static*/ isStatic() ||
1216 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate())
1219 QualType ParamType = getParamDecl(0)->getType();
1220 if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1221 ParamType = Ref->getPointeeType();
1223 ASTContext &Context = getASTContext();
1225 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1226 return Context.hasSameUnqualifiedType(ClassType, ParamType);
1229 bool CXXMethodDecl::isMoveAssignmentOperator() const {
1230 // C++0x [class.copy]p19:
1231 // A user-declared move assignment operator X::operator= is a non-static
1232 // non-template member function of class X with exactly one parameter of type
1233 // X&&, const X&&, volatile X&&, or const volatile X&&.
1234 if (getOverloadedOperator() != OO_Equal || isStatic() ||
1235 getPrimaryTemplate() || getDescribedFunctionTemplate())
1238 QualType ParamType = getParamDecl(0)->getType();
1239 if (!isa<RValueReferenceType>(ParamType))
1241 ParamType = ParamType->getPointeeType();
1243 ASTContext &Context = getASTContext();
1245 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1246 return Context.hasSameUnqualifiedType(ClassType, ParamType);
1249 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1250 assert(MD->isCanonicalDecl() && "Method is not canonical!");
1251 assert(!MD->getParent()->isDependentContext() &&
1252 "Can't add an overridden method to a class template!");
1254 getASTContext().addOverriddenMethod(this, MD);
1257 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1258 return getASTContext().overridden_methods_begin(this);
1261 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1262 return getASTContext().overridden_methods_end(this);
1265 unsigned CXXMethodDecl::size_overridden_methods() const {
1266 return getASTContext().overridden_methods_size(this);
1269 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1270 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1271 // If the member function is declared const, the type of this is const X*,
1272 // if the member function is declared volatile, the type of this is
1273 // volatile X*, and if the member function is declared const volatile,
1274 // the type of this is const volatile X*.
1276 assert(isInstance() && "No 'this' for static methods!");
1278 QualType ClassTy = C.getTypeDeclType(getParent());
1279 ClassTy = C.getQualifiedType(ClassTy,
1280 Qualifiers::fromCVRMask(getTypeQualifiers()));
1281 return C.getPointerType(ClassTy);
1284 bool CXXMethodDecl::hasInlineBody() const {
1285 // If this function is a template instantiation, look at the template from
1286 // which it was instantiated.
1287 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1291 const FunctionDecl *fn;
1292 return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1295 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1296 TypeSourceInfo *TInfo, bool IsVirtual,
1297 SourceLocation L, Expr *Init,
1299 SourceLocation EllipsisLoc)
1300 : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1301 LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
1302 SourceOrderOrNumArrayIndices(0)
1306 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1308 SourceLocation MemberLoc,
1309 SourceLocation L, Expr *Init,
1311 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1312 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1313 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1317 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1318 IndirectFieldDecl *Member,
1319 SourceLocation MemberLoc,
1320 SourceLocation L, Expr *Init,
1322 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1323 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1324 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1328 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1329 SourceLocation D, SourceLocation L,
1330 CXXConstructorDecl *Target, Expr *Init,
1332 : Initializee(Target), MemberOrEllipsisLocation(D), Init(Init),
1333 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1334 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1338 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1340 SourceLocation MemberLoc,
1341 SourceLocation L, Expr *Init,
1344 unsigned NumIndices)
1345 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1346 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1347 IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1349 VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1350 memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1353 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1355 SourceLocation MemberLoc,
1356 SourceLocation L, Expr *Init,
1359 unsigned NumIndices) {
1360 void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1361 sizeof(VarDecl *) * NumIndices,
1362 llvm::alignOf<CXXCtorInitializer>());
1363 return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1364 Indices, NumIndices);
1367 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1368 if (isBaseInitializer())
1369 return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1374 const Type *CXXCtorInitializer::getBaseClass() const {
1375 if (isBaseInitializer())
1376 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1381 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1382 if (isAnyMemberInitializer() || isDelegatingInitializer())
1383 return getMemberLocation();
1385 if (isInClassMemberInitializer())
1386 return getAnyMember()->getLocation();
1388 return getBaseClassLoc().getLocalSourceRange().getBegin();
1391 SourceRange CXXCtorInitializer::getSourceRange() const {
1392 if (isInClassMemberInitializer()) {
1393 FieldDecl *D = getAnyMember();
1394 if (Expr *I = D->getInClassInitializer())
1395 return I->getSourceRange();
1396 return SourceRange();
1399 return SourceRange(getSourceLocation(), getRParenLoc());
1402 CXXConstructorDecl *
1403 CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1404 return new (C) CXXConstructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1405 QualType(), 0, false, false, false);
1408 CXXConstructorDecl *
1409 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1410 SourceLocation StartLoc,
1411 const DeclarationNameInfo &NameInfo,
1412 QualType T, TypeSourceInfo *TInfo,
1415 bool isImplicitlyDeclared) {
1416 assert(NameInfo.getName().getNameKind()
1417 == DeclarationName::CXXConstructorName &&
1418 "Name must refer to a constructor");
1419 return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1420 isExplicit, isInline, isImplicitlyDeclared);
1423 bool CXXConstructorDecl::isDefaultConstructor() const {
1424 // C++ [class.ctor]p5:
1425 // A default constructor for a class X is a constructor of class
1426 // X that can be called without an argument.
1427 return (getNumParams() == 0) ||
1428 (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1432 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1433 return isCopyOrMoveConstructor(TypeQuals) &&
1434 getParamDecl(0)->getType()->isLValueReferenceType();
1437 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1438 return isCopyOrMoveConstructor(TypeQuals) &&
1439 getParamDecl(0)->getType()->isRValueReferenceType();
1442 /// \brief Determine whether this is a copy or move constructor.
1443 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1444 // C++ [class.copy]p2:
1445 // A non-template constructor for class X is a copy constructor
1446 // if its first parameter is of type X&, const X&, volatile X& or
1447 // const volatile X&, and either there are no other parameters
1448 // or else all other parameters have default arguments (8.3.6).
1449 // C++0x [class.copy]p3:
1450 // A non-template constructor for class X is a move constructor if its
1451 // first parameter is of type X&&, const X&&, volatile X&&, or
1452 // const volatile X&&, and either there are no other parameters or else
1453 // all other parameters have default arguments.
1454 if ((getNumParams() < 1) ||
1455 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1456 (getPrimaryTemplate() != 0) ||
1457 (getDescribedFunctionTemplate() != 0))
1460 const ParmVarDecl *Param = getParamDecl(0);
1462 // Do we have a reference type?
1463 const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1467 // Is it a reference to our class type?
1468 ASTContext &Context = getASTContext();
1470 CanQualType PointeeType
1471 = Context.getCanonicalType(ParamRefType->getPointeeType());
1473 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1474 if (PointeeType.getUnqualifiedType() != ClassTy)
1477 // FIXME: other qualifiers?
1479 // We have a copy or move constructor.
1480 TypeQuals = PointeeType.getCVRQualifiers();
1484 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1485 // C++ [class.conv.ctor]p1:
1486 // A constructor declared without the function-specifier explicit
1487 // that can be called with a single parameter specifies a
1488 // conversion from the type of its first parameter to the type of
1489 // its class. Such a constructor is called a converting
1491 if (isExplicit() && !AllowExplicit)
1494 return (getNumParams() == 0 &&
1495 getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1496 (getNumParams() == 1) ||
1497 (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
1500 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1501 if ((getNumParams() < 1) ||
1502 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1503 (getPrimaryTemplate() == 0) ||
1504 (getDescribedFunctionTemplate() != 0))
1507 const ParmVarDecl *Param = getParamDecl(0);
1509 ASTContext &Context = getASTContext();
1510 CanQualType ParamType = Context.getCanonicalType(Param->getType());
1512 // Is it the same as our our class type?
1514 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1515 if (ParamType.getUnqualifiedType() != ClassTy)
1521 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1522 // Hack: we store the inherited constructor in the overridden method table
1523 method_iterator It = begin_overridden_methods();
1524 if (It == end_overridden_methods())
1527 return cast<CXXConstructorDecl>(*It);
1531 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1532 // Hack: we store the inherited constructor in the overridden method table
1533 assert(size_overridden_methods() == 0 && "Base ctor already set.");
1534 addOverriddenMethod(BaseCtor);
1538 CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1539 return new (C) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1540 QualType(), 0, false, false);
1544 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1545 SourceLocation StartLoc,
1546 const DeclarationNameInfo &NameInfo,
1547 QualType T, TypeSourceInfo *TInfo,
1549 bool isImplicitlyDeclared) {
1550 assert(NameInfo.getName().getNameKind()
1551 == DeclarationName::CXXDestructorName &&
1552 "Name must refer to a destructor");
1553 return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1554 isImplicitlyDeclared);
1558 CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
1559 return new (C) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1560 QualType(), 0, false, false,
1565 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1566 SourceLocation StartLoc,
1567 const DeclarationNameInfo &NameInfo,
1568 QualType T, TypeSourceInfo *TInfo,
1569 bool isInline, bool isExplicit,
1570 SourceLocation EndLocation) {
1571 assert(NameInfo.getName().getNameKind()
1572 == DeclarationName::CXXConversionFunctionName &&
1573 "Name must refer to a conversion function");
1574 return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1575 isInline, isExplicit, EndLocation);
1578 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1580 SourceLocation ExternLoc,
1581 SourceLocation LangLoc,
1583 SourceLocation RBraceLoc) {
1584 return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
1587 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1589 SourceLocation NamespaceLoc,
1590 NestedNameSpecifierLoc QualifierLoc,
1591 SourceLocation IdentLoc,
1593 DeclContext *CommonAncestor) {
1594 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1595 Used = NS->getOriginalNamespace();
1596 return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1597 IdentLoc, Used, CommonAncestor);
1600 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1601 if (NamespaceAliasDecl *NA =
1602 dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1603 return NA->getNamespace();
1604 return cast_or_null<NamespaceDecl>(NominatedNamespace);
1607 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1608 SourceLocation UsingLoc,
1609 SourceLocation AliasLoc,
1610 IdentifierInfo *Alias,
1611 NestedNameSpecifierLoc QualifierLoc,
1612 SourceLocation IdentLoc,
1613 NamedDecl *Namespace) {
1614 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1615 Namespace = NS->getOriginalNamespace();
1616 return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias,
1617 QualifierLoc, IdentLoc, Namespace);
1620 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1621 const UsingShadowDecl *Shadow = this;
1622 while (const UsingShadowDecl *NextShadow =
1623 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1624 Shadow = NextShadow;
1625 return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1628 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1629 assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1630 "declaration already in set");
1631 assert(S->getUsingDecl() == this);
1633 if (FirstUsingShadow)
1634 S->UsingOrNextShadow = FirstUsingShadow;
1635 FirstUsingShadow = S;
1638 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1639 assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1640 "declaration not in set");
1641 assert(S->getUsingDecl() == this);
1643 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1645 if (FirstUsingShadow == S) {
1646 FirstUsingShadow = dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow);
1647 S->UsingOrNextShadow = this;
1651 UsingShadowDecl *Prev = FirstUsingShadow;
1652 while (Prev->UsingOrNextShadow != S)
1653 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1654 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1655 S->UsingOrNextShadow = this;
1658 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1659 NestedNameSpecifierLoc QualifierLoc,
1660 const DeclarationNameInfo &NameInfo,
1661 bool IsTypeNameArg) {
1662 return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1665 UnresolvedUsingValueDecl *
1666 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1667 SourceLocation UsingLoc,
1668 NestedNameSpecifierLoc QualifierLoc,
1669 const DeclarationNameInfo &NameInfo) {
1670 return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1671 QualifierLoc, NameInfo);
1674 UnresolvedUsingTypenameDecl *
1675 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1676 SourceLocation UsingLoc,
1677 SourceLocation TypenameLoc,
1678 NestedNameSpecifierLoc QualifierLoc,
1679 SourceLocation TargetNameLoc,
1680 DeclarationName TargetName) {
1681 return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1682 QualifierLoc, TargetNameLoc,
1683 TargetName.getAsIdentifierInfo());
1686 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1687 SourceLocation StaticAssertLoc,
1689 StringLiteral *Message,
1690 SourceLocation RParenLoc) {
1691 return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
1695 static const char *getAccessName(AccessSpecifier AS) {
1699 assert("Invalid access specifier!");
1710 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1711 AccessSpecifier AS) {
1712 return DB << getAccessName(AS);