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