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