]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp
Replace our version of the pwcache(3) API with NetBSD's implementation.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / DeclCXX.cpp
1 //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the C++ related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // Decl Allocation/Deallocation Method Implementations
29 //===----------------------------------------------------------------------===//
30
31 void AccessSpecDecl::anchor() { }
32
33 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
34   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
35   return new (Mem) AccessSpecDecl(EmptyShell());
36 }
37
38 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
39   : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
40     UserDeclaredMoveConstructor(false), UserDeclaredCopyAssignment(false),
41     UserDeclaredMoveAssignment(false), UserDeclaredDestructor(false),
42     Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
43     Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
44     HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
45     HasMutableFields(false), HasOnlyCMembers(true),
46     HasInClassInitializer(false),
47     HasTrivialDefaultConstructor(true),
48     HasConstexprNonCopyMoveConstructor(false),
49     DefaultedDefaultConstructorIsConstexpr(true),
50     HasConstexprDefaultConstructor(false), HasTrivialCopyConstructor(true),
51     HasTrivialMoveConstructor(true), HasTrivialCopyAssignment(true),
52     HasTrivialMoveAssignment(true), HasTrivialDestructor(true),
53     HasIrrelevantDestructor(true),
54     HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
55     UserProvidedDefaultConstructor(false), DeclaredDefaultConstructor(false),
56     DeclaredCopyConstructor(false), DeclaredMoveConstructor(false),
57     DeclaredCopyAssignment(false), DeclaredMoveAssignment(false),
58     DeclaredDestructor(false), FailedImplicitMoveConstructor(false),
59     FailedImplicitMoveAssignment(false), IsLambda(false), NumBases(0),
60     NumVBases(0), Bases(), VBases(), Definition(D), FirstFriend(0) {
61 }
62
63 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
64   return Bases.get(Definition->getASTContext().getExternalSource());
65 }
66
67 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
68   return VBases.get(Definition->getASTContext().getExternalSource());
69 }
70
71 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
72                              SourceLocation StartLoc, SourceLocation IdLoc,
73                              IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
74   : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
75     DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
76     TemplateOrInstantiation() { }
77
78 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
79                                      DeclContext *DC, SourceLocation StartLoc,
80                                      SourceLocation IdLoc, IdentifierInfo *Id,
81                                      CXXRecordDecl* PrevDecl,
82                                      bool DelayTypeCreation) {
83   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
84                                            Id, PrevDecl);
85
86   // FIXME: DelayTypeCreation seems like such a hack
87   if (!DelayTypeCreation)
88     C.getTypeDeclType(R, PrevDecl);
89   return R;
90 }
91
92 CXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
93                                            SourceLocation Loc, bool Dependent) {
94   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc, Loc,
95                                            0, 0);
96   R->IsBeingDefined = true;
97   R->DefinitionData = new (C) struct LambdaDefinitionData(R, Dependent);
98   C.getTypeDeclType(R, /*PrevDecl=*/0);
99   return R;
100 }
101
102 CXXRecordDecl *
103 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
104   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
105   return new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(),
106                                  SourceLocation(), 0, 0);
107 }
108
109 void
110 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
111                         unsigned NumBases) {
112   ASTContext &C = getASTContext();
113
114   if (!data().Bases.isOffset() && data().NumBases > 0)
115     C.Deallocate(data().getBases());
116
117   if (NumBases) {
118     // C++ [dcl.init.aggr]p1:
119     //   An aggregate is [...] a class with [...] no base classes [...].
120     data().Aggregate = false;
121
122     // C++ [class]p4:
123     //   A POD-struct is an aggregate class...
124     data().PlainOldData = false;
125   }
126
127   // The set of seen virtual base types.
128   llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
129   
130   // The virtual bases of this class.
131   SmallVector<const CXXBaseSpecifier *, 8> VBases;
132
133   data().Bases = new(C) CXXBaseSpecifier [NumBases];
134   data().NumBases = NumBases;
135   for (unsigned i = 0; i < NumBases; ++i) {
136     data().getBases()[i] = *Bases[i];
137     // Keep track of inherited vbases for this base class.
138     const CXXBaseSpecifier *Base = Bases[i];
139     QualType BaseType = Base->getType();
140     // Skip dependent types; we can't do any checking on them now.
141     if (BaseType->isDependentType())
142       continue;
143     CXXRecordDecl *BaseClassDecl
144       = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
145
146     // A class with a non-empty base class is not empty.
147     // FIXME: Standard ref?
148     if (!BaseClassDecl->isEmpty()) {
149       if (!data().Empty) {
150         // C++0x [class]p7:
151         //   A standard-layout class is a class that:
152         //    [...]
153         //    -- either has no non-static data members in the most derived
154         //       class and at most one base class with non-static data members,
155         //       or has no base classes with non-static data members, and
156         // If this is the second non-empty base, then neither of these two
157         // clauses can be true.
158         data().IsStandardLayout = false;
159       }
160
161       data().Empty = false;
162       data().HasNoNonEmptyBases = false;
163     }
164     
165     // C++ [class.virtual]p1:
166     //   A class that declares or inherits a virtual function is called a 
167     //   polymorphic class.
168     if (BaseClassDecl->isPolymorphic())
169       data().Polymorphic = true;
170
171     // C++0x [class]p7:
172     //   A standard-layout class is a class that: [...]
173     //    -- has no non-standard-layout base classes
174     if (!BaseClassDecl->isStandardLayout())
175       data().IsStandardLayout = false;
176
177     // Record if this base is the first non-literal field or base.
178     if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
179       data().HasNonLiteralTypeFieldsOrBases = true;
180     
181     // Now go through all virtual bases of this base and add them.
182     for (CXXRecordDecl::base_class_iterator VBase =
183           BaseClassDecl->vbases_begin(),
184          E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
185       // Add this base if it's not already in the list.
186       if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
187         VBases.push_back(VBase);
188     }
189
190     if (Base->isVirtual()) {
191       // Add this base if it's not already in the list.
192       if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
193           VBases.push_back(Base);
194       
195       // C++0x [meta.unary.prop] is_empty:
196       //    T is a class type, but not a union type, with ... no virtual base
197       //    classes
198       data().Empty = false;
199       
200       // C++ [class.ctor]p5:
201       //   A default constructor is trivial [...] if:
202       //    -- its class has [...] no virtual bases
203       data().HasTrivialDefaultConstructor = false;
204
205       // C++0x [class.copy]p13:
206       //   A copy/move constructor for class X is trivial if it is neither
207       //   user-provided nor deleted and if
208       //    -- class X has no virtual functions and no virtual base classes, and
209       data().HasTrivialCopyConstructor = false;
210       data().HasTrivialMoveConstructor = false;
211
212       // C++0x [class.copy]p27:
213       //   A copy/move assignment operator for class X is trivial if it is
214       //   neither user-provided nor deleted and if
215       //    -- class X has no virtual functions and no virtual base classes, and
216       data().HasTrivialCopyAssignment = false;
217       data().HasTrivialMoveAssignment = false;
218
219       // C++0x [class]p7:
220       //   A standard-layout class is a class that: [...]
221       //    -- has [...] no virtual base classes
222       data().IsStandardLayout = false;
223
224       // C++11 [dcl.constexpr]p4:
225       //   In the definition of a constexpr constructor [...]
226       //    -- the class shall not have any virtual base classes
227       data().DefaultedDefaultConstructorIsConstexpr = false;
228     } else {
229       // C++ [class.ctor]p5:
230       //   A default constructor is trivial [...] if:
231       //    -- all the direct base classes of its class have trivial default
232       //       constructors.
233       if (!BaseClassDecl->hasTrivialDefaultConstructor())
234         data().HasTrivialDefaultConstructor = false;
235       
236       // C++0x [class.copy]p13:
237       //   A copy/move constructor for class X is trivial if [...]
238       //    [...]
239       //    -- the constructor selected to copy/move each direct base class
240       //       subobject is trivial, and
241       // FIXME: C++0x: We need to only consider the selected constructor
242       // instead of all of them.
243       if (!BaseClassDecl->hasTrivialCopyConstructor())
244         data().HasTrivialCopyConstructor = false;
245       if (!BaseClassDecl->hasTrivialMoveConstructor())
246         data().HasTrivialMoveConstructor = false;
247
248       // C++0x [class.copy]p27:
249       //   A copy/move assignment operator for class X is trivial if [...]
250       //    [...]
251       //    -- the assignment operator selected to copy/move each direct base
252       //       class subobject is trivial, and
253       // FIXME: C++0x: We need to only consider the selected operator instead
254       // of all of them.
255       if (!BaseClassDecl->hasTrivialCopyAssignment())
256         data().HasTrivialCopyAssignment = false;
257       if (!BaseClassDecl->hasTrivialMoveAssignment())
258         data().HasTrivialMoveAssignment = false;
259
260       // C++11 [class.ctor]p6:
261       //   If that user-written default constructor would satisfy the
262       //   requirements of a constexpr constructor, the implicitly-defined
263       //   default constructor is constexpr.
264       if (!BaseClassDecl->hasConstexprDefaultConstructor())
265         data().DefaultedDefaultConstructorIsConstexpr = false;
266     }
267     
268     // C++ [class.ctor]p3:
269     //   A destructor is trivial if all the direct base classes of its class
270     //   have trivial destructors.
271     if (!BaseClassDecl->hasTrivialDestructor())
272       data().HasTrivialDestructor = false;
273
274     if (!BaseClassDecl->hasIrrelevantDestructor())
275       data().HasIrrelevantDestructor = false;
276
277     // A class has an Objective-C object member if... or any of its bases
278     // has an Objective-C object member.
279     if (BaseClassDecl->hasObjectMember())
280       setHasObjectMember(true);
281
282     // Keep track of the presence of mutable fields.
283     if (BaseClassDecl->hasMutableFields())
284       data().HasMutableFields = true;
285   }
286   
287   if (VBases.empty())
288     return;
289
290   // Create base specifier for any direct or indirect virtual bases.
291   data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
292   data().NumVBases = VBases.size();
293   for (int I = 0, E = VBases.size(); I != E; ++I)
294     data().getVBases()[I] = *VBases[I];
295 }
296
297 /// Callback function for CXXRecordDecl::forallBases that acknowledges
298 /// that it saw a base class.
299 static bool SawBase(const CXXRecordDecl *, void *) {
300   return true;
301 }
302
303 bool CXXRecordDecl::hasAnyDependentBases() const {
304   if (!isDependentContext())
305     return false;
306
307   return !forallBases(SawBase, 0);
308 }
309
310 bool CXXRecordDecl::hasConstCopyConstructor() const {
311   return getCopyConstructor(Qualifiers::Const) != 0;
312 }
313
314 bool CXXRecordDecl::isTriviallyCopyable() const {
315   // C++0x [class]p5:
316   //   A trivially copyable class is a class that:
317   //   -- has no non-trivial copy constructors,
318   if (!hasTrivialCopyConstructor()) return false;
319   //   -- has no non-trivial move constructors,
320   if (!hasTrivialMoveConstructor()) return false;
321   //   -- has no non-trivial copy assignment operators,
322   if (!hasTrivialCopyAssignment()) return false;
323   //   -- has no non-trivial move assignment operators, and
324   if (!hasTrivialMoveAssignment()) return false;
325   //   -- has a trivial destructor.
326   if (!hasTrivialDestructor()) return false;
327
328   return true;
329 }
330
331 /// \brief Perform a simplistic form of overload resolution that only considers
332 /// cv-qualifiers on a single parameter, and return the best overload candidate
333 /// (if there is one).
334 static CXXMethodDecl *
335 GetBestOverloadCandidateSimple(
336   const SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
337   if (Cands.empty())
338     return 0;
339   if (Cands.size() == 1)
340     return Cands[0].first;
341   
342   unsigned Best = 0, N = Cands.size();
343   for (unsigned I = 1; I != N; ++I)
344     if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
345       Best = I;
346   
347   for (unsigned I = 0; I != N; ++I)
348     if (I != Best && Cands[Best].second.compatiblyIncludes(Cands[I].second))
349       return 0;
350   
351   return Cands[Best].first;
352 }
353
354 CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(unsigned TypeQuals) const{
355   ASTContext &Context = getASTContext();
356   QualType ClassType
357     = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
358   DeclarationName ConstructorName
359     = Context.DeclarationNames.getCXXConstructorName(
360                                           Context.getCanonicalType(ClassType));
361   unsigned FoundTQs;
362   SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
363   DeclContext::lookup_const_iterator Con, ConEnd;
364   for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
365        Con != ConEnd; ++Con) {
366     // C++ [class.copy]p2:
367     //   A non-template constructor for class X is a copy constructor if [...]
368     if (isa<FunctionTemplateDecl>(*Con))
369       continue;
370
371     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
372     if (Constructor->isCopyConstructor(FoundTQs)) {
373       if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
374           (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
375         Found.push_back(std::make_pair(
376                                  const_cast<CXXConstructorDecl *>(Constructor), 
377                                        Qualifiers::fromCVRMask(FoundTQs)));
378     }
379   }
380   
381   return cast_or_null<CXXConstructorDecl>(
382                                         GetBestOverloadCandidateSimple(Found));
383 }
384
385 CXXConstructorDecl *CXXRecordDecl::getMoveConstructor() const {
386   for (ctor_iterator I = ctor_begin(), E = ctor_end(); I != E; ++I)
387     if (I->isMoveConstructor())
388       return *I;
389
390   return 0;
391 }
392
393 CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
394   ASTContext &Context = getASTContext();
395   QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
396   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
397   
398   SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
399   DeclContext::lookup_const_iterator Op, OpEnd;
400   for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
401     // C++ [class.copy]p9:
402     //   A user-declared copy assignment operator is a non-static non-template
403     //   member function of class X with exactly one parameter of type X, X&,
404     //   const X&, volatile X& or const volatile X&.
405     const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
406     if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
407       continue;
408     
409     const FunctionProtoType *FnType 
410       = Method->getType()->getAs<FunctionProtoType>();
411     assert(FnType && "Overloaded operator has no prototype.");
412     // Don't assert on this; an invalid decl might have been left in the AST.
413     if (FnType->getNumArgs() != 1 || FnType->isVariadic())
414       continue;
415     
416     QualType ArgType = FnType->getArgType(0);
417     Qualifiers Quals;
418     if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
419       ArgType = Ref->getPointeeType();
420       // If we have a const argument and we have a reference to a non-const,
421       // this function does not match.
422       if (ArgIsConst && !ArgType.isConstQualified())
423         continue;
424       
425       Quals = ArgType.getQualifiers();
426     } else {
427       // By-value copy-assignment operators are treated like const X&
428       // copy-assignment operators.
429       Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
430     }
431     
432     if (!Context.hasSameUnqualifiedType(ArgType, Class))
433       continue;
434
435     // Save this copy-assignment operator. It might be "the one".
436     Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
437   }
438   
439   // Use a simplistic form of overload resolution to find the candidate.
440   return GetBestOverloadCandidateSimple(Found);
441 }
442
443 CXXMethodDecl *CXXRecordDecl::getMoveAssignmentOperator() const {
444   for (method_iterator I = method_begin(), E = method_end(); I != E; ++I)
445     if (I->isMoveAssignmentOperator())
446       return *I;
447
448   return 0;
449 }
450
451 void CXXRecordDecl::markedVirtualFunctionPure() {
452   // C++ [class.abstract]p2: 
453   //   A class is abstract if it has at least one pure virtual function.
454   data().Abstract = true;
455 }
456
457 void CXXRecordDecl::markedConstructorConstexpr(CXXConstructorDecl *CD) {
458   if (!CD->isCopyOrMoveConstructor())
459     data().HasConstexprNonCopyMoveConstructor = true;
460
461   if (CD->isDefaultConstructor())
462     data().HasConstexprDefaultConstructor = true;
463 }
464
465 void CXXRecordDecl::addedMember(Decl *D) {
466   if (!D->isImplicit() &&
467       !isa<FieldDecl>(D) &&
468       !isa<IndirectFieldDecl>(D) &&
469       (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class))
470     data().HasOnlyCMembers = false;
471
472   // Ignore friends and invalid declarations.
473   if (D->getFriendObjectKind() || D->isInvalidDecl())
474     return;
475   
476   FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
477   if (FunTmpl)
478     D = FunTmpl->getTemplatedDecl();
479   
480   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
481     if (Method->isVirtual()) {
482       // C++ [dcl.init.aggr]p1:
483       //   An aggregate is an array or a class with [...] no virtual functions.
484       data().Aggregate = false;
485       
486       // C++ [class]p4:
487       //   A POD-struct is an aggregate class...
488       data().PlainOldData = false;
489       
490       // Virtual functions make the class non-empty.
491       // FIXME: Standard ref?
492       data().Empty = false;
493
494       // C++ [class.virtual]p1:
495       //   A class that declares or inherits a virtual function is called a 
496       //   polymorphic class.
497       data().Polymorphic = true;
498       
499       // C++0x [class.ctor]p5
500       //   A default constructor is trivial [...] if:
501       //    -- its class has no virtual functions [...]
502       data().HasTrivialDefaultConstructor = false;
503
504       // C++0x [class.copy]p13:
505       //   A copy/move constructor for class X is trivial if [...]
506       //    -- class X has no virtual functions [...]
507       data().HasTrivialCopyConstructor = false;
508       data().HasTrivialMoveConstructor = false;
509
510       // C++0x [class.copy]p27:
511       //   A copy/move assignment operator for class X is trivial if [...]
512       //    -- class X has no virtual functions [...]
513       data().HasTrivialCopyAssignment = false;
514       data().HasTrivialMoveAssignment = false;
515             
516       // C++0x [class]p7:
517       //   A standard-layout class is a class that: [...]
518       //    -- has no virtual functions
519       data().IsStandardLayout = false;
520     }
521   }
522   
523   if (D->isImplicit()) {
524     // Notify that an implicit member was added after the definition
525     // was completed.
526     if (!isBeingDefined())
527       if (ASTMutationListener *L = getASTMutationListener())
528         L->AddedCXXImplicitMember(data().Definition, D);
529
530     // If this is a special member function, note that it was added and then
531     // return early.
532     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
533       if (Constructor->isDefaultConstructor()) {
534         data().DeclaredDefaultConstructor = true;
535         if (Constructor->isConstexpr()) {
536           data().HasConstexprDefaultConstructor = true;
537           data().HasConstexprNonCopyMoveConstructor = true;
538         }
539       } else if (Constructor->isCopyConstructor()) {
540         data().DeclaredCopyConstructor = true;
541       } else if (Constructor->isMoveConstructor()) {
542         data().DeclaredMoveConstructor = true;
543       } else
544         goto NotASpecialMember;
545       return;
546     } else if (isa<CXXDestructorDecl>(D)) {
547       data().DeclaredDestructor = true;
548       return;
549     } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
550       if (Method->isCopyAssignmentOperator())
551         data().DeclaredCopyAssignment = true;
552       else if (Method->isMoveAssignmentOperator())
553         data().DeclaredMoveAssignment = true;
554       else
555         goto NotASpecialMember;
556       return;
557     }
558
559 NotASpecialMember:;
560     // Any other implicit declarations are handled like normal declarations.
561   }
562   
563   // Handle (user-declared) constructors.
564   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
565     // Note that we have a user-declared constructor.
566     data().UserDeclaredConstructor = true;
567
568     // Technically, "user-provided" is only defined for special member
569     // functions, but the intent of the standard is clearly that it should apply
570     // to all functions.
571     bool UserProvided = Constructor->isUserProvided();
572
573     if (Constructor->isDefaultConstructor()) {
574       data().DeclaredDefaultConstructor = true;
575       if (UserProvided) {
576         // C++0x [class.ctor]p5:
577         //   A default constructor is trivial if it is not user-provided [...]
578         data().HasTrivialDefaultConstructor = false;
579         data().UserProvidedDefaultConstructor = true;
580       }
581       if (Constructor->isConstexpr()) {
582         data().HasConstexprDefaultConstructor = true;
583         data().HasConstexprNonCopyMoveConstructor = true;
584       }
585     }
586
587     // Note when we have a user-declared copy or move constructor, which will
588     // suppress the implicit declaration of those constructors.
589     if (!FunTmpl) {
590       if (Constructor->isCopyConstructor()) {
591         data().UserDeclaredCopyConstructor = true;
592         data().DeclaredCopyConstructor = true;
593
594         // C++0x [class.copy]p13:
595         //   A copy/move constructor for class X is trivial if it is not
596         //   user-provided [...]
597         if (UserProvided)
598           data().HasTrivialCopyConstructor = false;
599       } else if (Constructor->isMoveConstructor()) {
600         data().UserDeclaredMoveConstructor = true;
601         data().DeclaredMoveConstructor = true;
602
603         // C++0x [class.copy]p13:
604         //   A copy/move constructor for class X is trivial if it is not
605         //   user-provided [...]
606         if (UserProvided)
607           data().HasTrivialMoveConstructor = false;
608       }
609     }
610     if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor()) {
611       // Record if we see any constexpr constructors which are neither copy
612       // nor move constructors.
613       data().HasConstexprNonCopyMoveConstructor = true;
614     }
615
616     // C++ [dcl.init.aggr]p1:
617     //   An aggregate is an array or a class with no user-declared
618     //   constructors [...].
619     // C++0x [dcl.init.aggr]p1:
620     //   An aggregate is an array or a class with no user-provided
621     //   constructors [...].
622     if (!getASTContext().getLangOpts().CPlusPlus0x || UserProvided)
623       data().Aggregate = false;
624
625     // C++ [class]p4:
626     //   A POD-struct is an aggregate class [...]
627     // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
628     // type is technically an aggregate in C++0x since it wouldn't be in 03.
629     data().PlainOldData = false;
630
631     return;
632   }
633
634   // Handle (user-declared) destructors.
635   if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
636     data().DeclaredDestructor = true;
637     data().UserDeclaredDestructor = true;
638     data().HasIrrelevantDestructor = false;
639
640     // C++ [class]p4: 
641     //   A POD-struct is an aggregate class that has [...] no user-defined 
642     //   destructor.
643     // This bit is the C++03 POD bit, not the 0x one.
644     data().PlainOldData = false;
645     
646     // C++11 [class.dtor]p5: 
647     //   A destructor is trivial if it is not user-provided and if
648     //    -- the destructor is not virtual.
649     if (DD->isUserProvided() || DD->isVirtual())
650       data().HasTrivialDestructor = false;
651
652     return;
653   }
654   
655   // Handle (user-declared) member functions.
656   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
657     if (Method->isCopyAssignmentOperator()) {
658       // C++ [class]p4:
659       //   A POD-struct is an aggregate class that [...] has no user-defined
660       //   copy assignment operator [...].
661       // This is the C++03 bit only.
662       data().PlainOldData = false;
663
664       // This is a copy assignment operator.
665
666       // Suppress the implicit declaration of a copy constructor.
667       data().UserDeclaredCopyAssignment = true;
668       data().DeclaredCopyAssignment = true;
669
670       // C++0x [class.copy]p27:
671       //   A copy/move assignment operator for class X is trivial if it is
672       //   neither user-provided nor deleted [...]
673       if (Method->isUserProvided())
674         data().HasTrivialCopyAssignment = false;
675
676       return;
677     }
678     
679     if (Method->isMoveAssignmentOperator()) {
680       // This is an extension in C++03 mode, but we'll keep consistency by
681       // taking a move assignment operator to induce non-POD-ness
682       data().PlainOldData = false;
683
684       // This is a move assignment operator.
685       data().UserDeclaredMoveAssignment = true;
686       data().DeclaredMoveAssignment = true;
687
688       // C++0x [class.copy]p27:
689       //   A copy/move assignment operator for class X is trivial if it is
690       //   neither user-provided nor deleted [...]
691       if (Method->isUserProvided())
692         data().HasTrivialMoveAssignment = false;
693     }
694
695     // Keep the list of conversion functions up-to-date.
696     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
697       // We don't record specializations.
698       if (Conversion->getPrimaryTemplate())
699         return;
700       
701       // FIXME: We intentionally don't use the decl's access here because it
702       // hasn't been set yet.  That's really just a misdesign in Sema.
703
704       if (FunTmpl) {
705         if (FunTmpl->getPreviousDecl())
706           data().Conversions.replace(FunTmpl->getPreviousDecl(),
707                                      FunTmpl);
708         else
709           data().Conversions.addDecl(FunTmpl);
710       } else {
711         if (Conversion->getPreviousDecl())
712           data().Conversions.replace(Conversion->getPreviousDecl(),
713                                      Conversion);
714         else
715           data().Conversions.addDecl(Conversion);        
716       }
717     }
718     
719     return;
720   }
721   
722   // Handle non-static data members.
723   if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
724     // C++ [class.bit]p2:
725     //   A declaration for a bit-field that omits the identifier declares an 
726     //   unnamed bit-field. Unnamed bit-fields are not members and cannot be 
727     //   initialized.
728     if (Field->isUnnamedBitfield())
729       return;
730     
731     // C++ [dcl.init.aggr]p1:
732     //   An aggregate is an array or a class (clause 9) with [...] no
733     //   private or protected non-static data members (clause 11).
734     //
735     // A POD must be an aggregate.    
736     if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
737       data().Aggregate = false;
738       data().PlainOldData = false;
739     }
740
741     // C++0x [class]p7:
742     //   A standard-layout class is a class that:
743     //    [...]
744     //    -- has the same access control for all non-static data members,
745     switch (D->getAccess()) {
746     case AS_private:    data().HasPrivateFields = true;   break;
747     case AS_protected:  data().HasProtectedFields = true; break;
748     case AS_public:     data().HasPublicFields = true;    break;
749     case AS_none:       llvm_unreachable("Invalid access specifier");
750     };
751     if ((data().HasPrivateFields + data().HasProtectedFields +
752          data().HasPublicFields) > 1)
753       data().IsStandardLayout = false;
754
755     // Keep track of the presence of mutable fields.
756     if (Field->isMutable())
757       data().HasMutableFields = true;
758     
759     // C++0x [class]p9:
760     //   A POD struct is a class that is both a trivial class and a 
761     //   standard-layout class, and has no non-static data members of type 
762     //   non-POD struct, non-POD union (or array of such types).
763     //
764     // Automatic Reference Counting: the presence of a member of Objective-C pointer type
765     // that does not explicitly have no lifetime makes the class a non-POD.
766     // However, we delay setting PlainOldData to false in this case so that
767     // Sema has a chance to diagnostic causes where the same class will be
768     // non-POD with Automatic Reference Counting but a POD without ARC.
769     // In this case, the class will become a non-POD class when we complete
770     // the definition.
771     ASTContext &Context = getASTContext();
772     QualType T = Context.getBaseElementType(Field->getType());
773     if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
774       if (!Context.getLangOpts().ObjCAutoRefCount ||
775           T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
776         setHasObjectMember(true);
777     } else if (!T.isPODType(Context))
778       data().PlainOldData = false;
779     
780     if (T->isReferenceType()) {
781       data().HasTrivialDefaultConstructor = false;
782
783       // C++0x [class]p7:
784       //   A standard-layout class is a class that:
785       //    -- has no non-static data members of type [...] reference,
786       data().IsStandardLayout = false;
787     }
788
789     // Record if this field is the first non-literal or volatile field or base.
790     if (!T->isLiteralType() || T.isVolatileQualified())
791       data().HasNonLiteralTypeFieldsOrBases = true;
792
793     if (Field->hasInClassInitializer()) {
794       data().HasInClassInitializer = true;
795
796       // C++11 [class]p5:
797       //   A default constructor is trivial if [...] no non-static data member
798       //   of its class has a brace-or-equal-initializer.
799       data().HasTrivialDefaultConstructor = false;
800
801       // C++11 [dcl.init.aggr]p1:
802       //   An aggregate is a [...] class with [...] no
803       //   brace-or-equal-initializers for non-static data members.
804       data().Aggregate = false;
805
806       // C++11 [class]p10:
807       //   A POD struct is [...] a trivial class.
808       data().PlainOldData = false;
809     }
810
811     if (const RecordType *RecordTy = T->getAs<RecordType>()) {
812       CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
813       if (FieldRec->getDefinition()) {
814         // C++0x [class.ctor]p5:
815         //   A default constructor is trivial [...] if:
816         //    -- for all the non-static data members of its class that are of
817         //       class type (or array thereof), each such class has a trivial
818         //       default constructor.
819         if (!FieldRec->hasTrivialDefaultConstructor())
820           data().HasTrivialDefaultConstructor = false;
821
822         // C++0x [class.copy]p13:
823         //   A copy/move constructor for class X is trivial if [...]
824         //    [...]
825         //    -- for each non-static data member of X that is of class type (or
826         //       an array thereof), the constructor selected to copy/move that
827         //       member is trivial;
828         // FIXME: C++0x: We don't correctly model 'selected' constructors.
829         if (!FieldRec->hasTrivialCopyConstructor())
830           data().HasTrivialCopyConstructor = false;
831         if (!FieldRec->hasTrivialMoveConstructor())
832           data().HasTrivialMoveConstructor = false;
833
834         // C++0x [class.copy]p27:
835         //   A copy/move assignment operator for class X is trivial if [...]
836         //    [...]
837         //    -- for each non-static data member of X that is of class type (or
838         //       an array thereof), the assignment operator selected to
839         //       copy/move that member is trivial;
840         // FIXME: C++0x: We don't correctly model 'selected' operators.
841         if (!FieldRec->hasTrivialCopyAssignment())
842           data().HasTrivialCopyAssignment = false;
843         if (!FieldRec->hasTrivialMoveAssignment())
844           data().HasTrivialMoveAssignment = false;
845
846         if (!FieldRec->hasTrivialDestructor())
847           data().HasTrivialDestructor = false;
848         if (!FieldRec->hasIrrelevantDestructor())
849           data().HasIrrelevantDestructor = false;
850         if (FieldRec->hasObjectMember())
851           setHasObjectMember(true);
852
853         // C++0x [class]p7:
854         //   A standard-layout class is a class that:
855         //    -- has no non-static data members of type non-standard-layout
856         //       class (or array of such types) [...]
857         if (!FieldRec->isStandardLayout())
858           data().IsStandardLayout = false;
859
860         // C++0x [class]p7:
861         //   A standard-layout class is a class that:
862         //    [...]
863         //    -- has no base classes of the same type as the first non-static
864         //       data member.
865         // We don't want to expend bits in the state of the record decl
866         // tracking whether this is the first non-static data member so we
867         // cheat a bit and use some of the existing state: the empty bit.
868         // Virtual bases and virtual methods make a class non-empty, but they
869         // also make it non-standard-layout so we needn't check here.
870         // A non-empty base class may leave the class standard-layout, but not
871         // if we have arrived here, and have at least on non-static data
872         // member. If IsStandardLayout remains true, then the first non-static
873         // data member must come through here with Empty still true, and Empty
874         // will subsequently be set to false below.
875         if (data().IsStandardLayout && data().Empty) {
876           for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
877                                                         BE = bases_end();
878                BI != BE; ++BI) {
879             if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
880               data().IsStandardLayout = false;
881               break;
882             }
883           }
884         }
885         
886         // Keep track of the presence of mutable fields.
887         if (FieldRec->hasMutableFields())
888           data().HasMutableFields = true;
889
890         // C++11 [class.copy]p13:
891         //   If the implicitly-defined constructor would satisfy the
892         //   requirements of a constexpr constructor, the implicitly-defined
893         //   constructor is constexpr.
894         // C++11 [dcl.constexpr]p4:
895         //    -- every constructor involved in initializing non-static data
896         //       members [...] shall be a constexpr constructor
897         if (!Field->hasInClassInitializer() &&
898             !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
899           // The standard requires any in-class initializer to be a constant
900           // expression. We consider this to be a defect.
901           data().DefaultedDefaultConstructorIsConstexpr = false;
902       }
903     } else {
904       // Base element type of field is a non-class type.
905       if (!T->isLiteralType() ||
906           (!Field->hasInClassInitializer() && !isUnion()))
907         data().DefaultedDefaultConstructorIsConstexpr = false;
908     }
909
910     // C++0x [class]p7:
911     //   A standard-layout class is a class that:
912     //    [...]
913     //    -- either has no non-static data members in the most derived
914     //       class and at most one base class with non-static data members,
915     //       or has no base classes with non-static data members, and
916     // At this point we know that we have a non-static data member, so the last
917     // clause holds.
918     if (!data().HasNoNonEmptyBases)
919       data().IsStandardLayout = false;
920
921     // If this is not a zero-length bit-field, then the class is not empty.
922     if (data().Empty) {
923       if (!Field->isBitField() ||
924           (!Field->getBitWidth()->isTypeDependent() &&
925            !Field->getBitWidth()->isValueDependent() &&
926            Field->getBitWidthValue(Context) != 0))
927         data().Empty = false;
928     }
929   }
930   
931   // Handle using declarations of conversion functions.
932   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
933     if (Shadow->getDeclName().getNameKind()
934           == DeclarationName::CXXConversionFunctionName)
935       data().Conversions.addDecl(Shadow, Shadow->getAccess());
936 }
937
938 bool CXXRecordDecl::isCLike() const {
939   if (getTagKind() == TTK_Class || !TemplateOrInstantiation.isNull())
940     return false;
941   if (!hasDefinition())
942     return true;
943
944   return isPOD() && data().HasOnlyCMembers;
945 }
946
947 void CXXRecordDecl::getCaptureFields(
948        llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
949        FieldDecl *&ThisCapture) const {
950   Captures.clear();
951   ThisCapture = 0;
952
953   LambdaDefinitionData &Lambda = getLambdaData();
954   RecordDecl::field_iterator Field = field_begin();
955   for (LambdaExpr::Capture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
956        C != CEnd; ++C, ++Field) {
957     if (C->capturesThis()) {
958       ThisCapture = *Field;
959       continue;
960     }
961
962     Captures[C->getCapturedVar()] = *Field;
963   }
964 }
965
966
967 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
968   QualType T;
969   if (isa<UsingShadowDecl>(Conv))
970     Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
971   if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
972     T = ConvTemp->getTemplatedDecl()->getResultType();
973   else 
974     T = cast<CXXConversionDecl>(Conv)->getConversionType();
975   return Context.getCanonicalType(T);
976 }
977
978 /// Collect the visible conversions of a base class.
979 ///
980 /// \param Record a base class of the class we're considering
981 /// \param InVirtual whether this base class is a virtual base (or a base
982 ///   of a virtual base)
983 /// \param Access the access along the inheritance path to this base
984 /// \param ParentHiddenTypes the conversions provided by the inheritors
985 ///   of this base
986 /// \param Output the set to which to add conversions from non-virtual bases
987 /// \param VOutput the set to which to add conversions from virtual bases
988 /// \param HiddenVBaseCs the set of conversions which were hidden in a
989 ///   virtual base along some inheritance path
990 static void CollectVisibleConversions(ASTContext &Context,
991                                       CXXRecordDecl *Record,
992                                       bool InVirtual,
993                                       AccessSpecifier Access,
994                   const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
995                                       UnresolvedSetImpl &Output,
996                                       UnresolvedSetImpl &VOutput,
997                            llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
998   // The set of types which have conversions in this class or its
999   // subclasses.  As an optimization, we don't copy the derived set
1000   // unless it might change.
1001   const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1002   llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1003
1004   // Collect the direct conversions and figure out which conversions
1005   // will be hidden in the subclasses.
1006   UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
1007   if (!Cs.empty()) {
1008     HiddenTypesBuffer = ParentHiddenTypes;
1009     HiddenTypes = &HiddenTypesBuffer;
1010
1011     for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
1012       CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1013       bool Hidden = ParentHiddenTypes.count(ConvType);
1014       if (!Hidden)
1015         HiddenTypesBuffer.insert(ConvType);
1016
1017       // If this conversion is hidden and we're in a virtual base,
1018       // remember that it's hidden along some inheritance path.
1019       if (Hidden && InVirtual)
1020         HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1021
1022       // If this conversion isn't hidden, add it to the appropriate output.
1023       else if (!Hidden) {
1024         AccessSpecifier IAccess
1025           = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1026
1027         if (InVirtual)
1028           VOutput.addDecl(I.getDecl(), IAccess);
1029         else
1030           Output.addDecl(I.getDecl(), IAccess);
1031       }
1032     }
1033   }
1034
1035   // Collect information recursively from any base classes.
1036   for (CXXRecordDecl::base_class_iterator
1037          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1038     const RecordType *RT = I->getType()->getAs<RecordType>();
1039     if (!RT) continue;
1040
1041     AccessSpecifier BaseAccess
1042       = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
1043     bool BaseInVirtual = InVirtual || I->isVirtual();
1044
1045     CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1046     CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1047                               *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1048   }
1049 }
1050
1051 /// Collect the visible conversions of a class.
1052 ///
1053 /// This would be extremely straightforward if it weren't for virtual
1054 /// bases.  It might be worth special-casing that, really.
1055 static void CollectVisibleConversions(ASTContext &Context,
1056                                       CXXRecordDecl *Record,
1057                                       UnresolvedSetImpl &Output) {
1058   // The collection of all conversions in virtual bases that we've
1059   // found.  These will be added to the output as long as they don't
1060   // appear in the hidden-conversions set.
1061   UnresolvedSet<8> VBaseCs;
1062   
1063   // The set of conversions in virtual bases that we've determined to
1064   // be hidden.
1065   llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1066
1067   // The set of types hidden by classes derived from this one.
1068   llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1069
1070   // Go ahead and collect the direct conversions and add them to the
1071   // hidden-types set.
1072   UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
1073   Output.append(Cs.begin(), Cs.end());
1074   for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
1075     HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
1076
1077   // Recursively collect conversions from base classes.
1078   for (CXXRecordDecl::base_class_iterator
1079          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1080     const RecordType *RT = I->getType()->getAs<RecordType>();
1081     if (!RT) continue;
1082
1083     CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1084                               I->isVirtual(), I->getAccessSpecifier(),
1085                               HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1086   }
1087
1088   // Add any unhidden conversions provided by virtual bases.
1089   for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1090          I != E; ++I) {
1091     if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1092       Output.addDecl(I.getDecl(), I.getAccess());
1093   }
1094 }
1095
1096 /// getVisibleConversionFunctions - get all conversion functions visible
1097 /// in current class; including conversion function templates.
1098 const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
1099   // If root class, all conversions are visible.
1100   if (bases_begin() == bases_end())
1101     return &data().Conversions;
1102   // If visible conversion list is already evaluated, return it.
1103   if (data().ComputedVisibleConversions)
1104     return &data().VisibleConversions;
1105   CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
1106   data().ComputedVisibleConversions = true;
1107   return &data().VisibleConversions;
1108 }
1109
1110 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1111   // This operation is O(N) but extremely rare.  Sema only uses it to
1112   // remove UsingShadowDecls in a class that were followed by a direct
1113   // declaration, e.g.:
1114   //   class A : B {
1115   //     using B::operator int;
1116   //     operator int();
1117   //   };
1118   // This is uncommon by itself and even more uncommon in conjunction
1119   // with sufficiently large numbers of directly-declared conversions
1120   // that asymptotic behavior matters.
1121
1122   UnresolvedSetImpl &Convs = *getConversionFunctions();
1123   for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1124     if (Convs[I].getDecl() == ConvDecl) {
1125       Convs.erase(I);
1126       assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1127              && "conversion was found multiple times in unresolved set");
1128       return;
1129     }
1130   }
1131
1132   llvm_unreachable("conversion not found in set!");
1133 }
1134
1135 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1136   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1137     return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1138   
1139   return 0;
1140 }
1141
1142 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1143   return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1144 }
1145
1146 void 
1147 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1148                                              TemplateSpecializationKind TSK) {
1149   assert(TemplateOrInstantiation.isNull() && 
1150          "Previous template or instantiation?");
1151   assert(!isa<ClassTemplateSpecializationDecl>(this));
1152   TemplateOrInstantiation 
1153     = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1154 }
1155
1156 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1157   if (const ClassTemplateSpecializationDecl *Spec
1158         = dyn_cast<ClassTemplateSpecializationDecl>(this))
1159     return Spec->getSpecializationKind();
1160   
1161   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1162     return MSInfo->getTemplateSpecializationKind();
1163   
1164   return TSK_Undeclared;
1165 }
1166
1167 void 
1168 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1169   if (ClassTemplateSpecializationDecl *Spec
1170       = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1171     Spec->setSpecializationKind(TSK);
1172     return;
1173   }
1174   
1175   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1176     MSInfo->setTemplateSpecializationKind(TSK);
1177     return;
1178   }
1179   
1180   llvm_unreachable("Not a class template or member class specialization");
1181 }
1182
1183 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1184   ASTContext &Context = getASTContext();
1185   QualType ClassType = Context.getTypeDeclType(this);
1186
1187   DeclarationName Name
1188     = Context.DeclarationNames.getCXXDestructorName(
1189                                           Context.getCanonicalType(ClassType));
1190
1191   DeclContext::lookup_const_iterator I, E;
1192   llvm::tie(I, E) = lookup(Name);
1193   if (I == E)
1194     return 0;
1195
1196   CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
1197   return Dtor;
1198 }
1199
1200 void CXXRecordDecl::completeDefinition() {
1201   completeDefinition(0);
1202 }
1203
1204 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1205   RecordDecl::completeDefinition();
1206   
1207   if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) {
1208     // Objective-C Automatic Reference Counting:
1209     //   If a class has a non-static data member of Objective-C pointer
1210     //   type (or array thereof), it is a non-POD type and its
1211     //   default constructor (if any), copy constructor, move constructor,
1212     //   copy assignment operator, move assignment operator, and destructor are
1213     //   non-trivial.
1214     struct DefinitionData &Data = data();
1215     Data.PlainOldData = false;
1216     Data.HasTrivialDefaultConstructor = false;
1217     Data.HasTrivialCopyConstructor = false;
1218     Data.HasTrivialMoveConstructor = false;
1219     Data.HasTrivialCopyAssignment = false;
1220     Data.HasTrivialMoveAssignment = false;
1221     Data.HasTrivialDestructor = false;
1222     Data.HasIrrelevantDestructor = false;
1223   }
1224   
1225   // If the class may be abstract (but hasn't been marked as such), check for
1226   // any pure final overriders.
1227   if (mayBeAbstract()) {
1228     CXXFinalOverriderMap MyFinalOverriders;
1229     if (!FinalOverriders) {
1230       getFinalOverriders(MyFinalOverriders);
1231       FinalOverriders = &MyFinalOverriders;
1232     }
1233     
1234     bool Done = false;
1235     for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), 
1236                                      MEnd = FinalOverriders->end();
1237          M != MEnd && !Done; ++M) {
1238       for (OverridingMethods::iterator SO = M->second.begin(), 
1239                                     SOEnd = M->second.end();
1240            SO != SOEnd && !Done; ++SO) {
1241         assert(SO->second.size() > 0 && 
1242                "All virtual functions have overridding virtual functions");
1243         
1244         // C++ [class.abstract]p4:
1245         //   A class is abstract if it contains or inherits at least one
1246         //   pure virtual function for which the final overrider is pure
1247         //   virtual.
1248         if (SO->second.front().Method->isPure()) {
1249           data().Abstract = true;
1250           Done = true;
1251           break;
1252         }
1253       }
1254     }
1255   }
1256   
1257   // Set access bits correctly on the directly-declared conversions.
1258   for (UnresolvedSetIterator I = data().Conversions.begin(), 
1259                              E = data().Conversions.end(); 
1260        I != E; ++I)
1261     data().Conversions.setAccess(I, (*I)->getAccess());
1262 }
1263
1264 bool CXXRecordDecl::mayBeAbstract() const {
1265   if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1266       isDependentContext())
1267     return false;
1268   
1269   for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1270                                              BEnd = bases_end();
1271        B != BEnd; ++B) {
1272     CXXRecordDecl *BaseDecl 
1273       = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1274     if (BaseDecl->isAbstract())
1275       return true;
1276   }
1277   
1278   return false;
1279 }
1280
1281 void CXXMethodDecl::anchor() { }
1282
1283 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
1284                                  const CXXMethodDecl *BaseMD) {
1285   for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
1286          E = DerivedMD->end_overridden_methods(); I != E; ++I) {
1287     const CXXMethodDecl *MD = *I;
1288     if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
1289       return true;
1290     if (recursivelyOverrides(MD, BaseMD))
1291       return true;
1292   }
1293   return false;
1294 }
1295
1296 CXXMethodDecl *
1297 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
1298                                              bool MayBeBase) {
1299   if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
1300     return this;
1301
1302   // Lookup doesn't work for destructors, so handle them separately.
1303   if (isa<CXXDestructorDecl>(this)) {
1304     CXXMethodDecl *MD = RD->getDestructor();
1305     if (MD) {
1306       if (recursivelyOverrides(MD, this))
1307         return MD;
1308       if (MayBeBase && recursivelyOverrides(this, MD))
1309         return MD;
1310     }
1311     return NULL;
1312   }
1313
1314   lookup_const_result Candidates = RD->lookup(getDeclName());
1315   for (NamedDecl * const * I = Candidates.first; I != Candidates.second; ++I) {
1316     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I);
1317     if (!MD)
1318       continue;
1319     if (recursivelyOverrides(MD, this))
1320       return MD;
1321     if (MayBeBase && recursivelyOverrides(this, MD))
1322       return MD;
1323   }
1324
1325   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1326          E = RD->bases_end(); I != E; ++I) {
1327     const RecordType *RT = I->getType()->getAs<RecordType>();
1328     if (!RT)
1329       continue;
1330     const CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1331     CXXMethodDecl *T = this->getCorrespondingMethodInClass(Base);
1332     if (T)
1333       return T;
1334   }
1335
1336   return NULL;
1337 }
1338
1339 CXXMethodDecl *
1340 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1341                       SourceLocation StartLoc,
1342                       const DeclarationNameInfo &NameInfo,
1343                       QualType T, TypeSourceInfo *TInfo,
1344                       bool isStatic, StorageClass SCAsWritten, bool isInline,
1345                       bool isConstexpr, SourceLocation EndLocation) {
1346   return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1347                                isStatic, SCAsWritten, isInline, isConstexpr,
1348                                EndLocation);
1349 }
1350
1351 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1352   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
1353   return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(), 
1354                                  DeclarationNameInfo(), QualType(),
1355                                  0, false, SC_None, false, false,
1356                                  SourceLocation());
1357 }
1358
1359 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1360   if (getOverloadedOperator() != OO_Delete &&
1361       getOverloadedOperator() != OO_Array_Delete)
1362     return false;
1363
1364   // C++ [basic.stc.dynamic.deallocation]p2:
1365   //   A template instance is never a usual deallocation function,
1366   //   regardless of its signature.
1367   if (getPrimaryTemplate())
1368     return false;
1369
1370   // C++ [basic.stc.dynamic.deallocation]p2:
1371   //   If a class T has a member deallocation function named operator delete 
1372   //   with exactly one parameter, then that function is a usual (non-placement)
1373   //   deallocation function. [...]
1374   if (getNumParams() == 1)
1375     return true;
1376   
1377   // C++ [basic.stc.dynamic.deallocation]p2:
1378   //   [...] If class T does not declare such an operator delete but does 
1379   //   declare a member deallocation function named operator delete with 
1380   //   exactly two parameters, the second of which has type std::size_t (18.1),
1381   //   then this function is a usual deallocation function.
1382   ASTContext &Context = getASTContext();
1383   if (getNumParams() != 2 ||
1384       !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1385                                       Context.getSizeType()))
1386     return false;
1387                  
1388   // This function is a usual deallocation function if there are no 
1389   // single-parameter deallocation functions of the same kind.
1390   for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1391        R.first != R.second; ++R.first) {
1392     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
1393       if (FD->getNumParams() == 1)
1394         return false;
1395   }
1396   
1397   return true;
1398 }
1399
1400 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1401   // C++0x [class.copy]p17:
1402   //  A user-declared copy assignment operator X::operator= is a non-static 
1403   //  non-template member function of class X with exactly one parameter of 
1404   //  type X, X&, const X&, volatile X& or const volatile X&.
1405   if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1406       /*non-static*/ isStatic() || 
1407       /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate())
1408     return false;
1409       
1410   QualType ParamType = getParamDecl(0)->getType();
1411   if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1412     ParamType = Ref->getPointeeType();
1413   
1414   ASTContext &Context = getASTContext();
1415   QualType ClassType
1416     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1417   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1418 }
1419
1420 bool CXXMethodDecl::isMoveAssignmentOperator() const {
1421   // C++0x [class.copy]p19:
1422   //  A user-declared move assignment operator X::operator= is a non-static
1423   //  non-template member function of class X with exactly one parameter of type
1424   //  X&&, const X&&, volatile X&&, or const volatile X&&.
1425   if (getOverloadedOperator() != OO_Equal || isStatic() ||
1426       getPrimaryTemplate() || getDescribedFunctionTemplate())
1427     return false;
1428
1429   QualType ParamType = getParamDecl(0)->getType();
1430   if (!isa<RValueReferenceType>(ParamType))
1431     return false;
1432   ParamType = ParamType->getPointeeType();
1433
1434   ASTContext &Context = getASTContext();
1435   QualType ClassType
1436     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1437   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1438 }
1439
1440 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1441   assert(MD->isCanonicalDecl() && "Method is not canonical!");
1442   assert(!MD->getParent()->isDependentContext() &&
1443          "Can't add an overridden method to a class template!");
1444   assert(MD->isVirtual() && "Method is not virtual!");
1445
1446   getASTContext().addOverriddenMethod(this, MD);
1447 }
1448
1449 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1450   if (isa<CXXConstructorDecl>(this)) return 0;
1451   return getASTContext().overridden_methods_begin(this);
1452 }
1453
1454 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1455   if (isa<CXXConstructorDecl>(this)) return 0;
1456   return getASTContext().overridden_methods_end(this);
1457 }
1458
1459 unsigned CXXMethodDecl::size_overridden_methods() const {
1460   if (isa<CXXConstructorDecl>(this)) return 0;
1461   return getASTContext().overridden_methods_size(this);
1462 }
1463
1464 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1465   // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1466   // If the member function is declared const, the type of this is const X*,
1467   // if the member function is declared volatile, the type of this is
1468   // volatile X*, and if the member function is declared const volatile,
1469   // the type of this is const volatile X*.
1470
1471   assert(isInstance() && "No 'this' for static methods!");
1472
1473   QualType ClassTy = C.getTypeDeclType(getParent());
1474   ClassTy = C.getQualifiedType(ClassTy,
1475                                Qualifiers::fromCVRMask(getTypeQualifiers()));
1476   return C.getPointerType(ClassTy);
1477 }
1478
1479 bool CXXMethodDecl::hasInlineBody() const {
1480   // If this function is a template instantiation, look at the template from 
1481   // which it was instantiated.
1482   const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1483   if (!CheckFn)
1484     CheckFn = this;
1485   
1486   const FunctionDecl *fn;
1487   return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1488 }
1489
1490 bool CXXMethodDecl::isLambdaStaticInvoker() const {
1491   return getParent()->isLambda() && 
1492          getIdentifier() && getIdentifier()->getName() == "__invoke";
1493 }
1494
1495
1496 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1497                                        TypeSourceInfo *TInfo, bool IsVirtual,
1498                                        SourceLocation L, Expr *Init,
1499                                        SourceLocation R,
1500                                        SourceLocation EllipsisLoc)
1501   : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init), 
1502     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), 
1503     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1504 {
1505 }
1506
1507 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1508                                        FieldDecl *Member,
1509                                        SourceLocation MemberLoc,
1510                                        SourceLocation L, Expr *Init,
1511                                        SourceLocation R)
1512   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1513     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1514     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1515 {
1516 }
1517
1518 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1519                                        IndirectFieldDecl *Member,
1520                                        SourceLocation MemberLoc,
1521                                        SourceLocation L, Expr *Init,
1522                                        SourceLocation R)
1523   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1524     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1525     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1526 {
1527 }
1528
1529 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1530                                        TypeSourceInfo *TInfo,
1531                                        SourceLocation L, Expr *Init, 
1532                                        SourceLocation R)
1533   : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
1534     LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
1535     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1536 {
1537 }
1538
1539 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1540                                        FieldDecl *Member,
1541                                        SourceLocation MemberLoc,
1542                                        SourceLocation L, Expr *Init,
1543                                        SourceLocation R,
1544                                        VarDecl **Indices,
1545                                        unsigned NumIndices)
1546   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init), 
1547     LParenLoc(L), RParenLoc(R), IsVirtual(false),
1548     IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1549 {
1550   VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1551   memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1552 }
1553
1554 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1555                                                FieldDecl *Member, 
1556                                                SourceLocation MemberLoc,
1557                                                SourceLocation L, Expr *Init,
1558                                                SourceLocation R,
1559                                                VarDecl **Indices,
1560                                                unsigned NumIndices) {
1561   void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1562                                sizeof(VarDecl *) * NumIndices,
1563                                llvm::alignOf<CXXCtorInitializer>());
1564   return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1565                                       Indices, NumIndices);
1566 }
1567
1568 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1569   if (isBaseInitializer())
1570     return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1571   else
1572     return TypeLoc();
1573 }
1574
1575 const Type *CXXCtorInitializer::getBaseClass() const {
1576   if (isBaseInitializer())
1577     return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1578   else
1579     return 0;
1580 }
1581
1582 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1583   if (isAnyMemberInitializer())
1584     return getMemberLocation();
1585
1586   if (isInClassMemberInitializer())
1587     return getAnyMember()->getLocation();
1588   
1589   if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
1590     return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
1591   
1592   return SourceLocation();
1593 }
1594
1595 SourceRange CXXCtorInitializer::getSourceRange() const {
1596   if (isInClassMemberInitializer()) {
1597     FieldDecl *D = getAnyMember();
1598     if (Expr *I = D->getInClassInitializer())
1599       return I->getSourceRange();
1600     return SourceRange();
1601   }
1602
1603   return SourceRange(getSourceLocation(), getRParenLoc());
1604 }
1605
1606 void CXXConstructorDecl::anchor() { }
1607
1608 CXXConstructorDecl *
1609 CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1610   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl));
1611   return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameInfo(),
1612                                       QualType(), 0, false, false, false,false);
1613 }
1614
1615 CXXConstructorDecl *
1616 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1617                            SourceLocation StartLoc,
1618                            const DeclarationNameInfo &NameInfo,
1619                            QualType T, TypeSourceInfo *TInfo,
1620                            bool isExplicit, bool isInline,
1621                            bool isImplicitlyDeclared, bool isConstexpr) {
1622   assert(NameInfo.getName().getNameKind()
1623          == DeclarationName::CXXConstructorName &&
1624          "Name must refer to a constructor");
1625   return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1626                                     isExplicit, isInline, isImplicitlyDeclared,
1627                                     isConstexpr);
1628 }
1629
1630 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
1631   assert(isDelegatingConstructor() && "Not a delegating constructor!");
1632   Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
1633   if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E))
1634     return Construct->getConstructor();
1635   
1636   return 0;
1637 }
1638
1639 bool CXXConstructorDecl::isDefaultConstructor() const {
1640   // C++ [class.ctor]p5:
1641   //   A default constructor for a class X is a constructor of class
1642   //   X that can be called without an argument.
1643   return (getNumParams() == 0) ||
1644          (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1645 }
1646
1647 bool
1648 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1649   return isCopyOrMoveConstructor(TypeQuals) &&
1650          getParamDecl(0)->getType()->isLValueReferenceType();
1651 }
1652
1653 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1654   return isCopyOrMoveConstructor(TypeQuals) &&
1655     getParamDecl(0)->getType()->isRValueReferenceType();
1656 }
1657
1658 /// \brief Determine whether this is a copy or move constructor.
1659 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1660   // C++ [class.copy]p2:
1661   //   A non-template constructor for class X is a copy constructor
1662   //   if its first parameter is of type X&, const X&, volatile X& or
1663   //   const volatile X&, and either there are no other parameters
1664   //   or else all other parameters have default arguments (8.3.6).
1665   // C++0x [class.copy]p3:
1666   //   A non-template constructor for class X is a move constructor if its
1667   //   first parameter is of type X&&, const X&&, volatile X&&, or 
1668   //   const volatile X&&, and either there are no other parameters or else 
1669   //   all other parameters have default arguments.
1670   if ((getNumParams() < 1) ||
1671       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1672       (getPrimaryTemplate() != 0) ||
1673       (getDescribedFunctionTemplate() != 0))
1674     return false;
1675   
1676   const ParmVarDecl *Param = getParamDecl(0);
1677   
1678   // Do we have a reference type? 
1679   const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1680   if (!ParamRefType)
1681     return false;
1682   
1683   // Is it a reference to our class type?
1684   ASTContext &Context = getASTContext();
1685   
1686   CanQualType PointeeType
1687     = Context.getCanonicalType(ParamRefType->getPointeeType());
1688   CanQualType ClassTy 
1689     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1690   if (PointeeType.getUnqualifiedType() != ClassTy)
1691     return false;
1692   
1693   // FIXME: other qualifiers?
1694   
1695   // We have a copy or move constructor.
1696   TypeQuals = PointeeType.getCVRQualifiers();
1697   return true;  
1698 }
1699
1700 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1701   // C++ [class.conv.ctor]p1:
1702   //   A constructor declared without the function-specifier explicit
1703   //   that can be called with a single parameter specifies a
1704   //   conversion from the type of its first parameter to the type of
1705   //   its class. Such a constructor is called a converting
1706   //   constructor.
1707   if (isExplicit() && !AllowExplicit)
1708     return false;
1709
1710   return (getNumParams() == 0 &&
1711           getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1712          (getNumParams() == 1) ||
1713          (getNumParams() > 1 &&
1714           (getParamDecl(1)->hasDefaultArg() ||
1715            getParamDecl(1)->isParameterPack()));
1716 }
1717
1718 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1719   if ((getNumParams() < 1) ||
1720       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1721       (getPrimaryTemplate() == 0) ||
1722       (getDescribedFunctionTemplate() != 0))
1723     return false;
1724
1725   const ParmVarDecl *Param = getParamDecl(0);
1726
1727   ASTContext &Context = getASTContext();
1728   CanQualType ParamType = Context.getCanonicalType(Param->getType());
1729   
1730   // Is it the same as our our class type?
1731   CanQualType ClassTy 
1732     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1733   if (ParamType.getUnqualifiedType() != ClassTy)
1734     return false;
1735   
1736   return true;  
1737 }
1738
1739 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1740   // Hack: we store the inherited constructor in the overridden method table
1741   method_iterator It = getASTContext().overridden_methods_begin(this);
1742   if (It == getASTContext().overridden_methods_end(this))
1743     return 0;
1744
1745   return cast<CXXConstructorDecl>(*It);
1746 }
1747
1748 void
1749 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1750   // Hack: we store the inherited constructor in the overridden method table
1751   assert(getASTContext().overridden_methods_size(this) == 0 &&
1752          "Base ctor already set.");
1753   getASTContext().addOverriddenMethod(this, BaseCtor);
1754 }
1755
1756 void CXXDestructorDecl::anchor() { }
1757
1758 CXXDestructorDecl *
1759 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1760   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
1761   return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1762                                    QualType(), 0, false, false);
1763 }
1764
1765 CXXDestructorDecl *
1766 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1767                           SourceLocation StartLoc,
1768                           const DeclarationNameInfo &NameInfo,
1769                           QualType T, TypeSourceInfo *TInfo,
1770                           bool isInline, bool isImplicitlyDeclared) {
1771   assert(NameInfo.getName().getNameKind()
1772          == DeclarationName::CXXDestructorName &&
1773          "Name must refer to a destructor");
1774   return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1775                                    isImplicitlyDeclared);
1776 }
1777
1778 void CXXConversionDecl::anchor() { }
1779
1780 CXXConversionDecl *
1781 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1782   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
1783   return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1784                                      QualType(), 0, false, false, false,
1785                                      SourceLocation());
1786 }
1787
1788 CXXConversionDecl *
1789 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1790                           SourceLocation StartLoc,
1791                           const DeclarationNameInfo &NameInfo,
1792                           QualType T, TypeSourceInfo *TInfo,
1793                           bool isInline, bool isExplicit,
1794                           bool isConstexpr, SourceLocation EndLocation) {
1795   assert(NameInfo.getName().getNameKind()
1796          == DeclarationName::CXXConversionFunctionName &&
1797          "Name must refer to a conversion function");
1798   return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1799                                    isInline, isExplicit, isConstexpr,
1800                                    EndLocation);
1801 }
1802
1803 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
1804   return isImplicit() && getParent()->isLambda() &&
1805          getConversionType()->isBlockPointerType();
1806 }
1807
1808 void LinkageSpecDecl::anchor() { }
1809
1810 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1811                                          DeclContext *DC,
1812                                          SourceLocation ExternLoc,
1813                                          SourceLocation LangLoc,
1814                                          LanguageIDs Lang,
1815                                          SourceLocation RBraceLoc) {
1816   return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
1817 }
1818
1819 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1820   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
1821   return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
1822                                    lang_c, SourceLocation());
1823 }
1824
1825 void UsingDirectiveDecl::anchor() { }
1826
1827 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1828                                                SourceLocation L,
1829                                                SourceLocation NamespaceLoc,
1830                                            NestedNameSpecifierLoc QualifierLoc,
1831                                                SourceLocation IdentLoc,
1832                                                NamedDecl *Used,
1833                                                DeclContext *CommonAncestor) {
1834   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1835     Used = NS->getOriginalNamespace();
1836   return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1837                                     IdentLoc, Used, CommonAncestor);
1838 }
1839
1840 UsingDirectiveDecl *
1841 UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1842   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl));
1843   return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(),
1844                                       NestedNameSpecifierLoc(),
1845                                       SourceLocation(), 0, 0);
1846 }
1847
1848 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1849   if (NamespaceAliasDecl *NA =
1850         dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1851     return NA->getNamespace();
1852   return cast_or_null<NamespaceDecl>(NominatedNamespace);
1853 }
1854
1855 void NamespaceDecl::anchor() { }
1856
1857 NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline, 
1858                              SourceLocation StartLoc,
1859                              SourceLocation IdLoc, IdentifierInfo *Id,
1860                              NamespaceDecl *PrevDecl)
1861   : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
1862     LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inline) 
1863 {
1864   setPreviousDeclaration(PrevDecl);
1865   
1866   if (PrevDecl)
1867     AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
1868 }
1869
1870 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1871                                      bool Inline, SourceLocation StartLoc,
1872                                      SourceLocation IdLoc, IdentifierInfo *Id,
1873                                      NamespaceDecl *PrevDecl) {
1874   return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
1875 }
1876
1877 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1878   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
1879   return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocation(), 
1880                                  0, 0);
1881 }
1882
1883 void NamespaceAliasDecl::anchor() { }
1884
1885 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1886                                                SourceLocation UsingLoc,
1887                                                SourceLocation AliasLoc,
1888                                                IdentifierInfo *Alias,
1889                                            NestedNameSpecifierLoc QualifierLoc,
1890                                                SourceLocation IdentLoc,
1891                                                NamedDecl *Namespace) {
1892   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1893     Namespace = NS->getOriginalNamespace();
1894   return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias, 
1895                                     QualifierLoc, IdentLoc, Namespace);
1896 }
1897
1898 NamespaceAliasDecl *
1899 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1900   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl));
1901   return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(), 0,
1902                                       NestedNameSpecifierLoc(), 
1903                                       SourceLocation(), 0);
1904 }
1905
1906 void UsingShadowDecl::anchor() { }
1907
1908 UsingShadowDecl *
1909 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1910   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
1911   return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
1912 }
1913
1914 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1915   const UsingShadowDecl *Shadow = this;
1916   while (const UsingShadowDecl *NextShadow =
1917          dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1918     Shadow = NextShadow;
1919   return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1920 }
1921
1922 void UsingDecl::anchor() { }
1923
1924 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1925   assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1926          "declaration already in set");
1927   assert(S->getUsingDecl() == this);
1928
1929   if (FirstUsingShadow.getPointer())
1930     S->UsingOrNextShadow = FirstUsingShadow.getPointer();
1931   FirstUsingShadow.setPointer(S);
1932 }
1933
1934 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1935   assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1936          "declaration not in set");
1937   assert(S->getUsingDecl() == this);
1938
1939   // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1940
1941   if (FirstUsingShadow.getPointer() == S) {
1942     FirstUsingShadow.setPointer(
1943       dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
1944     S->UsingOrNextShadow = this;
1945     return;
1946   }
1947
1948   UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
1949   while (Prev->UsingOrNextShadow != S)
1950     Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1951   Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1952   S->UsingOrNextShadow = this;
1953 }
1954
1955 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1956                              NestedNameSpecifierLoc QualifierLoc,
1957                              const DeclarationNameInfo &NameInfo,
1958                              bool IsTypeNameArg) {
1959   return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1960 }
1961
1962 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1963   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
1964   return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
1965                              DeclarationNameInfo(), false);
1966 }
1967
1968 void UnresolvedUsingValueDecl::anchor() { }
1969
1970 UnresolvedUsingValueDecl *
1971 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1972                                  SourceLocation UsingLoc,
1973                                  NestedNameSpecifierLoc QualifierLoc,
1974                                  const DeclarationNameInfo &NameInfo) {
1975   return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1976                                           QualifierLoc, NameInfo);
1977 }
1978
1979 UnresolvedUsingValueDecl *
1980 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1981   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValueDecl));
1982   return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(),
1983                                             NestedNameSpecifierLoc(),
1984                                             DeclarationNameInfo());
1985 }
1986
1987 void UnresolvedUsingTypenameDecl::anchor() { }
1988
1989 UnresolvedUsingTypenameDecl *
1990 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1991                                     SourceLocation UsingLoc,
1992                                     SourceLocation TypenameLoc,
1993                                     NestedNameSpecifierLoc QualifierLoc,
1994                                     SourceLocation TargetNameLoc,
1995                                     DeclarationName TargetName) {
1996   return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1997                                              QualifierLoc, TargetNameLoc,
1998                                              TargetName.getAsIdentifierInfo());
1999 }
2000
2001 UnresolvedUsingTypenameDecl *
2002 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2003   void *Mem = AllocateDeserializedDecl(C, ID, 
2004                                        sizeof(UnresolvedUsingTypenameDecl));
2005   return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
2006                                                SourceLocation(),
2007                                                NestedNameSpecifierLoc(),
2008                                                SourceLocation(),
2009                                                0);
2010 }
2011
2012 void StaticAssertDecl::anchor() { }
2013
2014 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
2015                                            SourceLocation StaticAssertLoc,
2016                                            Expr *AssertExpr,
2017                                            StringLiteral *Message,
2018                                            SourceLocation RParenLoc,
2019                                            bool Failed) {
2020   return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
2021                                   RParenLoc, Failed);
2022 }
2023
2024 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, 
2025                                                        unsigned ID) {
2026   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
2027   return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,
2028                                     SourceLocation(), false);
2029 }
2030
2031 static const char *getAccessName(AccessSpecifier AS) {
2032   switch (AS) {
2033     case AS_none:
2034       llvm_unreachable("Invalid access specifier!");
2035     case AS_public:
2036       return "public";
2037     case AS_private:
2038       return "private";
2039     case AS_protected:
2040       return "protected";
2041   }
2042   llvm_unreachable("Invalid access specifier!");
2043 }
2044
2045 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2046                                            AccessSpecifier AS) {
2047   return DB << getAccessName(AS);
2048 }
2049
2050 const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
2051                                            AccessSpecifier AS) {
2052   return DB << getAccessName(AS);
2053 }