]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / AST / DeclCXX.h
1 //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
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 /// \file
11 /// Defines the C++ Decl subclasses, other than those for templates
12 /// (found in DeclTemplate.h) and friends (in DeclFriend.h).
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CLANG_AST_DECLCXX_H
17 #define LLVM_CLANG_AST_DECLCXX_H
18
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/LambdaCapture.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/Redeclarable.h"
30 #include "clang/AST/Stmt.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/UnresolvedSet.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/Lambda.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/SourceLocation.h"
39 #include "clang/Basic/Specifiers.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/PointerIntPair.h"
43 #include "llvm/ADT/PointerUnion.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/PointerLikeTypeTraits.h"
49 #include "llvm/Support/TrailingObjects.h"
50 #include <cassert>
51 #include <cstddef>
52 #include <iterator>
53 #include <memory>
54 #include <vector>
55
56 namespace clang {
57
58 class ClassTemplateDecl;
59 class ConstructorUsingShadowDecl;
60 class CXXBasePath;
61 class CXXBasePaths;
62 class CXXConstructorDecl;
63 class CXXDestructorDecl;
64 class CXXFinalOverriderMap;
65 class CXXIndirectPrimaryBaseSet;
66 class CXXMethodDecl;
67 class DiagnosticBuilder;
68 class FriendDecl;
69 class FunctionTemplateDecl;
70 class IdentifierInfo;
71 class MemberSpecializationInfo;
72 class TemplateDecl;
73 class TemplateParameterList;
74 class UsingDecl;
75
76 /// Represents any kind of function declaration, whether it is a
77 /// concrete function or a function template.
78 class AnyFunctionDecl {
79   NamedDecl *Function;
80
81   AnyFunctionDecl(NamedDecl *ND) : Function(ND) {}
82
83 public:
84   AnyFunctionDecl(FunctionDecl *FD) : Function(FD) {}
85   AnyFunctionDecl(FunctionTemplateDecl *FTD);
86
87   /// Implicily converts any function or function template into a
88   /// named declaration.
89   operator NamedDecl *() const { return Function; }
90
91   /// Retrieve the underlying function or function template.
92   NamedDecl *get() const { return Function; }
93
94   static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) {
95     return AnyFunctionDecl(ND);
96   }
97 };
98
99 } // namespace clang
100
101 namespace llvm {
102
103   // Provide PointerLikeTypeTraits for non-cvr pointers.
104   template<>
105   struct PointerLikeTypeTraits< ::clang::AnyFunctionDecl> {
106     static void *getAsVoidPointer(::clang::AnyFunctionDecl F) {
107       return F.get();
108     }
109
110     static ::clang::AnyFunctionDecl getFromVoidPointer(void *P) {
111       return ::clang::AnyFunctionDecl::getFromNamedDecl(
112                                       static_cast< ::clang::NamedDecl*>(P));
113     }
114
115     enum { NumLowBitsAvailable = 2 };
116   };
117
118 } // namespace llvm
119
120 namespace clang {
121
122 /// Represents an access specifier followed by colon ':'.
123 ///
124 /// An objects of this class represents sugar for the syntactic occurrence
125 /// of an access specifier followed by a colon in the list of member
126 /// specifiers of a C++ class definition.
127 ///
128 /// Note that they do not represent other uses of access specifiers,
129 /// such as those occurring in a list of base specifiers.
130 /// Also note that this class has nothing to do with so-called
131 /// "access declarations" (C++98 11.3 [class.access.dcl]).
132 class AccessSpecDecl : public Decl {
133   /// The location of the ':'.
134   SourceLocation ColonLoc;
135
136   AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
137                  SourceLocation ASLoc, SourceLocation ColonLoc)
138     : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
139     setAccess(AS);
140   }
141
142   AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
143
144   virtual void anchor();
145
146 public:
147   /// The location of the access specifier.
148   SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
149
150   /// Sets the location of the access specifier.
151   void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
152
153   /// The location of the colon following the access specifier.
154   SourceLocation getColonLoc() const { return ColonLoc; }
155
156   /// Sets the location of the colon.
157   void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
158
159   SourceRange getSourceRange() const override LLVM_READONLY {
160     return SourceRange(getAccessSpecifierLoc(), getColonLoc());
161   }
162
163   static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
164                                 DeclContext *DC, SourceLocation ASLoc,
165                                 SourceLocation ColonLoc) {
166     return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
167   }
168
169   static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
170
171   // Implement isa/cast/dyncast/etc.
172   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
173   static bool classofKind(Kind K) { return K == AccessSpec; }
174 };
175
176 /// Represents a base class of a C++ class.
177 ///
178 /// Each CXXBaseSpecifier represents a single, direct base class (or
179 /// struct) of a C++ class (or struct). It specifies the type of that
180 /// base class, whether it is a virtual or non-virtual base, and what
181 /// level of access (public, protected, private) is used for the
182 /// derivation. For example:
183 ///
184 /// \code
185 ///   class A { };
186 ///   class B { };
187 ///   class C : public virtual A, protected B { };
188 /// \endcode
189 ///
190 /// In this code, C will have two CXXBaseSpecifiers, one for "public
191 /// virtual A" and the other for "protected B".
192 class CXXBaseSpecifier {
193   /// The source code range that covers the full base
194   /// specifier, including the "virtual" (if present) and access
195   /// specifier (if present).
196   SourceRange Range;
197
198   /// The source location of the ellipsis, if this is a pack
199   /// expansion.
200   SourceLocation EllipsisLoc;
201
202   /// Whether this is a virtual base class or not.
203   unsigned Virtual : 1;
204
205   /// Whether this is the base of a class (true) or of a struct (false).
206   ///
207   /// This determines the mapping from the access specifier as written in the
208   /// source code to the access specifier used for semantic analysis.
209   unsigned BaseOfClass : 1;
210
211   /// Access specifier as written in the source code (may be AS_none).
212   ///
213   /// The actual type of data stored here is an AccessSpecifier, but we use
214   /// "unsigned" here to work around a VC++ bug.
215   unsigned Access : 2;
216
217   /// Whether the class contains a using declaration
218   /// to inherit the named class's constructors.
219   unsigned InheritConstructors : 1;
220
221   /// The type of the base class.
222   ///
223   /// This will be a class or struct (or a typedef of such). The source code
224   /// range does not include the \c virtual or the access specifier.
225   TypeSourceInfo *BaseTypeInfo;
226
227 public:
228   CXXBaseSpecifier() = default;
229   CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
230                    TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
231     : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
232       Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
233
234   /// Retrieves the source range that contains the entire base specifier.
235   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
236   SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
237   SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
238   SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
239   SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
240
241   /// Get the location at which the base class type was written.
242   SourceLocation getBaseTypeLoc() const LLVM_READONLY {
243     return BaseTypeInfo->getTypeLoc().getLocStart();
244   }
245
246   /// Determines whether the base class is a virtual base class (or not).
247   bool isVirtual() const { return Virtual; }
248
249   /// Determine whether this base class is a base of a class declared
250   /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
251   bool isBaseOfClass() const { return BaseOfClass; }
252
253   /// Determine whether this base specifier is a pack expansion.
254   bool isPackExpansion() const { return EllipsisLoc.isValid(); }
255
256   /// Determine whether this base class's constructors get inherited.
257   bool getInheritConstructors() const { return InheritConstructors; }
258
259   /// Set that this base class's constructors should be inherited.
260   void setInheritConstructors(bool Inherit = true) {
261     InheritConstructors = Inherit;
262   }
263
264   /// For a pack expansion, determine the location of the ellipsis.
265   SourceLocation getEllipsisLoc() const {
266     return EllipsisLoc;
267   }
268
269   /// Returns the access specifier for this base specifier.
270   ///
271   /// This is the actual base specifier as used for semantic analysis, so
272   /// the result can never be AS_none. To retrieve the access specifier as
273   /// written in the source code, use getAccessSpecifierAsWritten().
274   AccessSpecifier getAccessSpecifier() const {
275     if ((AccessSpecifier)Access == AS_none)
276       return BaseOfClass? AS_private : AS_public;
277     else
278       return (AccessSpecifier)Access;
279   }
280
281   /// Retrieves the access specifier as written in the source code
282   /// (which may mean that no access specifier was explicitly written).
283   ///
284   /// Use getAccessSpecifier() to retrieve the access specifier for use in
285   /// semantic analysis.
286   AccessSpecifier getAccessSpecifierAsWritten() const {
287     return (AccessSpecifier)Access;
288   }
289
290   /// Retrieves the type of the base class.
291   ///
292   /// This type will always be an unqualified class type.
293   QualType getType() const {
294     return BaseTypeInfo->getType().getUnqualifiedType();
295   }
296
297   /// Retrieves the type and source location of the base class.
298   TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
299 };
300
301 /// Represents a C++ struct/union/class.
302 class CXXRecordDecl : public RecordDecl {
303   friend class ASTDeclReader;
304   friend class ASTDeclWriter;
305   friend class ASTNodeImporter;
306   friend class ASTReader;
307   friend class ASTRecordWriter;
308   friend class ASTWriter;
309   friend class DeclContext;
310   friend class LambdaExpr;
311
312   friend void FunctionDecl::setPure(bool);
313   friend void TagDecl::startDefinition();
314
315   /// Values used in DefinitionData fields to represent special members.
316   enum SpecialMemberFlags {
317     SMF_DefaultConstructor = 0x1,
318     SMF_CopyConstructor = 0x2,
319     SMF_MoveConstructor = 0x4,
320     SMF_CopyAssignment = 0x8,
321     SMF_MoveAssignment = 0x10,
322     SMF_Destructor = 0x20,
323     SMF_All = 0x3f
324   };
325
326   struct DefinitionData {
327     /// True if this class has any user-declared constructors.
328     unsigned UserDeclaredConstructor : 1;
329
330     /// The user-declared special members which this class has.
331     unsigned UserDeclaredSpecialMembers : 6;
332
333     /// True when this class is an aggregate.
334     unsigned Aggregate : 1;
335
336     /// True when this class is a POD-type.
337     unsigned PlainOldData : 1;
338
339     /// true when this class is empty for traits purposes,
340     /// i.e. has no data members other than 0-width bit-fields, has no
341     /// virtual function/base, and doesn't inherit from a non-empty
342     /// class. Doesn't take union-ness into account.
343     unsigned Empty : 1;
344
345     /// True when this class is polymorphic, i.e., has at
346     /// least one virtual member or derives from a polymorphic class.
347     unsigned Polymorphic : 1;
348
349     /// True when this class is abstract, i.e., has at least
350     /// one pure virtual function, (that can come from a base class).
351     unsigned Abstract : 1;
352
353     /// True when this class is standard-layout, per the applicable
354     /// language rules (including DRs).
355     unsigned IsStandardLayout : 1;
356
357     /// True when this class was standard-layout under the C++11
358     /// definition.
359     ///
360     /// C++11 [class]p7.  A standard-layout class is a class that:
361     /// * has no non-static data members of type non-standard-layout class (or
362     ///   array of such types) or reference,
363     /// * has no virtual functions (10.3) and no virtual base classes (10.1),
364     /// * has the same access control (Clause 11) for all non-static data
365     ///   members
366     /// * has no non-standard-layout base classes,
367     /// * either has no non-static data members in the most derived class and at
368     ///   most one base class with non-static data members, or has no base
369     ///   classes with non-static data members, and
370     /// * has no base classes of the same type as the first non-static data
371     ///   member.
372     unsigned IsCXX11StandardLayout : 1;
373
374     /// True when any base class has any declared non-static data
375     /// members or bit-fields.
376     /// This is a helper bit of state used to implement IsStandardLayout more
377     /// efficiently.
378     unsigned HasBasesWithFields : 1;
379
380     /// True when any base class has any declared non-static data
381     /// members.
382     /// This is a helper bit of state used to implement IsCXX11StandardLayout
383     /// more efficiently.
384     unsigned HasBasesWithNonStaticDataMembers : 1;
385
386     /// True when there are private non-static data members.
387     unsigned HasPrivateFields : 1;
388
389     /// True when there are protected non-static data members.
390     unsigned HasProtectedFields : 1;
391
392     /// True when there are private non-static data members.
393     unsigned HasPublicFields : 1;
394
395     /// True if this class (or any subobject) has mutable fields.
396     unsigned HasMutableFields : 1;
397
398     /// True if this class (or any nested anonymous struct or union)
399     /// has variant members.
400     unsigned HasVariantMembers : 1;
401
402     /// True if there no non-field members declared by the user.
403     unsigned HasOnlyCMembers : 1;
404
405     /// True if any field has an in-class initializer, including those
406     /// within anonymous unions or structs.
407     unsigned HasInClassInitializer : 1;
408
409     /// True if any field is of reference type, and does not have an
410     /// in-class initializer.
411     ///
412     /// In this case, value-initialization of this class is illegal in C++98
413     /// even if the class has a trivial default constructor.
414     unsigned HasUninitializedReferenceMember : 1;
415
416     /// True if any non-mutable field whose type doesn't have a user-
417     /// provided default ctor also doesn't have an in-class initializer.
418     unsigned HasUninitializedFields : 1;
419
420     /// True if there are any member using-declarations that inherit
421     /// constructors from a base class.
422     unsigned HasInheritedConstructor : 1;
423
424     /// True if there are any member using-declarations named
425     /// 'operator='.
426     unsigned HasInheritedAssignment : 1;
427
428     /// These flags are \c true if a defaulted corresponding special
429     /// member can't be fully analyzed without performing overload resolution.
430     /// @{
431     unsigned NeedOverloadResolutionForCopyConstructor : 1;
432     unsigned NeedOverloadResolutionForMoveConstructor : 1;
433     unsigned NeedOverloadResolutionForMoveAssignment : 1;
434     unsigned NeedOverloadResolutionForDestructor : 1;
435     /// @}
436
437     /// These flags are \c true if an implicit defaulted corresponding
438     /// special member would be defined as deleted.
439     /// @{
440     unsigned DefaultedCopyConstructorIsDeleted : 1;
441     unsigned DefaultedMoveConstructorIsDeleted : 1;
442     unsigned DefaultedMoveAssignmentIsDeleted : 1;
443     unsigned DefaultedDestructorIsDeleted : 1;
444     /// @}
445
446     /// The trivial special members which this class has, per
447     /// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25,
448     /// C++11 [class.dtor]p5, or would have if the member were not suppressed.
449     ///
450     /// This excludes any user-declared but not user-provided special members
451     /// which have been declared but not yet defined.
452     unsigned HasTrivialSpecialMembers : 6;
453
454     /// These bits keep track of the triviality of special functions for the
455     /// purpose of calls. Only the bits corresponding to SMF_CopyConstructor,
456     /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
457     unsigned HasTrivialSpecialMembersForCall : 6;
458
459     /// The declared special members of this class which are known to be
460     /// non-trivial.
461     ///
462     /// This excludes any user-declared but not user-provided special members
463     /// which have been declared but not yet defined, and any implicit special
464     /// members which have not yet been declared.
465     unsigned DeclaredNonTrivialSpecialMembers : 6;
466
467     /// These bits keep track of the declared special members that are
468     /// non-trivial for the purpose of calls.
469     /// Only the bits corresponding to SMF_CopyConstructor,
470     /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
471     unsigned DeclaredNonTrivialSpecialMembersForCall : 6;
472
473     /// True when this class has a destructor with no semantic effect.
474     unsigned HasIrrelevantDestructor : 1;
475
476     /// True when this class has at least one user-declared constexpr
477     /// constructor which is neither the copy nor move constructor.
478     unsigned HasConstexprNonCopyMoveConstructor : 1;
479
480     /// True if this class has a (possibly implicit) defaulted default
481     /// constructor.
482     unsigned HasDefaultedDefaultConstructor : 1;
483
484     /// True if a defaulted default constructor for this class would
485     /// be constexpr.
486     unsigned DefaultedDefaultConstructorIsConstexpr : 1;
487
488     /// True if this class has a constexpr default constructor.
489     ///
490     /// This is true for either a user-declared constexpr default constructor
491     /// or an implicitly declared constexpr default constructor.
492     unsigned HasConstexprDefaultConstructor : 1;
493
494     /// True when this class contains at least one non-static data
495     /// member or base class of non-literal or volatile type.
496     unsigned HasNonLiteralTypeFieldsOrBases : 1;
497
498     /// True when visible conversion functions are already computed
499     /// and are available.
500     unsigned ComputedVisibleConversions : 1;
501
502     /// Whether we have a C++11 user-provided default constructor (not
503     /// explicitly deleted or defaulted).
504     unsigned UserProvidedDefaultConstructor : 1;
505
506     /// The special members which have been declared for this class,
507     /// either by the user or implicitly.
508     unsigned DeclaredSpecialMembers : 6;
509
510     /// Whether an implicit copy constructor could have a const-qualified
511     /// parameter, for initializing virtual bases and for other subobjects.
512     unsigned ImplicitCopyConstructorCanHaveConstParamForVBase : 1;
513     unsigned ImplicitCopyConstructorCanHaveConstParamForNonVBase : 1;
514
515     /// Whether an implicit copy assignment operator would have a
516     /// const-qualified parameter.
517     unsigned ImplicitCopyAssignmentHasConstParam : 1;
518
519     /// Whether any declared copy constructor has a const-qualified
520     /// parameter.
521     unsigned HasDeclaredCopyConstructorWithConstParam : 1;
522
523     /// Whether any declared copy assignment operator has either a
524     /// const-qualified reference parameter or a non-reference parameter.
525     unsigned HasDeclaredCopyAssignmentWithConstParam : 1;
526
527     /// Whether this class describes a C++ lambda.
528     unsigned IsLambda : 1;
529
530     /// Whether we are currently parsing base specifiers.
531     unsigned IsParsingBaseSpecifiers : 1;
532
533     unsigned HasODRHash : 1;
534
535     /// A hash of parts of the class to help in ODR checking.
536     unsigned ODRHash = 0;
537
538     /// The number of base class specifiers in Bases.
539     unsigned NumBases = 0;
540
541     /// The number of virtual base class specifiers in VBases.
542     unsigned NumVBases = 0;
543
544     /// Base classes of this class.
545     ///
546     /// FIXME: This is wasted space for a union.
547     LazyCXXBaseSpecifiersPtr Bases;
548
549     /// direct and indirect virtual base classes of this class.
550     LazyCXXBaseSpecifiersPtr VBases;
551
552     /// The conversion functions of this C++ class (but not its
553     /// inherited conversion functions).
554     ///
555     /// Each of the entries in this overload set is a CXXConversionDecl.
556     LazyASTUnresolvedSet Conversions;
557
558     /// The conversion functions of this C++ class and all those
559     /// inherited conversion functions that are visible in this class.
560     ///
561     /// Each of the entries in this overload set is a CXXConversionDecl or a
562     /// FunctionTemplateDecl.
563     LazyASTUnresolvedSet VisibleConversions;
564
565     /// The declaration which defines this record.
566     CXXRecordDecl *Definition;
567
568     /// The first friend declaration in this class, or null if there
569     /// aren't any.
570     ///
571     /// This is actually currently stored in reverse order.
572     LazyDeclPtr FirstFriend;
573
574     DefinitionData(CXXRecordDecl *D);
575
576     /// Retrieve the set of direct base classes.
577     CXXBaseSpecifier *getBases() const {
578       if (!Bases.isOffset())
579         return Bases.get(nullptr);
580       return getBasesSlowCase();
581     }
582
583     /// Retrieve the set of virtual base classes.
584     CXXBaseSpecifier *getVBases() const {
585       if (!VBases.isOffset())
586         return VBases.get(nullptr);
587       return getVBasesSlowCase();
588     }
589
590     ArrayRef<CXXBaseSpecifier> bases() const {
591       return llvm::makeArrayRef(getBases(), NumBases);
592     }
593
594     ArrayRef<CXXBaseSpecifier> vbases() const {
595       return llvm::makeArrayRef(getVBases(), NumVBases);
596     }
597
598   private:
599     CXXBaseSpecifier *getBasesSlowCase() const;
600     CXXBaseSpecifier *getVBasesSlowCase() const;
601   };
602
603   struct DefinitionData *DefinitionData;
604
605   /// Describes a C++ closure type (generated by a lambda expression).
606   struct LambdaDefinitionData : public DefinitionData {
607     using Capture = LambdaCapture;
608
609     /// Whether this lambda is known to be dependent, even if its
610     /// context isn't dependent.
611     ///
612     /// A lambda with a non-dependent context can be dependent if it occurs
613     /// within the default argument of a function template, because the
614     /// lambda will have been created with the enclosing context as its
615     /// declaration context, rather than function. This is an unfortunate
616     /// artifact of having to parse the default arguments before.
617     unsigned Dependent : 1;
618
619     /// Whether this lambda is a generic lambda.
620     unsigned IsGenericLambda : 1;
621
622     /// The Default Capture.
623     unsigned CaptureDefault : 2;
624
625     /// The number of captures in this lambda is limited 2^NumCaptures.
626     unsigned NumCaptures : 15;
627
628     /// The number of explicit captures in this lambda.
629     unsigned NumExplicitCaptures : 13;
630
631     /// The number used to indicate this lambda expression for name
632     /// mangling in the Itanium C++ ABI.
633     unsigned ManglingNumber = 0;
634
635     /// The declaration that provides context for this lambda, if the
636     /// actual DeclContext does not suffice. This is used for lambdas that
637     /// occur within default arguments of function parameters within the class
638     /// or within a data member initializer.
639     LazyDeclPtr ContextDecl;
640
641     /// The list of captures, both explicit and implicit, for this
642     /// lambda.
643     Capture *Captures = nullptr;
644
645     /// The type of the call method.
646     TypeSourceInfo *MethodTyInfo;
647
648     LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info,
649                          bool Dependent, bool IsGeneric,
650                          LambdaCaptureDefault CaptureDefault)
651       : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
652         CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0),
653         MethodTyInfo(Info) {
654       IsLambda = true;
655
656       // C++1z [expr.prim.lambda]p4:
657       //   This class type is not an aggregate type.
658       Aggregate = false;
659       PlainOldData = false;
660     }
661   };
662
663   struct DefinitionData *dataPtr() const {
664     // Complete the redecl chain (if necessary).
665     getMostRecentDecl();
666     return DefinitionData;
667   }
668
669   struct DefinitionData &data() const {
670     auto *DD = dataPtr();
671     assert(DD && "queried property of class with no definition");
672     return *DD;
673   }
674
675   struct LambdaDefinitionData &getLambdaData() const {
676     // No update required: a merged definition cannot change any lambda
677     // properties.
678     auto *DD = DefinitionData;
679     assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
680     return static_cast<LambdaDefinitionData&>(*DD);
681   }
682
683   /// The template or declaration that this declaration
684   /// describes or was instantiated from, respectively.
685   ///
686   /// For non-templates, this value will be null. For record
687   /// declarations that describe a class template, this will be a
688   /// pointer to a ClassTemplateDecl. For member
689   /// classes of class template specializations, this will be the
690   /// MemberSpecializationInfo referring to the member class that was
691   /// instantiated or specialized.
692   llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
693       TemplateOrInstantiation;
694
695   /// Called from setBases and addedMember to notify the class that a
696   /// direct or virtual base class or a member of class type has been added.
697   void addedClassSubobject(CXXRecordDecl *Base);
698
699   /// Notify the class that member has been added.
700   ///
701   /// This routine helps maintain information about the class based on which
702   /// members have been added. It will be invoked by DeclContext::addDecl()
703   /// whenever a member is added to this record.
704   void addedMember(Decl *D);
705
706   void markedVirtualFunctionPure();
707
708   /// Get the head of our list of friend declarations, possibly
709   /// deserializing the friends from an external AST source.
710   FriendDecl *getFirstFriend() const;
711
712   /// Determine whether this class has an empty base class subobject of type X
713   /// or of one of the types that might be at offset 0 within X (per the C++
714   /// "standard layout" rules).
715   bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
716                                                const CXXRecordDecl *X);
717
718 protected:
719   CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
720                 SourceLocation StartLoc, SourceLocation IdLoc,
721                 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
722
723 public:
724   /// Iterator that traverses the base classes of a class.
725   using base_class_iterator = CXXBaseSpecifier *;
726
727   /// Iterator that traverses the base classes of a class.
728   using base_class_const_iterator = const CXXBaseSpecifier *;
729
730   CXXRecordDecl *getCanonicalDecl() override {
731     return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
732   }
733
734   const CXXRecordDecl *getCanonicalDecl() const {
735     return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
736   }
737
738   CXXRecordDecl *getPreviousDecl() {
739     return cast_or_null<CXXRecordDecl>(
740             static_cast<RecordDecl *>(this)->getPreviousDecl());
741   }
742
743   const CXXRecordDecl *getPreviousDecl() const {
744     return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
745   }
746
747   CXXRecordDecl *getMostRecentDecl() {
748     return cast<CXXRecordDecl>(
749             static_cast<RecordDecl *>(this)->getMostRecentDecl());
750   }
751
752   const CXXRecordDecl *getMostRecentDecl() const {
753     return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
754   }
755
756   CXXRecordDecl *getMostRecentNonInjectedDecl() {
757     CXXRecordDecl *Recent =
758         static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
759     while (Recent->isInjectedClassName()) {
760       // FIXME: Does injected class name need to be in the redeclarations chain?
761       assert(Recent->getPreviousDecl());
762       Recent = Recent->getPreviousDecl();
763     }
764     return Recent;
765   }
766
767   const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
768     return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
769   }
770
771   CXXRecordDecl *getDefinition() const {
772     // We only need an update if we don't already know which
773     // declaration is the definition.
774     auto *DD = DefinitionData ? DefinitionData : dataPtr();
775     return DD ? DD->Definition : nullptr;
776   }
777
778   bool hasDefinition() const { return DefinitionData || dataPtr(); }
779
780   static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
781                                SourceLocation StartLoc, SourceLocation IdLoc,
782                                IdentifierInfo *Id,
783                                CXXRecordDecl *PrevDecl = nullptr,
784                                bool DelayTypeCreation = false);
785   static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
786                                      TypeSourceInfo *Info, SourceLocation Loc,
787                                      bool DependentLambda, bool IsGeneric,
788                                      LambdaCaptureDefault CaptureDefault);
789   static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
790
791   bool isDynamicClass() const {
792     return data().Polymorphic || data().NumVBases != 0;
793   }
794
795   /// @returns true if class is dynamic or might be dynamic because the
796   /// definition is incomplete of dependent.
797   bool mayBeDynamicClass() const {
798     return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
799   }
800
801   /// @returns true if class is non dynamic or might be non dynamic because the
802   /// definition is incomplete of dependent.
803   bool mayBeNonDynamicClass() const {
804     return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
805   }
806
807   void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
808
809   bool isParsingBaseSpecifiers() const {
810     return data().IsParsingBaseSpecifiers;
811   }
812
813   unsigned getODRHash() const;
814
815   /// Sets the base classes of this struct or class.
816   void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
817
818   /// Retrieves the number of base classes of this class.
819   unsigned getNumBases() const { return data().NumBases; }
820
821   using base_class_range = llvm::iterator_range<base_class_iterator>;
822   using base_class_const_range =
823       llvm::iterator_range<base_class_const_iterator>;
824
825   base_class_range bases() {
826     return base_class_range(bases_begin(), bases_end());
827   }
828   base_class_const_range bases() const {
829     return base_class_const_range(bases_begin(), bases_end());
830   }
831
832   base_class_iterator bases_begin() { return data().getBases(); }
833   base_class_const_iterator bases_begin() const { return data().getBases(); }
834   base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
835   base_class_const_iterator bases_end() const {
836     return bases_begin() + data().NumBases;
837   }
838
839   /// Retrieves the number of virtual base classes of this class.
840   unsigned getNumVBases() const { return data().NumVBases; }
841
842   base_class_range vbases() {
843     return base_class_range(vbases_begin(), vbases_end());
844   }
845   base_class_const_range vbases() const {
846     return base_class_const_range(vbases_begin(), vbases_end());
847   }
848
849   base_class_iterator vbases_begin() { return data().getVBases(); }
850   base_class_const_iterator vbases_begin() const { return data().getVBases(); }
851   base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
852   base_class_const_iterator vbases_end() const {
853     return vbases_begin() + data().NumVBases;
854   }
855
856   /// Determine whether this class has any dependent base classes which
857   /// are not the current instantiation.
858   bool hasAnyDependentBases() const;
859
860   /// Iterator access to method members.  The method iterator visits
861   /// all method members of the class, including non-instance methods,
862   /// special methods, etc.
863   using method_iterator = specific_decl_iterator<CXXMethodDecl>;
864   using method_range =
865       llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
866
867   method_range methods() const {
868     return method_range(method_begin(), method_end());
869   }
870
871   /// Method begin iterator.  Iterates in the order the methods
872   /// were declared.
873   method_iterator method_begin() const {
874     return method_iterator(decls_begin());
875   }
876
877   /// Method past-the-end iterator.
878   method_iterator method_end() const {
879     return method_iterator(decls_end());
880   }
881
882   /// Iterator access to constructor members.
883   using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
884   using ctor_range =
885       llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
886
887   ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
888
889   ctor_iterator ctor_begin() const {
890     return ctor_iterator(decls_begin());
891   }
892
893   ctor_iterator ctor_end() const {
894     return ctor_iterator(decls_end());
895   }
896
897   /// An iterator over friend declarations.  All of these are defined
898   /// in DeclFriend.h.
899   class friend_iterator;
900   using friend_range = llvm::iterator_range<friend_iterator>;
901
902   friend_range friends() const;
903   friend_iterator friend_begin() const;
904   friend_iterator friend_end() const;
905   void pushFriendDecl(FriendDecl *FD);
906
907   /// Determines whether this record has any friends.
908   bool hasFriends() const {
909     return data().FirstFriend.isValid();
910   }
911
912   /// \c true if a defaulted copy constructor for this class would be
913   /// deleted.
914   bool defaultedCopyConstructorIsDeleted() const {
915     assert((!needsOverloadResolutionForCopyConstructor() ||
916             (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
917            "this property has not yet been computed by Sema");
918     return data().DefaultedCopyConstructorIsDeleted;
919   }
920
921   /// \c true if a defaulted move constructor for this class would be
922   /// deleted.
923   bool defaultedMoveConstructorIsDeleted() const {
924     assert((!needsOverloadResolutionForMoveConstructor() ||
925             (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
926            "this property has not yet been computed by Sema");
927     return data().DefaultedMoveConstructorIsDeleted;
928   }
929
930   /// \c true if a defaulted destructor for this class would be deleted.
931   bool defaultedDestructorIsDeleted() const {
932     assert((!needsOverloadResolutionForDestructor() ||
933             (data().DeclaredSpecialMembers & SMF_Destructor)) &&
934            "this property has not yet been computed by Sema");
935     return data().DefaultedDestructorIsDeleted;
936   }
937
938   /// \c true if we know for sure that this class has a single,
939   /// accessible, unambiguous copy constructor that is not deleted.
940   bool hasSimpleCopyConstructor() const {
941     return !hasUserDeclaredCopyConstructor() &&
942            !data().DefaultedCopyConstructorIsDeleted;
943   }
944
945   /// \c true if we know for sure that this class has a single,
946   /// accessible, unambiguous move constructor that is not deleted.
947   bool hasSimpleMoveConstructor() const {
948     return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
949            !data().DefaultedMoveConstructorIsDeleted;
950   }
951
952   /// \c true if we know for sure that this class has a single,
953   /// accessible, unambiguous move assignment operator that is not deleted.
954   bool hasSimpleMoveAssignment() const {
955     return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
956            !data().DefaultedMoveAssignmentIsDeleted;
957   }
958
959   /// \c true if we know for sure that this class has an accessible
960   /// destructor that is not deleted.
961   bool hasSimpleDestructor() const {
962     return !hasUserDeclaredDestructor() &&
963            !data().DefaultedDestructorIsDeleted;
964   }
965
966   /// Determine whether this class has any default constructors.
967   bool hasDefaultConstructor() const {
968     return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
969            needsImplicitDefaultConstructor();
970   }
971
972   /// Determine if we need to declare a default constructor for
973   /// this class.
974   ///
975   /// This value is used for lazy creation of default constructors.
976   bool needsImplicitDefaultConstructor() const {
977     return !data().UserDeclaredConstructor &&
978            !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
979            // C++14 [expr.prim.lambda]p20:
980            //   The closure type associated with a lambda-expression has no
981            //   default constructor.
982            !isLambda();
983   }
984
985   /// Determine whether this class has any user-declared constructors.
986   ///
987   /// When true, a default constructor will not be implicitly declared.
988   bool hasUserDeclaredConstructor() const {
989     return data().UserDeclaredConstructor;
990   }
991
992   /// Whether this class has a user-provided default constructor
993   /// per C++11.
994   bool hasUserProvidedDefaultConstructor() const {
995     return data().UserProvidedDefaultConstructor;
996   }
997
998   /// Determine whether this class has a user-declared copy constructor.
999   ///
1000   /// When false, a copy constructor will be implicitly declared.
1001   bool hasUserDeclaredCopyConstructor() const {
1002     return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
1003   }
1004
1005   /// Determine whether this class needs an implicit copy
1006   /// constructor to be lazily declared.
1007   bool needsImplicitCopyConstructor() const {
1008     return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
1009   }
1010
1011   /// Determine whether we need to eagerly declare a defaulted copy
1012   /// constructor for this class.
1013   bool needsOverloadResolutionForCopyConstructor() const {
1014     // C++17 [class.copy.ctor]p6:
1015     //   If the class definition declares a move constructor or move assignment
1016     //   operator, the implicitly declared copy constructor is defined as
1017     //   deleted.
1018     // In MSVC mode, sometimes a declared move assignment does not delete an
1019     // implicit copy constructor, so defer this choice to Sema.
1020     if (data().UserDeclaredSpecialMembers &
1021         (SMF_MoveConstructor | SMF_MoveAssignment))
1022       return true;
1023     return data().NeedOverloadResolutionForCopyConstructor;
1024   }
1025
1026   /// Determine whether an implicit copy constructor for this type
1027   /// would have a parameter with a const-qualified reference type.
1028   bool implicitCopyConstructorHasConstParam() const {
1029     return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
1030            (isAbstract() ||
1031             data().ImplicitCopyConstructorCanHaveConstParamForVBase);
1032   }
1033
1034   /// Determine whether this class has a copy constructor with
1035   /// a parameter type which is a reference to a const-qualified type.
1036   bool hasCopyConstructorWithConstParam() const {
1037     return data().HasDeclaredCopyConstructorWithConstParam ||
1038            (needsImplicitCopyConstructor() &&
1039             implicitCopyConstructorHasConstParam());
1040   }
1041
1042   /// Whether this class has a user-declared move constructor or
1043   /// assignment operator.
1044   ///
1045   /// When false, a move constructor and assignment operator may be
1046   /// implicitly declared.
1047   bool hasUserDeclaredMoveOperation() const {
1048     return data().UserDeclaredSpecialMembers &
1049              (SMF_MoveConstructor | SMF_MoveAssignment);
1050   }
1051
1052   /// Determine whether this class has had a move constructor
1053   /// declared by the user.
1054   bool hasUserDeclaredMoveConstructor() const {
1055     return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
1056   }
1057
1058   /// Determine whether this class has a move constructor.
1059   bool hasMoveConstructor() const {
1060     return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
1061            needsImplicitMoveConstructor();
1062   }
1063
1064   /// Set that we attempted to declare an implicit copy
1065   /// constructor, but overload resolution failed so we deleted it.
1066   void setImplicitCopyConstructorIsDeleted() {
1067     assert((data().DefaultedCopyConstructorIsDeleted ||
1068             needsOverloadResolutionForCopyConstructor()) &&
1069            "Copy constructor should not be deleted");
1070     data().DefaultedCopyConstructorIsDeleted = true;
1071   }
1072
1073   /// Set that we attempted to declare an implicit move
1074   /// constructor, but overload resolution failed so we deleted it.
1075   void setImplicitMoveConstructorIsDeleted() {
1076     assert((data().DefaultedMoveConstructorIsDeleted ||
1077             needsOverloadResolutionForMoveConstructor()) &&
1078            "move constructor should not be deleted");
1079     data().DefaultedMoveConstructorIsDeleted = true;
1080   }
1081
1082   /// Set that we attempted to declare an implicit destructor,
1083   /// but overload resolution failed so we deleted it.
1084   void setImplicitDestructorIsDeleted() {
1085     assert((data().DefaultedDestructorIsDeleted ||
1086             needsOverloadResolutionForDestructor()) &&
1087            "destructor should not be deleted");
1088     data().DefaultedDestructorIsDeleted = true;
1089   }
1090
1091   /// Determine whether this class should get an implicit move
1092   /// constructor or if any existing special member function inhibits this.
1093   bool needsImplicitMoveConstructor() const {
1094     return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
1095            !hasUserDeclaredCopyConstructor() &&
1096            !hasUserDeclaredCopyAssignment() &&
1097            !hasUserDeclaredMoveAssignment() &&
1098            !hasUserDeclaredDestructor();
1099   }
1100
1101   /// Determine whether we need to eagerly declare a defaulted move
1102   /// constructor for this class.
1103   bool needsOverloadResolutionForMoveConstructor() const {
1104     return data().NeedOverloadResolutionForMoveConstructor;
1105   }
1106
1107   /// Determine whether this class has a user-declared copy assignment
1108   /// operator.
1109   ///
1110   /// When false, a copy assignment operator will be implicitly declared.
1111   bool hasUserDeclaredCopyAssignment() const {
1112     return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
1113   }
1114
1115   /// Determine whether this class needs an implicit copy
1116   /// assignment operator to be lazily declared.
1117   bool needsImplicitCopyAssignment() const {
1118     return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
1119   }
1120
1121   /// Determine whether we need to eagerly declare a defaulted copy
1122   /// assignment operator for this class.
1123   bool needsOverloadResolutionForCopyAssignment() const {
1124     return data().HasMutableFields;
1125   }
1126
1127   /// Determine whether an implicit copy assignment operator for this
1128   /// type would have a parameter with a const-qualified reference type.
1129   bool implicitCopyAssignmentHasConstParam() const {
1130     return data().ImplicitCopyAssignmentHasConstParam;
1131   }
1132
1133   /// Determine whether this class has a copy assignment operator with
1134   /// a parameter type which is a reference to a const-qualified type or is not
1135   /// a reference.
1136   bool hasCopyAssignmentWithConstParam() const {
1137     return data().HasDeclaredCopyAssignmentWithConstParam ||
1138            (needsImplicitCopyAssignment() &&
1139             implicitCopyAssignmentHasConstParam());
1140   }
1141
1142   /// Determine whether this class has had a move assignment
1143   /// declared by the user.
1144   bool hasUserDeclaredMoveAssignment() const {
1145     return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
1146   }
1147
1148   /// Determine whether this class has a move assignment operator.
1149   bool hasMoveAssignment() const {
1150     return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
1151            needsImplicitMoveAssignment();
1152   }
1153
1154   /// Set that we attempted to declare an implicit move assignment
1155   /// operator, but overload resolution failed so we deleted it.
1156   void setImplicitMoveAssignmentIsDeleted() {
1157     assert((data().DefaultedMoveAssignmentIsDeleted ||
1158             needsOverloadResolutionForMoveAssignment()) &&
1159            "move assignment should not be deleted");
1160     data().DefaultedMoveAssignmentIsDeleted = true;
1161   }
1162
1163   /// Determine whether this class should get an implicit move
1164   /// assignment operator or if any existing special member function inhibits
1165   /// this.
1166   bool needsImplicitMoveAssignment() const {
1167     return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
1168            !hasUserDeclaredCopyConstructor() &&
1169            !hasUserDeclaredCopyAssignment() &&
1170            !hasUserDeclaredMoveConstructor() &&
1171            !hasUserDeclaredDestructor() &&
1172            // C++1z [expr.prim.lambda]p21: "the closure type has a deleted copy
1173            // assignment operator". The intent is that this counts as a user
1174            // declared copy assignment, but we do not model it that way.
1175            !isLambda();
1176   }
1177
1178   /// Determine whether we need to eagerly declare a move assignment
1179   /// operator for this class.
1180   bool needsOverloadResolutionForMoveAssignment() const {
1181     return data().NeedOverloadResolutionForMoveAssignment;
1182   }
1183
1184   /// Determine whether this class has a user-declared destructor.
1185   ///
1186   /// When false, a destructor will be implicitly declared.
1187   bool hasUserDeclaredDestructor() const {
1188     return data().UserDeclaredSpecialMembers & SMF_Destructor;
1189   }
1190
1191   /// Determine whether this class needs an implicit destructor to
1192   /// be lazily declared.
1193   bool needsImplicitDestructor() const {
1194     return !(data().DeclaredSpecialMembers & SMF_Destructor);
1195   }
1196
1197   /// Determine whether we need to eagerly declare a destructor for this
1198   /// class.
1199   bool needsOverloadResolutionForDestructor() const {
1200     return data().NeedOverloadResolutionForDestructor;
1201   }
1202
1203   /// Determine whether this class describes a lambda function object.
1204   bool isLambda() const {
1205     // An update record can't turn a non-lambda into a lambda.
1206     auto *DD = DefinitionData;
1207     return DD && DD->IsLambda;
1208   }
1209
1210   /// Determine whether this class describes a generic
1211   /// lambda function object (i.e. function call operator is
1212   /// a template).
1213   bool isGenericLambda() const;
1214
1215   /// Retrieve the lambda call operator of the closure type
1216   /// if this is a closure type.
1217   CXXMethodDecl *getLambdaCallOperator() const;
1218
1219   /// Retrieve the lambda static invoker, the address of which
1220   /// is returned by the conversion operator, and the body of which
1221   /// is forwarded to the lambda call operator.
1222   CXXMethodDecl *getLambdaStaticInvoker() const;
1223
1224   /// Retrieve the generic lambda's template parameter list.
1225   /// Returns null if the class does not represent a lambda or a generic
1226   /// lambda.
1227   TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1228
1229   LambdaCaptureDefault getLambdaCaptureDefault() const {
1230     assert(isLambda());
1231     return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1232   }
1233
1234   /// For a closure type, retrieve the mapping from captured
1235   /// variables and \c this to the non-static data members that store the
1236   /// values or references of the captures.
1237   ///
1238   /// \param Captures Will be populated with the mapping from captured
1239   /// variables to the corresponding fields.
1240   ///
1241   /// \param ThisCapture Will be set to the field declaration for the
1242   /// \c this capture.
1243   ///
1244   /// \note No entries will be added for init-captures, as they do not capture
1245   /// variables.
1246   void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1247                         FieldDecl *&ThisCapture) const;
1248
1249   using capture_const_iterator = const LambdaCapture *;
1250   using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1251
1252   capture_const_range captures() const {
1253     return capture_const_range(captures_begin(), captures_end());
1254   }
1255
1256   capture_const_iterator captures_begin() const {
1257     return isLambda() ? getLambdaData().Captures : nullptr;
1258   }
1259
1260   capture_const_iterator captures_end() const {
1261     return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1262                       : nullptr;
1263   }
1264
1265   using conversion_iterator = UnresolvedSetIterator;
1266
1267   conversion_iterator conversion_begin() const {
1268     return data().Conversions.get(getASTContext()).begin();
1269   }
1270
1271   conversion_iterator conversion_end() const {
1272     return data().Conversions.get(getASTContext()).end();
1273   }
1274
1275   /// Removes a conversion function from this class.  The conversion
1276   /// function must currently be a member of this class.  Furthermore,
1277   /// this class must currently be in the process of being defined.
1278   void removeConversion(const NamedDecl *Old);
1279
1280   /// Get all conversion functions visible in current class,
1281   /// including conversion function templates.
1282   llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1283
1284   /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1285   /// which is a class with no user-declared constructors, no private
1286   /// or protected non-static data members, no base classes, and no virtual
1287   /// functions (C++ [dcl.init.aggr]p1).
1288   bool isAggregate() const { return data().Aggregate; }
1289
1290   /// Whether this class has any in-class initializers
1291   /// for non-static data members (including those in anonymous unions or
1292   /// structs).
1293   bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1294
1295   /// Whether this class or any of its subobjects has any members of
1296   /// reference type which would make value-initialization ill-formed.
1297   ///
1298   /// Per C++03 [dcl.init]p5:
1299   ///  - if T is a non-union class type without a user-declared constructor,
1300   ///    then every non-static data member and base-class component of T is
1301   ///    value-initialized [...] A program that calls for [...]
1302   ///    value-initialization of an entity of reference type is ill-formed.
1303   bool hasUninitializedReferenceMember() const {
1304     return !isUnion() && !hasUserDeclaredConstructor() &&
1305            data().HasUninitializedReferenceMember;
1306   }
1307
1308   /// Whether this class is a POD-type (C++ [class]p4)
1309   ///
1310   /// For purposes of this function a class is POD if it is an aggregate
1311   /// that has no non-static non-POD data members, no reference data
1312   /// members, no user-defined copy assignment operator and no
1313   /// user-defined destructor.
1314   ///
1315   /// Note that this is the C++ TR1 definition of POD.
1316   bool isPOD() const { return data().PlainOldData; }
1317
1318   /// True if this class is C-like, without C++-specific features, e.g.
1319   /// it contains only public fields, no bases, tag kind is not 'class', etc.
1320   bool isCLike() const;
1321
1322   /// Determine whether this is an empty class in the sense of
1323   /// (C++11 [meta.unary.prop]).
1324   ///
1325   /// The CXXRecordDecl is a class type, but not a union type,
1326   /// with no non-static data members other than bit-fields of length 0,
1327   /// no virtual member functions, no virtual base classes,
1328   /// and no base class B for which is_empty<B>::value is false.
1329   ///
1330   /// \note This does NOT include a check for union-ness.
1331   bool isEmpty() const { return data().Empty; }
1332
1333   /// Determine whether this class has direct non-static data members.
1334   bool hasDirectFields() const {
1335     auto &D = data();
1336     return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1337   }
1338
1339   /// Whether this class is polymorphic (C++ [class.virtual]),
1340   /// which means that the class contains or inherits a virtual function.
1341   bool isPolymorphic() const { return data().Polymorphic; }
1342
1343   /// Determine whether this class has a pure virtual function.
1344   ///
1345   /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1346   /// a pure virtual function or inherits a pure virtual function that is
1347   /// not overridden.
1348   bool isAbstract() const { return data().Abstract; }
1349
1350   /// Determine whether this class is standard-layout per
1351   /// C++ [class]p7.
1352   bool isStandardLayout() const { return data().IsStandardLayout; }
1353
1354   /// Determine whether this class was standard-layout per
1355   /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1356   bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1357
1358   /// Determine whether this class, or any of its class subobjects,
1359   /// contains a mutable field.
1360   bool hasMutableFields() const { return data().HasMutableFields; }
1361
1362   /// Determine whether this class has any variant members.
1363   bool hasVariantMembers() const { return data().HasVariantMembers; }
1364
1365   /// Determine whether this class has a trivial default constructor
1366   /// (C++11 [class.ctor]p5).
1367   bool hasTrivialDefaultConstructor() const {
1368     return hasDefaultConstructor() &&
1369            (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1370   }
1371
1372   /// Determine whether this class has a non-trivial default constructor
1373   /// (C++11 [class.ctor]p5).
1374   bool hasNonTrivialDefaultConstructor() const {
1375     return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1376            (needsImplicitDefaultConstructor() &&
1377             !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1378   }
1379
1380   /// Determine whether this class has at least one constexpr constructor
1381   /// other than the copy or move constructors.
1382   bool hasConstexprNonCopyMoveConstructor() const {
1383     return data().HasConstexprNonCopyMoveConstructor ||
1384            (needsImplicitDefaultConstructor() &&
1385             defaultedDefaultConstructorIsConstexpr());
1386   }
1387
1388   /// Determine whether a defaulted default constructor for this class
1389   /// would be constexpr.
1390   bool defaultedDefaultConstructorIsConstexpr() const {
1391     return data().DefaultedDefaultConstructorIsConstexpr &&
1392            (!isUnion() || hasInClassInitializer() || !hasVariantMembers());
1393   }
1394
1395   /// Determine whether this class has a constexpr default constructor.
1396   bool hasConstexprDefaultConstructor() const {
1397     return data().HasConstexprDefaultConstructor ||
1398            (needsImplicitDefaultConstructor() &&
1399             defaultedDefaultConstructorIsConstexpr());
1400   }
1401
1402   /// Determine whether this class has a trivial copy constructor
1403   /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1404   bool hasTrivialCopyConstructor() const {
1405     return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1406   }
1407
1408   bool hasTrivialCopyConstructorForCall() const {
1409     return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1410   }
1411
1412   /// Determine whether this class has a non-trivial copy constructor
1413   /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1414   bool hasNonTrivialCopyConstructor() const {
1415     return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1416            !hasTrivialCopyConstructor();
1417   }
1418
1419   bool hasNonTrivialCopyConstructorForCall() const {
1420     return (data().DeclaredNonTrivialSpecialMembersForCall &
1421             SMF_CopyConstructor) ||
1422            !hasTrivialCopyConstructorForCall();
1423   }
1424
1425   /// Determine whether this class has a trivial move constructor
1426   /// (C++11 [class.copy]p12)
1427   bool hasTrivialMoveConstructor() const {
1428     return hasMoveConstructor() &&
1429            (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1430   }
1431
1432   bool hasTrivialMoveConstructorForCall() const {
1433     return hasMoveConstructor() &&
1434            (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1435   }
1436
1437   /// Determine whether this class has a non-trivial move constructor
1438   /// (C++11 [class.copy]p12)
1439   bool hasNonTrivialMoveConstructor() const {
1440     return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1441            (needsImplicitMoveConstructor() &&
1442             !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1443   }
1444
1445   bool hasNonTrivialMoveConstructorForCall() const {
1446     return (data().DeclaredNonTrivialSpecialMembersForCall &
1447             SMF_MoveConstructor) ||
1448            (needsImplicitMoveConstructor() &&
1449             !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1450   }
1451
1452   /// Determine whether this class has a trivial copy assignment operator
1453   /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1454   bool hasTrivialCopyAssignment() const {
1455     return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1456   }
1457
1458   /// Determine whether this class has a non-trivial copy assignment
1459   /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1460   bool hasNonTrivialCopyAssignment() const {
1461     return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1462            !hasTrivialCopyAssignment();
1463   }
1464
1465   /// Determine whether this class has a trivial move assignment operator
1466   /// (C++11 [class.copy]p25)
1467   bool hasTrivialMoveAssignment() const {
1468     return hasMoveAssignment() &&
1469            (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1470   }
1471
1472   /// Determine whether this class has a non-trivial move assignment
1473   /// operator (C++11 [class.copy]p25)
1474   bool hasNonTrivialMoveAssignment() const {
1475     return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1476            (needsImplicitMoveAssignment() &&
1477             !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1478   }
1479
1480   /// Determine whether this class has a trivial destructor
1481   /// (C++ [class.dtor]p3)
1482   bool hasTrivialDestructor() const {
1483     return data().HasTrivialSpecialMembers & SMF_Destructor;
1484   }
1485
1486   bool hasTrivialDestructorForCall() const {
1487     return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1488   }
1489
1490   /// Determine whether this class has a non-trivial destructor
1491   /// (C++ [class.dtor]p3)
1492   bool hasNonTrivialDestructor() const {
1493     return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1494   }
1495
1496   bool hasNonTrivialDestructorForCall() const {
1497     return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1498   }
1499
1500   void setHasTrivialSpecialMemberForCall() {
1501     data().HasTrivialSpecialMembersForCall =
1502         (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1503   }
1504
1505   /// Determine whether declaring a const variable with this type is ok
1506   /// per core issue 253.
1507   bool allowConstDefaultInit() const {
1508     return !data().HasUninitializedFields ||
1509            !(data().HasDefaultedDefaultConstructor ||
1510              needsImplicitDefaultConstructor());
1511   }
1512
1513   /// Determine whether this class has a destructor which has no
1514   /// semantic effect.
1515   ///
1516   /// Any such destructor will be trivial, public, defaulted and not deleted,
1517   /// and will call only irrelevant destructors.
1518   bool hasIrrelevantDestructor() const {
1519     return data().HasIrrelevantDestructor;
1520   }
1521
1522   /// Determine whether this class has a non-literal or/ volatile type
1523   /// non-static data member or base class.
1524   bool hasNonLiteralTypeFieldsOrBases() const {
1525     return data().HasNonLiteralTypeFieldsOrBases;
1526   }
1527
1528   /// Determine whether this class has a using-declaration that names
1529   /// a user-declared base class constructor.
1530   bool hasInheritedConstructor() const {
1531     return data().HasInheritedConstructor;
1532   }
1533
1534   /// Determine whether this class has a using-declaration that names
1535   /// a base class assignment operator.
1536   bool hasInheritedAssignment() const {
1537     return data().HasInheritedAssignment;
1538   }
1539
1540   /// Determine whether this class is considered trivially copyable per
1541   /// (C++11 [class]p6).
1542   bool isTriviallyCopyable() const;
1543
1544   /// Determine whether this class is considered trivial.
1545   ///
1546   /// C++11 [class]p6:
1547   ///    "A trivial class is a class that has a trivial default constructor and
1548   ///    is trivially copiable."
1549   bool isTrivial() const {
1550     return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1551   }
1552
1553   /// Determine whether this class is a literal type.
1554   ///
1555   /// C++11 [basic.types]p10:
1556   ///   A class type that has all the following properties:
1557   ///     - it has a trivial destructor
1558   ///     - every constructor call and full-expression in the
1559   ///       brace-or-equal-intializers for non-static data members (if any) is
1560   ///       a constant expression.
1561   ///     - it is an aggregate type or has at least one constexpr constructor
1562   ///       or constructor template that is not a copy or move constructor, and
1563   ///     - all of its non-static data members and base classes are of literal
1564   ///       types
1565   ///
1566   /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1567   /// treating types with trivial default constructors as literal types.
1568   ///
1569   /// Only in C++17 and beyond, are lambdas literal types.
1570   bool isLiteral() const {
1571     return hasTrivialDestructor() &&
1572            (!isLambda() || getASTContext().getLangOpts().CPlusPlus17) &&
1573            !hasNonLiteralTypeFieldsOrBases() &&
1574            (isAggregate() || isLambda() ||
1575             hasConstexprNonCopyMoveConstructor() ||
1576             hasTrivialDefaultConstructor());
1577   }
1578
1579   /// If this record is an instantiation of a member class,
1580   /// retrieves the member class from which it was instantiated.
1581   ///
1582   /// This routine will return non-null for (non-templated) member
1583   /// classes of class templates. For example, given:
1584   ///
1585   /// \code
1586   /// template<typename T>
1587   /// struct X {
1588   ///   struct A { };
1589   /// };
1590   /// \endcode
1591   ///
1592   /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1593   /// whose parent is the class template specialization X<int>. For
1594   /// this declaration, getInstantiatedFromMemberClass() will return
1595   /// the CXXRecordDecl X<T>::A. When a complete definition of
1596   /// X<int>::A is required, it will be instantiated from the
1597   /// declaration returned by getInstantiatedFromMemberClass().
1598   CXXRecordDecl *getInstantiatedFromMemberClass() const;
1599
1600   /// If this class is an instantiation of a member class of a
1601   /// class template specialization, retrieves the member specialization
1602   /// information.
1603   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1604
1605   /// Specify that this record is an instantiation of the
1606   /// member class \p RD.
1607   void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1608                                      TemplateSpecializationKind TSK);
1609
1610   /// Retrieves the class template that is described by this
1611   /// class declaration.
1612   ///
1613   /// Every class template is represented as a ClassTemplateDecl and a
1614   /// CXXRecordDecl. The former contains template properties (such as
1615   /// the template parameter lists) while the latter contains the
1616   /// actual description of the template's
1617   /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1618   /// CXXRecordDecl that from a ClassTemplateDecl, while
1619   /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1620   /// a CXXRecordDecl.
1621   ClassTemplateDecl *getDescribedClassTemplate() const;
1622
1623   void setDescribedClassTemplate(ClassTemplateDecl *Template);
1624
1625   /// Determine whether this particular class is a specialization or
1626   /// instantiation of a class template or member class of a class template,
1627   /// and how it was instantiated or specialized.
1628   TemplateSpecializationKind getTemplateSpecializationKind() const;
1629
1630   /// Set the kind of specialization or template instantiation this is.
1631   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1632
1633   /// Retrieve the record declaration from which this record could be
1634   /// instantiated. Returns null if this class is not a template instantiation.
1635   const CXXRecordDecl *getTemplateInstantiationPattern() const;
1636
1637   CXXRecordDecl *getTemplateInstantiationPattern() {
1638     return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1639                                            ->getTemplateInstantiationPattern());
1640   }
1641
1642   /// Returns the destructor decl for this class.
1643   CXXDestructorDecl *getDestructor() const;
1644
1645   /// Returns true if the class destructor, or any implicitly invoked
1646   /// destructors are marked noreturn.
1647   bool isAnyDestructorNoReturn() const;
1648
1649   /// If the class is a local class [class.local], returns
1650   /// the enclosing function declaration.
1651   const FunctionDecl *isLocalClass() const {
1652     if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1653       return RD->isLocalClass();
1654
1655     return dyn_cast<FunctionDecl>(getDeclContext());
1656   }
1657
1658   FunctionDecl *isLocalClass() {
1659     return const_cast<FunctionDecl*>(
1660         const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1661   }
1662
1663   /// Determine whether this dependent class is a current instantiation,
1664   /// when viewed from within the given context.
1665   bool isCurrentInstantiation(const DeclContext *CurContext) const;
1666
1667   /// Determine whether this class is derived from the class \p Base.
1668   ///
1669   /// This routine only determines whether this class is derived from \p Base,
1670   /// but does not account for factors that may make a Derived -> Base class
1671   /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1672   /// base class subobjects.
1673   ///
1674   /// \param Base the base class we are searching for.
1675   ///
1676   /// \returns true if this class is derived from Base, false otherwise.
1677   bool isDerivedFrom(const CXXRecordDecl *Base) const;
1678
1679   /// Determine whether this class is derived from the type \p Base.
1680   ///
1681   /// This routine only determines whether this class is derived from \p Base,
1682   /// but does not account for factors that may make a Derived -> Base class
1683   /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1684   /// base class subobjects.
1685   ///
1686   /// \param Base the base class we are searching for.
1687   ///
1688   /// \param Paths will contain the paths taken from the current class to the
1689   /// given \p Base class.
1690   ///
1691   /// \returns true if this class is derived from \p Base, false otherwise.
1692   ///
1693   /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1694   /// tangling input and output in \p Paths
1695   bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1696
1697   /// Determine whether this class is virtually derived from
1698   /// the class \p Base.
1699   ///
1700   /// This routine only determines whether this class is virtually
1701   /// derived from \p Base, but does not account for factors that may
1702   /// make a Derived -> Base class ill-formed, such as
1703   /// private/protected inheritance or multiple, ambiguous base class
1704   /// subobjects.
1705   ///
1706   /// \param Base the base class we are searching for.
1707   ///
1708   /// \returns true if this class is virtually derived from Base,
1709   /// false otherwise.
1710   bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1711
1712   /// Determine whether this class is provably not derived from
1713   /// the type \p Base.
1714   bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1715
1716   /// Function type used by forallBases() as a callback.
1717   ///
1718   /// \param BaseDefinition the definition of the base class
1719   ///
1720   /// \returns true if this base matched the search criteria
1721   using ForallBasesCallback =
1722       llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1723
1724   /// Determines if the given callback holds for all the direct
1725   /// or indirect base classes of this type.
1726   ///
1727   /// The class itself does not count as a base class.  This routine
1728   /// returns false if the class has non-computable base classes.
1729   ///
1730   /// \param BaseMatches Callback invoked for each (direct or indirect) base
1731   /// class of this type, or if \p AllowShortCircuit is true then until a call
1732   /// returns false.
1733   ///
1734   /// \param AllowShortCircuit if false, forces the callback to be called
1735   /// for every base class, even if a dependent or non-matching base was
1736   /// found.
1737   bool forallBases(ForallBasesCallback BaseMatches,
1738                    bool AllowShortCircuit = true) const;
1739
1740   /// Function type used by lookupInBases() to determine whether a
1741   /// specific base class subobject matches the lookup criteria.
1742   ///
1743   /// \param Specifier the base-class specifier that describes the inheritance
1744   /// from the base class we are trying to match.
1745   ///
1746   /// \param Path the current path, from the most-derived class down to the
1747   /// base named by the \p Specifier.
1748   ///
1749   /// \returns true if this base matched the search criteria, false otherwise.
1750   using BaseMatchesCallback =
1751       llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1752                               CXXBasePath &Path)>;
1753
1754   /// Look for entities within the base classes of this C++ class,
1755   /// transitively searching all base class subobjects.
1756   ///
1757   /// This routine uses the callback function \p BaseMatches to find base
1758   /// classes meeting some search criteria, walking all base class subobjects
1759   /// and populating the given \p Paths structure with the paths through the
1760   /// inheritance hierarchy that resulted in a match. On a successful search,
1761   /// the \p Paths structure can be queried to retrieve the matching paths and
1762   /// to determine if there were any ambiguities.
1763   ///
1764   /// \param BaseMatches callback function used to determine whether a given
1765   /// base matches the user-defined search criteria.
1766   ///
1767   /// \param Paths used to record the paths from this class to its base class
1768   /// subobjects that match the search criteria.
1769   ///
1770   /// \param LookupInDependent can be set to true to extend the search to
1771   /// dependent base classes.
1772   ///
1773   /// \returns true if there exists any path from this class to a base class
1774   /// subobject that matches the search criteria.
1775   bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1776                      bool LookupInDependent = false) const;
1777
1778   /// Base-class lookup callback that determines whether the given
1779   /// base class specifier refers to a specific class declaration.
1780   ///
1781   /// This callback can be used with \c lookupInBases() to determine whether
1782   /// a given derived class has is a base class subobject of a particular type.
1783   /// The base record pointer should refer to the canonical CXXRecordDecl of the
1784   /// base class that we are searching for.
1785   static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1786                             CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1787
1788   /// Base-class lookup callback that determines whether the
1789   /// given base class specifier refers to a specific class
1790   /// declaration and describes virtual derivation.
1791   ///
1792   /// This callback can be used with \c lookupInBases() to determine
1793   /// whether a given derived class has is a virtual base class
1794   /// subobject of a particular type.  The base record pointer should
1795   /// refer to the canonical CXXRecordDecl of the base class that we
1796   /// are searching for.
1797   static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1798                                    CXXBasePath &Path,
1799                                    const CXXRecordDecl *BaseRecord);
1800
1801   /// Base-class lookup callback that determines whether there exists
1802   /// a tag with the given name.
1803   ///
1804   /// This callback can be used with \c lookupInBases() to find tag members
1805   /// of the given name within a C++ class hierarchy.
1806   static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1807                             CXXBasePath &Path, DeclarationName Name);
1808
1809   /// Base-class lookup callback that determines whether there exists
1810   /// a member with the given name.
1811   ///
1812   /// This callback can be used with \c lookupInBases() to find members
1813   /// of the given name within a C++ class hierarchy.
1814   static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1815                                  CXXBasePath &Path, DeclarationName Name);
1816
1817   /// Base-class lookup callback that determines whether there exists
1818   /// a member with the given name.
1819   ///
1820   /// This callback can be used with \c lookupInBases() to find members
1821   /// of the given name within a C++ class hierarchy, including dependent
1822   /// classes.
1823   static bool
1824   FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1825                                        CXXBasePath &Path, DeclarationName Name);
1826
1827   /// Base-class lookup callback that determines whether there exists
1828   /// an OpenMP declare reduction member with the given name.
1829   ///
1830   /// This callback can be used with \c lookupInBases() to find members
1831   /// of the given name within a C++ class hierarchy.
1832   static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1833                                      CXXBasePath &Path, DeclarationName Name);
1834
1835   /// Base-class lookup callback that determines whether there exists
1836   /// a member with the given name that can be used in a nested-name-specifier.
1837   ///
1838   /// This callback can be used with \c lookupInBases() to find members of
1839   /// the given name within a C++ class hierarchy that can occur within
1840   /// nested-name-specifiers.
1841   static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1842                                             CXXBasePath &Path,
1843                                             DeclarationName Name);
1844
1845   /// Retrieve the final overriders for each virtual member
1846   /// function in the class hierarchy where this class is the
1847   /// most-derived class in the class hierarchy.
1848   void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1849
1850   /// Get the indirect primary bases for this class.
1851   void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1852
1853   /// Performs an imprecise lookup of a dependent name in this class.
1854   ///
1855   /// This function does not follow strict semantic rules and should be used
1856   /// only when lookup rules can be relaxed, e.g. indexing.
1857   std::vector<const NamedDecl *>
1858   lookupDependentName(const DeclarationName &Name,
1859                       llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1860
1861   /// Renders and displays an inheritance diagram
1862   /// for this C++ class and all of its base classes (transitively) using
1863   /// GraphViz.
1864   void viewInheritance(ASTContext& Context) const;
1865
1866   /// Calculates the access of a decl that is reached
1867   /// along a path.
1868   static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1869                                      AccessSpecifier DeclAccess) {
1870     assert(DeclAccess != AS_none);
1871     if (DeclAccess == AS_private) return AS_none;
1872     return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1873   }
1874
1875   /// Indicates that the declaration of a defaulted or deleted special
1876   /// member function is now complete.
1877   void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1878
1879   void setTrivialForCallFlags(CXXMethodDecl *MD);
1880
1881   /// Indicates that the definition of this class is now complete.
1882   void completeDefinition() override;
1883
1884   /// Indicates that the definition of this class is now complete,
1885   /// and provides a final overrider map to help determine
1886   ///
1887   /// \param FinalOverriders The final overrider map for this class, which can
1888   /// be provided as an optimization for abstract-class checking. If NULL,
1889   /// final overriders will be computed if they are needed to complete the
1890   /// definition.
1891   void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1892
1893   /// Determine whether this class may end up being abstract, even though
1894   /// it is not yet known to be abstract.
1895   ///
1896   /// \returns true if this class is not known to be abstract but has any
1897   /// base classes that are abstract. In this case, \c completeDefinition()
1898   /// will need to compute final overriders to determine whether the class is
1899   /// actually abstract.
1900   bool mayBeAbstract() const;
1901
1902   /// If this is the closure type of a lambda expression, retrieve the
1903   /// number to be used for name mangling in the Itanium C++ ABI.
1904   ///
1905   /// Zero indicates that this closure type has internal linkage, so the
1906   /// mangling number does not matter, while a non-zero value indicates which
1907   /// lambda expression this is in this particular context.
1908   unsigned getLambdaManglingNumber() const {
1909     assert(isLambda() && "Not a lambda closure type!");
1910     return getLambdaData().ManglingNumber;
1911   }
1912
1913   /// Retrieve the declaration that provides additional context for a
1914   /// lambda, when the normal declaration context is not specific enough.
1915   ///
1916   /// Certain contexts (default arguments of in-class function parameters and
1917   /// the initializers of data members) have separate name mangling rules for
1918   /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1919   /// the declaration in which the lambda occurs, e.g., the function parameter
1920   /// or the non-static data member. Otherwise, it returns NULL to imply that
1921   /// the declaration context suffices.
1922   Decl *getLambdaContextDecl() const;
1923
1924   /// Set the mangling number and context declaration for a lambda
1925   /// class.
1926   void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
1927     getLambdaData().ManglingNumber = ManglingNumber;
1928     getLambdaData().ContextDecl = ContextDecl;
1929   }
1930
1931   /// Returns the inheritance model used for this record.
1932   MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1933
1934   /// Calculate what the inheritance model would be for this class.
1935   MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1936
1937   /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1938   /// member pointer if we can guarantee that zero is not a valid field offset,
1939   /// or if the member pointer has multiple fields.  Polymorphic classes have a
1940   /// vfptr at offset zero, so we can use zero for null.  If there are multiple
1941   /// fields, we can use zero even if it is a valid field offset because
1942   /// null-ness testing will check the other fields.
1943   bool nullFieldOffsetIsZero() const {
1944     return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1945                                                getMSInheritanceModel()) ||
1946            (hasDefinition() && isPolymorphic());
1947   }
1948
1949   /// Controls when vtordisps will be emitted if this record is used as a
1950   /// virtual base.
1951   MSVtorDispAttr::Mode getMSVtorDispMode() const;
1952
1953   /// Determine whether this lambda expression was known to be dependent
1954   /// at the time it was created, even if its context does not appear to be
1955   /// dependent.
1956   ///
1957   /// This flag is a workaround for an issue with parsing, where default
1958   /// arguments are parsed before their enclosing function declarations have
1959   /// been created. This means that any lambda expressions within those
1960   /// default arguments will have as their DeclContext the context enclosing
1961   /// the function declaration, which may be non-dependent even when the
1962   /// function declaration itself is dependent. This flag indicates when we
1963   /// know that the lambda is dependent despite that.
1964   bool isDependentLambda() const {
1965     return isLambda() && getLambdaData().Dependent;
1966   }
1967
1968   TypeSourceInfo *getLambdaTypeInfo() const {
1969     return getLambdaData().MethodTyInfo;
1970   }
1971
1972   // Determine whether this type is an Interface Like type for
1973   // __interface inheritance purposes.
1974   bool isInterfaceLike() const;
1975
1976   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1977   static bool classofKind(Kind K) {
1978     return K >= firstCXXRecord && K <= lastCXXRecord;
1979   }
1980 };
1981
1982 /// Represents a C++ deduction guide declaration.
1983 ///
1984 /// \code
1985 /// template<typename T> struct A { A(); A(T); };
1986 /// A() -> A<int>;
1987 /// \endcode
1988 ///
1989 /// In this example, there will be an explicit deduction guide from the
1990 /// second line, and implicit deduction guide templates synthesized from
1991 /// the constructors of \c A.
1992 class CXXDeductionGuideDecl : public FunctionDecl {
1993   void anchor() override;
1994
1995 private:
1996   CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1997                         bool IsExplicit, const DeclarationNameInfo &NameInfo,
1998                         QualType T, TypeSourceInfo *TInfo,
1999                         SourceLocation EndLocation)
2000       : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
2001                      SC_None, false, false) {
2002     if (EndLocation.isValid())
2003       setRangeEnd(EndLocation);
2004     IsExplicitSpecified = IsExplicit;
2005   }
2006
2007 public:
2008   friend class ASTDeclReader;
2009   friend class ASTDeclWriter;
2010
2011   static CXXDeductionGuideDecl *Create(ASTContext &C, DeclContext *DC,
2012                                        SourceLocation StartLoc, bool IsExplicit,
2013                                        const DeclarationNameInfo &NameInfo,
2014                                        QualType T, TypeSourceInfo *TInfo,
2015                                        SourceLocation EndLocation);
2016
2017   static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2018
2019   /// Whether this deduction guide is explicit.
2020   bool isExplicit() const { return IsExplicitSpecified; }
2021
2022   /// Whether this deduction guide was declared with the 'explicit' specifier.
2023   bool isExplicitSpecified() const { return IsExplicitSpecified; }
2024
2025   /// Get the template for which this guide performs deduction.
2026   TemplateDecl *getDeducedTemplate() const {
2027     return getDeclName().getCXXDeductionGuideTemplate();
2028   }
2029
2030   void setIsCopyDeductionCandidate() {
2031     IsCopyDeductionCandidate = true;
2032   }
2033
2034   bool isCopyDeductionCandidate() const { return IsCopyDeductionCandidate; }
2035
2036   // Implement isa/cast/dyncast/etc.
2037   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2038   static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2039 };
2040
2041 /// Represents a static or instance method of a struct/union/class.
2042 ///
2043 /// In the terminology of the C++ Standard, these are the (static and
2044 /// non-static) member functions, whether virtual or not.
2045 class CXXMethodDecl : public FunctionDecl {
2046   void anchor() override;
2047
2048 protected:
2049   CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2050                 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2051                 QualType T, TypeSourceInfo *TInfo,
2052                 StorageClass SC, bool isInline,
2053                 bool isConstexpr, SourceLocation EndLocation)
2054     : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo,
2055                    SC, isInline, isConstexpr) {
2056     if (EndLocation.isValid())
2057       setRangeEnd(EndLocation);
2058   }
2059
2060 public:
2061   static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2062                                SourceLocation StartLoc,
2063                                const DeclarationNameInfo &NameInfo,
2064                                QualType T, TypeSourceInfo *TInfo,
2065                                StorageClass SC,
2066                                bool isInline,
2067                                bool isConstexpr,
2068                                SourceLocation EndLocation);
2069
2070   static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2071
2072   bool isStatic() const;
2073   bool isInstance() const { return !isStatic(); }
2074
2075   /// Returns true if the given operator is implicitly static in a record
2076   /// context.
2077   static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2078     // [class.free]p1:
2079     // Any allocation function for a class T is a static member
2080     // (even if not explicitly declared static).
2081     // [class.free]p6 Any deallocation function for a class X is a static member
2082     // (even if not explicitly declared static).
2083     return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2084            OOK == OO_Array_Delete;
2085   }
2086
2087   bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2088   bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2089
2090   bool isVirtual() const {
2091     CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2092
2093     // Member function is virtual if it is marked explicitly so, or if it is
2094     // declared in __interface -- then it is automatically pure virtual.
2095     if (CD->isVirtualAsWritten() || CD->isPure())
2096       return true;
2097
2098     return CD->size_overridden_methods() != 0;
2099   }
2100
2101   /// If it's possible to devirtualize a call to this method, return the called
2102   /// function. Otherwise, return null.
2103
2104   /// \param Base The object on which this virtual function is called.
2105   /// \param IsAppleKext True if we are compiling for Apple kext.
2106   CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2107
2108   const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2109                                               bool IsAppleKext) const {
2110     return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2111         Base, IsAppleKext);
2112   }
2113
2114   /// Determine whether this is a usual deallocation function
2115   /// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded
2116   /// delete or delete[] operator with a particular signature.
2117   bool isUsualDeallocationFunction() const;
2118
2119   /// Determine whether this is a copy-assignment operator, regardless
2120   /// of whether it was declared implicitly or explicitly.
2121   bool isCopyAssignmentOperator() const;
2122
2123   /// Determine whether this is a move assignment operator.
2124   bool isMoveAssignmentOperator() const;
2125
2126   CXXMethodDecl *getCanonicalDecl() override {
2127     return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2128   }
2129   const CXXMethodDecl *getCanonicalDecl() const {
2130     return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2131   }
2132
2133   CXXMethodDecl *getMostRecentDecl() {
2134     return cast<CXXMethodDecl>(
2135             static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2136   }
2137   const CXXMethodDecl *getMostRecentDecl() const {
2138     return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2139   }
2140
2141   /// True if this method is user-declared and was not
2142   /// deleted or defaulted on its first declaration.
2143   bool isUserProvided() const {
2144     auto *DeclAsWritten = this;
2145     if (auto *Pattern = getTemplateInstantiationPattern())
2146       DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2147     return !(DeclAsWritten->isDeleted() ||
2148              DeclAsWritten->getCanonicalDecl()->isDefaulted());
2149   }
2150
2151   void addOverriddenMethod(const CXXMethodDecl *MD);
2152
2153   using method_iterator = const CXXMethodDecl *const *;
2154
2155   method_iterator begin_overridden_methods() const;
2156   method_iterator end_overridden_methods() const;
2157   unsigned size_overridden_methods() const;
2158
2159   using overridden_method_range= ASTContext::overridden_method_range;
2160
2161   overridden_method_range overridden_methods() const;
2162
2163   /// Returns the parent of this method declaration, which
2164   /// is the class in which this method is defined.
2165   const CXXRecordDecl *getParent() const {
2166     return cast<CXXRecordDecl>(FunctionDecl::getParent());
2167   }
2168
2169   /// Returns the parent of this method declaration, which
2170   /// is the class in which this method is defined.
2171   CXXRecordDecl *getParent() {
2172     return const_cast<CXXRecordDecl *>(
2173              cast<CXXRecordDecl>(FunctionDecl::getParent()));
2174   }
2175
2176   /// Returns the type of the \c this pointer.
2177   ///
2178   /// Should only be called for instance (i.e., non-static) methods. Note
2179   /// that for the call operator of a lambda closure type, this returns the
2180   /// desugared 'this' type (a pointer to the closure type), not the captured
2181   /// 'this' type.
2182   QualType getThisType(ASTContext &C) const;
2183
2184   unsigned getTypeQualifiers() const {
2185     return getType()->getAs<FunctionProtoType>()->getTypeQuals();
2186   }
2187
2188   /// Retrieve the ref-qualifier associated with this method.
2189   ///
2190   /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2191   /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2192   /// @code
2193   /// struct X {
2194   ///   void f() &;
2195   ///   void g() &&;
2196   ///   void h();
2197   /// };
2198   /// @endcode
2199   RefQualifierKind getRefQualifier() const {
2200     return getType()->getAs<FunctionProtoType>()->getRefQualifier();
2201   }
2202
2203   bool hasInlineBody() const;
2204
2205   /// Determine whether this is a lambda closure type's static member
2206   /// function that is used for the result of the lambda's conversion to
2207   /// function pointer (for a lambda with no captures).
2208   ///
2209   /// The function itself, if used, will have a placeholder body that will be
2210   /// supplied by IR generation to either forward to the function call operator
2211   /// or clone the function call operator.
2212   bool isLambdaStaticInvoker() const;
2213
2214   /// Find the method in \p RD that corresponds to this one.
2215   ///
2216   /// Find if \p RD or one of the classes it inherits from override this method.
2217   /// If so, return it. \p RD is assumed to be a subclass of the class defining
2218   /// this method (or be the class itself), unless \p MayBeBase is set to true.
2219   CXXMethodDecl *
2220   getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2221                                 bool MayBeBase = false);
2222
2223   const CXXMethodDecl *
2224   getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2225                                 bool MayBeBase = false) const {
2226     return const_cast<CXXMethodDecl *>(this)
2227               ->getCorrespondingMethodInClass(RD, MayBeBase);
2228   }
2229
2230   // Implement isa/cast/dyncast/etc.
2231   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2232   static bool classofKind(Kind K) {
2233     return K >= firstCXXMethod && K <= lastCXXMethod;
2234   }
2235 };
2236
2237 /// Represents a C++ base or member initializer.
2238 ///
2239 /// This is part of a constructor initializer that
2240 /// initializes one non-static member variable or one base class. For
2241 /// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2242 /// initializers:
2243 ///
2244 /// \code
2245 /// class A { };
2246 /// class B : public A {
2247 ///   float f;
2248 /// public:
2249 ///   B(A& a) : A(a), f(3.14159) { }
2250 /// };
2251 /// \endcode
2252 class CXXCtorInitializer final {
2253   /// Either the base class name/delegating constructor type (stored as
2254   /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2255   /// (IndirectFieldDecl*) being initialized.
2256   llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2257     Initializee;
2258
2259   /// The source location for the field name or, for a base initializer
2260   /// pack expansion, the location of the ellipsis.
2261   ///
2262   /// In the case of a delegating
2263   /// constructor, it will still include the type's source location as the
2264   /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2265   SourceLocation MemberOrEllipsisLocation;
2266
2267   /// The argument used to initialize the base or member, which may
2268   /// end up constructing an object (when multiple arguments are involved).
2269   Stmt *Init;
2270
2271   /// Location of the left paren of the ctor-initializer.
2272   SourceLocation LParenLoc;
2273
2274   /// Location of the right paren of the ctor-initializer.
2275   SourceLocation RParenLoc;
2276
2277   /// If the initializee is a type, whether that type makes this
2278   /// a delegating initialization.
2279   unsigned IsDelegating : 1;
2280
2281   /// If the initializer is a base initializer, this keeps track
2282   /// of whether the base is virtual or not.
2283   unsigned IsVirtual : 1;
2284
2285   /// Whether or not the initializer is explicitly written
2286   /// in the sources.
2287   unsigned IsWritten : 1;
2288
2289   /// If IsWritten is true, then this number keeps track of the textual order
2290   /// of this initializer in the original sources, counting from 0.
2291   unsigned SourceOrder : 13;
2292
2293 public:
2294   /// Creates a new base-class initializer.
2295   explicit
2296   CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2297                      SourceLocation L, Expr *Init, SourceLocation R,
2298                      SourceLocation EllipsisLoc);
2299
2300   /// Creates a new member initializer.
2301   explicit
2302   CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2303                      SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2304                      SourceLocation R);
2305
2306   /// Creates a new anonymous field initializer.
2307   explicit
2308   CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2309                      SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2310                      SourceLocation R);
2311
2312   /// Creates a new delegating initializer.
2313   explicit
2314   CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2315                      SourceLocation L, Expr *Init, SourceLocation R);
2316
2317   /// Determine whether this initializer is initializing a base class.
2318   bool isBaseInitializer() const {
2319     return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2320   }
2321
2322   /// Determine whether this initializer is initializing a non-static
2323   /// data member.
2324   bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2325
2326   bool isAnyMemberInitializer() const {
2327     return isMemberInitializer() || isIndirectMemberInitializer();
2328   }
2329
2330   bool isIndirectMemberInitializer() const {
2331     return Initializee.is<IndirectFieldDecl*>();
2332   }
2333
2334   /// Determine whether this initializer is an implicit initializer
2335   /// generated for a field with an initializer defined on the member
2336   /// declaration.
2337   ///
2338   /// In-class member initializers (also known as "non-static data member
2339   /// initializations", NSDMIs) were introduced in C++11.
2340   bool isInClassMemberInitializer() const {
2341     return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2342   }
2343
2344   /// Determine whether this initializer is creating a delegating
2345   /// constructor.
2346   bool isDelegatingInitializer() const {
2347     return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2348   }
2349
2350   /// Determine whether this initializer is a pack expansion.
2351   bool isPackExpansion() const {
2352     return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2353   }
2354
2355   // For a pack expansion, returns the location of the ellipsis.
2356   SourceLocation getEllipsisLoc() const {
2357     assert(isPackExpansion() && "Initializer is not a pack expansion");
2358     return MemberOrEllipsisLocation;
2359   }
2360
2361   /// If this is a base class initializer, returns the type of the
2362   /// base class with location information. Otherwise, returns an NULL
2363   /// type location.
2364   TypeLoc getBaseClassLoc() const;
2365
2366   /// If this is a base class initializer, returns the type of the base class.
2367   /// Otherwise, returns null.
2368   const Type *getBaseClass() const;
2369
2370   /// Returns whether the base is virtual or not.
2371   bool isBaseVirtual() const {
2372     assert(isBaseInitializer() && "Must call this on base initializer!");
2373
2374     return IsVirtual;
2375   }
2376
2377   /// Returns the declarator information for a base class or delegating
2378   /// initializer.
2379   TypeSourceInfo *getTypeSourceInfo() const {
2380     return Initializee.dyn_cast<TypeSourceInfo *>();
2381   }
2382
2383   /// If this is a member initializer, returns the declaration of the
2384   /// non-static data member being initialized. Otherwise, returns null.
2385   FieldDecl *getMember() const {
2386     if (isMemberInitializer())
2387       return Initializee.get<FieldDecl*>();
2388     return nullptr;
2389   }
2390
2391   FieldDecl *getAnyMember() const {
2392     if (isMemberInitializer())
2393       return Initializee.get<FieldDecl*>();
2394     if (isIndirectMemberInitializer())
2395       return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2396     return nullptr;
2397   }
2398
2399   IndirectFieldDecl *getIndirectMember() const {
2400     if (isIndirectMemberInitializer())
2401       return Initializee.get<IndirectFieldDecl*>();
2402     return nullptr;
2403   }
2404
2405   SourceLocation getMemberLocation() const {
2406     return MemberOrEllipsisLocation;
2407   }
2408
2409   /// Determine the source location of the initializer.
2410   SourceLocation getSourceLocation() const;
2411
2412   /// Determine the source range covering the entire initializer.
2413   SourceRange getSourceRange() const LLVM_READONLY;
2414
2415   /// Determine whether this initializer is explicitly written
2416   /// in the source code.
2417   bool isWritten() const { return IsWritten; }
2418
2419   /// Return the source position of the initializer, counting from 0.
2420   /// If the initializer was implicit, -1 is returned.
2421   int getSourceOrder() const {
2422     return IsWritten ? static_cast<int>(SourceOrder) : -1;
2423   }
2424
2425   /// Set the source order of this initializer.
2426   ///
2427   /// This can only be called once for each initializer; it cannot be called
2428   /// on an initializer having a positive number of (implicit) array indices.
2429   ///
2430   /// This assumes that the initializer was written in the source code, and
2431   /// ensures that isWritten() returns true.
2432   void setSourceOrder(int Pos) {
2433     assert(!IsWritten &&
2434            "setSourceOrder() used on implicit initializer");
2435     assert(SourceOrder == 0 &&
2436            "calling twice setSourceOrder() on the same initializer");
2437     assert(Pos >= 0 &&
2438            "setSourceOrder() used to make an initializer implicit");
2439     IsWritten = true;
2440     SourceOrder = static_cast<unsigned>(Pos);
2441   }
2442
2443   SourceLocation getLParenLoc() const { return LParenLoc; }
2444   SourceLocation getRParenLoc() const { return RParenLoc; }
2445
2446   /// Get the initializer.
2447   Expr *getInit() const { return static_cast<Expr *>(Init); }
2448 };
2449
2450 /// Description of a constructor that was inherited from a base class.
2451 class InheritedConstructor {
2452   ConstructorUsingShadowDecl *Shadow = nullptr;
2453   CXXConstructorDecl *BaseCtor = nullptr;
2454
2455 public:
2456   InheritedConstructor() = default;
2457   InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2458                        CXXConstructorDecl *BaseCtor)
2459       : Shadow(Shadow), BaseCtor(BaseCtor) {}
2460
2461   explicit operator bool() const { return Shadow; }
2462
2463   ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2464   CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2465 };
2466
2467 /// Represents a C++ constructor within a class.
2468 ///
2469 /// For example:
2470 ///
2471 /// \code
2472 /// class X {
2473 /// public:
2474 ///   explicit X(int); // represented by a CXXConstructorDecl.
2475 /// };
2476 /// \endcode
2477 class CXXConstructorDecl final
2478     : public CXXMethodDecl,
2479       private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor> {
2480   /// \name Support for base and member initializers.
2481   /// \{
2482   /// The arguments used to initialize the base or member.
2483   LazyCXXCtorInitializersPtr CtorInitializers;
2484   unsigned NumCtorInitializers : 31;
2485   /// \}
2486
2487   /// Whether this constructor declaration is an implicitly-declared
2488   /// inheriting constructor.
2489   unsigned IsInheritingConstructor : 1;
2490
2491   CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2492                      const DeclarationNameInfo &NameInfo,
2493                      QualType T, TypeSourceInfo *TInfo,
2494                      bool isExplicitSpecified, bool isInline,
2495                      bool isImplicitlyDeclared, bool isConstexpr,
2496                      InheritedConstructor Inherited)
2497     : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2498                     SC_None, isInline, isConstexpr, SourceLocation()),
2499       NumCtorInitializers(0), IsInheritingConstructor((bool)Inherited) {
2500     setImplicit(isImplicitlyDeclared);
2501     if (Inherited)
2502       *getTrailingObjects<InheritedConstructor>() = Inherited;
2503     IsExplicitSpecified = isExplicitSpecified;
2504   }
2505
2506   void anchor() override;
2507
2508 public:
2509   friend class ASTDeclReader;
2510   friend class ASTDeclWriter;
2511   friend TrailingObjects;
2512
2513   static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2514                                                 bool InheritsConstructor);
2515   static CXXConstructorDecl *
2516   Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2517          const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2518          bool isExplicit, bool isInline, bool isImplicitlyDeclared,
2519          bool isConstexpr,
2520          InheritedConstructor Inherited = InheritedConstructor());
2521
2522   /// Iterates through the member/base initializer list.
2523   using init_iterator = CXXCtorInitializer **;
2524
2525   /// Iterates through the member/base initializer list.
2526   using init_const_iterator = CXXCtorInitializer *const *;
2527
2528   using init_range = llvm::iterator_range<init_iterator>;
2529   using init_const_range = llvm::iterator_range<init_const_iterator>;
2530
2531   init_range inits() { return init_range(init_begin(), init_end()); }
2532   init_const_range inits() const {
2533     return init_const_range(init_begin(), init_end());
2534   }
2535
2536   /// Retrieve an iterator to the first initializer.
2537   init_iterator init_begin() {
2538     const auto *ConstThis = this;
2539     return const_cast<init_iterator>(ConstThis->init_begin());
2540   }
2541
2542   /// Retrieve an iterator to the first initializer.
2543   init_const_iterator init_begin() const;
2544
2545   /// Retrieve an iterator past the last initializer.
2546   init_iterator       init_end()       {
2547     return init_begin() + NumCtorInitializers;
2548   }
2549
2550   /// Retrieve an iterator past the last initializer.
2551   init_const_iterator init_end() const {
2552     return init_begin() + NumCtorInitializers;
2553   }
2554
2555   using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2556   using init_const_reverse_iterator =
2557       std::reverse_iterator<init_const_iterator>;
2558
2559   init_reverse_iterator init_rbegin() {
2560     return init_reverse_iterator(init_end());
2561   }
2562   init_const_reverse_iterator init_rbegin() const {
2563     return init_const_reverse_iterator(init_end());
2564   }
2565
2566   init_reverse_iterator init_rend() {
2567     return init_reverse_iterator(init_begin());
2568   }
2569   init_const_reverse_iterator init_rend() const {
2570     return init_const_reverse_iterator(init_begin());
2571   }
2572
2573   /// Determine the number of arguments used to initialize the member
2574   /// or base.
2575   unsigned getNumCtorInitializers() const {
2576       return NumCtorInitializers;
2577   }
2578
2579   void setNumCtorInitializers(unsigned numCtorInitializers) {
2580     NumCtorInitializers = numCtorInitializers;
2581   }
2582
2583   void setCtorInitializers(CXXCtorInitializer **Initializers) {
2584     CtorInitializers = Initializers;
2585   }
2586
2587   /// Whether this function is marked as explicit explicitly.
2588   bool isExplicitSpecified() const { return IsExplicitSpecified; }
2589
2590   /// Whether this function is explicit.
2591   bool isExplicit() const {
2592     return getCanonicalDecl()->isExplicitSpecified();
2593   }
2594
2595   /// Determine whether this constructor is a delegating constructor.
2596   bool isDelegatingConstructor() const {
2597     return (getNumCtorInitializers() == 1) &&
2598            init_begin()[0]->isDelegatingInitializer();
2599   }
2600
2601   /// When this constructor delegates to another, retrieve the target.
2602   CXXConstructorDecl *getTargetConstructor() const;
2603
2604   /// Whether this constructor is a default
2605   /// constructor (C++ [class.ctor]p5), which can be used to
2606   /// default-initialize a class of this type.
2607   bool isDefaultConstructor() const;
2608
2609   /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2610   /// which can be used to copy the class.
2611   ///
2612   /// \p TypeQuals will be set to the qualifiers on the
2613   /// argument type. For example, \p TypeQuals would be set to \c
2614   /// Qualifiers::Const for the following copy constructor:
2615   ///
2616   /// \code
2617   /// class X {
2618   /// public:
2619   ///   X(const X&);
2620   /// };
2621   /// \endcode
2622   bool isCopyConstructor(unsigned &TypeQuals) const;
2623
2624   /// Whether this constructor is a copy
2625   /// constructor (C++ [class.copy]p2, which can be used to copy the
2626   /// class.
2627   bool isCopyConstructor() const {
2628     unsigned TypeQuals = 0;
2629     return isCopyConstructor(TypeQuals);
2630   }
2631
2632   /// Determine whether this constructor is a move constructor
2633   /// (C++11 [class.copy]p3), which can be used to move values of the class.
2634   ///
2635   /// \param TypeQuals If this constructor is a move constructor, will be set
2636   /// to the type qualifiers on the referent of the first parameter's type.
2637   bool isMoveConstructor(unsigned &TypeQuals) const;
2638
2639   /// Determine whether this constructor is a move constructor
2640   /// (C++11 [class.copy]p3), which can be used to move values of the class.
2641   bool isMoveConstructor() const {
2642     unsigned TypeQuals = 0;
2643     return isMoveConstructor(TypeQuals);
2644   }
2645
2646   /// Determine whether this is a copy or move constructor.
2647   ///
2648   /// \param TypeQuals Will be set to the type qualifiers on the reference
2649   /// parameter, if in fact this is a copy or move constructor.
2650   bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2651
2652   /// Determine whether this a copy or move constructor.
2653   bool isCopyOrMoveConstructor() const {
2654     unsigned Quals;
2655     return isCopyOrMoveConstructor(Quals);
2656   }
2657
2658   /// Whether this constructor is a
2659   /// converting constructor (C++ [class.conv.ctor]), which can be
2660   /// used for user-defined conversions.
2661   bool isConvertingConstructor(bool AllowExplicit) const;
2662
2663   /// Determine whether this is a member template specialization that
2664   /// would copy the object to itself. Such constructors are never used to copy
2665   /// an object.
2666   bool isSpecializationCopyingObject() const;
2667
2668   /// Determine whether this is an implicit constructor synthesized to
2669   /// model a call to a constructor inherited from a base class.
2670   bool isInheritingConstructor() const { return IsInheritingConstructor; }
2671
2672   /// Get the constructor that this inheriting constructor is based on.
2673   InheritedConstructor getInheritedConstructor() const {
2674     return IsInheritingConstructor ? *getTrailingObjects<InheritedConstructor>()
2675                                    : InheritedConstructor();
2676   }
2677
2678   CXXConstructorDecl *getCanonicalDecl() override {
2679     return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2680   }
2681   const CXXConstructorDecl *getCanonicalDecl() const {
2682     return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2683   }
2684
2685   // Implement isa/cast/dyncast/etc.
2686   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2687   static bool classofKind(Kind K) { return K == CXXConstructor; }
2688 };
2689
2690 /// Represents a C++ destructor within a class.
2691 ///
2692 /// For example:
2693 ///
2694 /// \code
2695 /// class X {
2696 /// public:
2697 ///   ~X(); // represented by a CXXDestructorDecl.
2698 /// };
2699 /// \endcode
2700 class CXXDestructorDecl : public CXXMethodDecl {
2701   friend class ASTDeclReader;
2702   friend class ASTDeclWriter;
2703
2704   // FIXME: Don't allocate storage for these except in the first declaration
2705   // of a virtual destructor.
2706   FunctionDecl *OperatorDelete = nullptr;
2707   Expr *OperatorDeleteThisArg = nullptr;
2708
2709   CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2710                     const DeclarationNameInfo &NameInfo,
2711                     QualType T, TypeSourceInfo *TInfo,
2712                     bool isInline, bool isImplicitlyDeclared)
2713     : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2714                     SC_None, isInline, /*isConstexpr=*/false, SourceLocation())
2715   {
2716     setImplicit(isImplicitlyDeclared);
2717   }
2718
2719   void anchor() override;
2720
2721 public:
2722   static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2723                                    SourceLocation StartLoc,
2724                                    const DeclarationNameInfo &NameInfo,
2725                                    QualType T, TypeSourceInfo* TInfo,
2726                                    bool isInline,
2727                                    bool isImplicitlyDeclared);
2728   static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2729
2730   void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2731
2732   const FunctionDecl *getOperatorDelete() const {
2733     return getCanonicalDecl()->OperatorDelete;
2734   }
2735
2736   Expr *getOperatorDeleteThisArg() const {
2737     return getCanonicalDecl()->OperatorDeleteThisArg;
2738   }
2739
2740   CXXDestructorDecl *getCanonicalDecl() override {
2741     return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2742   }
2743   const CXXDestructorDecl *getCanonicalDecl() const {
2744     return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2745   }
2746
2747   // Implement isa/cast/dyncast/etc.
2748   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2749   static bool classofKind(Kind K) { return K == CXXDestructor; }
2750 };
2751
2752 /// Represents a C++ conversion function within a class.
2753 ///
2754 /// For example:
2755 ///
2756 /// \code
2757 /// class X {
2758 /// public:
2759 ///   operator bool();
2760 /// };
2761 /// \endcode
2762 class CXXConversionDecl : public CXXMethodDecl {
2763   CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2764                     const DeclarationNameInfo &NameInfo, QualType T,
2765                     TypeSourceInfo *TInfo, bool isInline,
2766                     bool isExplicitSpecified, bool isConstexpr,
2767                     SourceLocation EndLocation)
2768       : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2769                       SC_None, isInline, isConstexpr, EndLocation) {
2770     IsExplicitSpecified = isExplicitSpecified;
2771   }
2772
2773   void anchor() override;
2774
2775 public:
2776   friend class ASTDeclReader;
2777   friend class ASTDeclWriter;
2778
2779   static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2780                                    SourceLocation StartLoc,
2781                                    const DeclarationNameInfo &NameInfo,
2782                                    QualType T, TypeSourceInfo *TInfo,
2783                                    bool isInline, bool isExplicit,
2784                                    bool isConstexpr,
2785                                    SourceLocation EndLocation);
2786   static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2787
2788   /// Whether this function is marked as explicit explicitly.
2789   bool isExplicitSpecified() const { return IsExplicitSpecified; }
2790
2791   /// Whether this function is explicit.
2792   bool isExplicit() const {
2793     return getCanonicalDecl()->isExplicitSpecified();
2794   }
2795
2796   /// Returns the type that this conversion function is converting to.
2797   QualType getConversionType() const {
2798     return getType()->getAs<FunctionType>()->getReturnType();
2799   }
2800
2801   /// Determine whether this conversion function is a conversion from
2802   /// a lambda closure type to a block pointer.
2803   bool isLambdaToBlockPointerConversion() const;
2804
2805   CXXConversionDecl *getCanonicalDecl() override {
2806     return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2807   }
2808   const CXXConversionDecl *getCanonicalDecl() const {
2809     return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2810   }
2811
2812   // Implement isa/cast/dyncast/etc.
2813   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2814   static bool classofKind(Kind K) { return K == CXXConversion; }
2815 };
2816
2817 /// Represents a linkage specification.
2818 ///
2819 /// For example:
2820 /// \code
2821 ///   extern "C" void foo();
2822 /// \endcode
2823 class LinkageSpecDecl : public Decl, public DeclContext {
2824   virtual void anchor();
2825
2826 public:
2827   /// Represents the language in a linkage specification.
2828   ///
2829   /// The values are part of the serialization ABI for
2830   /// ASTs and cannot be changed without altering that ABI.  To help
2831   /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2832   /// from the dwarf standard.
2833   enum LanguageIDs {
2834     lang_c = /* DW_LANG_C */ 0x0002,
2835     lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004
2836   };
2837
2838 private:
2839   /// The language for this linkage specification.
2840   unsigned Language : 3;
2841
2842   /// True if this linkage spec has braces.
2843   ///
2844   /// This is needed so that hasBraces() returns the correct result while the
2845   /// linkage spec body is being parsed.  Once RBraceLoc has been set this is
2846   /// not used, so it doesn't need to be serialized.
2847   unsigned HasBraces : 1;
2848
2849   /// The source location for the extern keyword.
2850   SourceLocation ExternLoc;
2851
2852   /// The source location for the right brace (if valid).
2853   SourceLocation RBraceLoc;
2854
2855   LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2856                   SourceLocation LangLoc, LanguageIDs lang, bool HasBraces)
2857       : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2858         Language(lang), HasBraces(HasBraces), ExternLoc(ExternLoc),
2859         RBraceLoc(SourceLocation()) {}
2860
2861 public:
2862   static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2863                                  SourceLocation ExternLoc,
2864                                  SourceLocation LangLoc, LanguageIDs Lang,
2865                                  bool HasBraces);
2866   static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2867
2868   /// Return the language specified by this linkage specification.
2869   LanguageIDs getLanguage() const { return LanguageIDs(Language); }
2870
2871   /// Set the language specified by this linkage specification.
2872   void setLanguage(LanguageIDs L) { Language = L; }
2873
2874   /// Determines whether this linkage specification had braces in
2875   /// its syntactic form.
2876   bool hasBraces() const {
2877     assert(!RBraceLoc.isValid() || HasBraces);
2878     return HasBraces;
2879   }
2880
2881   SourceLocation getExternLoc() const { return ExternLoc; }
2882   SourceLocation getRBraceLoc() const { return RBraceLoc; }
2883   void setExternLoc(SourceLocation L) { ExternLoc = L; }
2884   void setRBraceLoc(SourceLocation L) {
2885     RBraceLoc = L;
2886     HasBraces = RBraceLoc.isValid();
2887   }
2888
2889   SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2890   SourceLocation getEndLoc() const LLVM_READONLY {
2891     if (hasBraces())
2892       return getRBraceLoc();
2893     // No braces: get the end location of the (only) declaration in context
2894     // (if present).
2895     return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
2896   }
2897
2898   SourceRange getSourceRange() const override LLVM_READONLY {
2899     return SourceRange(ExternLoc, getLocEnd());
2900   }
2901
2902   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2903   static bool classofKind(Kind K) { return K == LinkageSpec; }
2904
2905   static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2906     return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2907   }
2908
2909   static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2910     return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2911   }
2912 };
2913
2914 /// Represents C++ using-directive.
2915 ///
2916 /// For example:
2917 /// \code
2918 ///    using namespace std;
2919 /// \endcode
2920 ///
2921 /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2922 /// artificial names for all using-directives in order to store
2923 /// them in DeclContext effectively.
2924 class UsingDirectiveDecl : public NamedDecl {
2925   /// The location of the \c using keyword.
2926   SourceLocation UsingLoc;
2927
2928   /// The location of the \c namespace keyword.
2929   SourceLocation NamespaceLoc;
2930
2931   /// The nested-name-specifier that precedes the namespace.
2932   NestedNameSpecifierLoc QualifierLoc;
2933
2934   /// The namespace nominated by this using-directive.
2935   NamedDecl *NominatedNamespace;
2936
2937   /// Enclosing context containing both using-directive and nominated
2938   /// namespace.
2939   DeclContext *CommonAncestor;
2940
2941   UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2942                      SourceLocation NamespcLoc,
2943                      NestedNameSpecifierLoc QualifierLoc,
2944                      SourceLocation IdentLoc,
2945                      NamedDecl *Nominated,
2946                      DeclContext *CommonAncestor)
2947       : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2948         NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2949         NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2950
2951   /// Returns special DeclarationName used by using-directives.
2952   ///
2953   /// This is only used by DeclContext for storing UsingDirectiveDecls in
2954   /// its lookup structure.
2955   static DeclarationName getName() {
2956     return DeclarationName::getUsingDirectiveName();
2957   }
2958
2959   void anchor() override;
2960
2961 public:
2962   friend class ASTDeclReader;
2963
2964   // Friend for getUsingDirectiveName.
2965   friend class DeclContext;
2966
2967   /// Retrieve the nested-name-specifier that qualifies the
2968   /// name of the namespace, with source-location information.
2969   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2970
2971   /// Retrieve the nested-name-specifier that qualifies the
2972   /// name of the namespace.
2973   NestedNameSpecifier *getQualifier() const {
2974     return QualifierLoc.getNestedNameSpecifier();
2975   }
2976
2977   NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2978   const NamedDecl *getNominatedNamespaceAsWritten() const {
2979     return NominatedNamespace;
2980   }
2981
2982   /// Returns the namespace nominated by this using-directive.
2983   NamespaceDecl *getNominatedNamespace();
2984
2985   const NamespaceDecl *getNominatedNamespace() const {
2986     return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2987   }
2988
2989   /// Returns the common ancestor context of this using-directive and
2990   /// its nominated namespace.
2991   DeclContext *getCommonAncestor() { return CommonAncestor; }
2992   const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2993
2994   /// Return the location of the \c using keyword.
2995   SourceLocation getUsingLoc() const { return UsingLoc; }
2996
2997   // FIXME: Could omit 'Key' in name.
2998   /// Returns the location of the \c namespace keyword.
2999   SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3000
3001   /// Returns the location of this using declaration's identifier.
3002   SourceLocation getIdentLocation() const { return getLocation(); }
3003
3004   static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3005                                     SourceLocation UsingLoc,
3006                                     SourceLocation NamespaceLoc,
3007                                     NestedNameSpecifierLoc QualifierLoc,
3008                                     SourceLocation IdentLoc,
3009                                     NamedDecl *Nominated,
3010                                     DeclContext *CommonAncestor);
3011   static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3012
3013   SourceRange getSourceRange() const override LLVM_READONLY {
3014     return SourceRange(UsingLoc, getLocation());
3015   }
3016
3017   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3018   static bool classofKind(Kind K) { return K == UsingDirective; }
3019 };
3020
3021 /// Represents a C++ namespace alias.
3022 ///
3023 /// For example:
3024 ///
3025 /// \code
3026 /// namespace Foo = Bar;
3027 /// \endcode
3028 class NamespaceAliasDecl : public NamedDecl,
3029                            public Redeclarable<NamespaceAliasDecl> {
3030   friend class ASTDeclReader;
3031
3032   /// The location of the \c namespace keyword.
3033   SourceLocation NamespaceLoc;
3034
3035   /// The location of the namespace's identifier.
3036   ///
3037   /// This is accessed by TargetNameLoc.
3038   SourceLocation IdentLoc;
3039
3040   /// The nested-name-specifier that precedes the namespace.
3041   NestedNameSpecifierLoc QualifierLoc;
3042
3043   /// The Decl that this alias points to, either a NamespaceDecl or
3044   /// a NamespaceAliasDecl.
3045   NamedDecl *Namespace;
3046
3047   NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3048                      SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3049                      IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3050                      SourceLocation IdentLoc, NamedDecl *Namespace)
3051       : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3052         NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3053         QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3054
3055   void anchor() override;
3056
3057   using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3058
3059   NamespaceAliasDecl *getNextRedeclarationImpl() override;
3060   NamespaceAliasDecl *getPreviousDeclImpl() override;
3061   NamespaceAliasDecl *getMostRecentDeclImpl() override;
3062
3063 public:
3064   static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3065                                     SourceLocation NamespaceLoc,
3066                                     SourceLocation AliasLoc,
3067                                     IdentifierInfo *Alias,
3068                                     NestedNameSpecifierLoc QualifierLoc,
3069                                     SourceLocation IdentLoc,
3070                                     NamedDecl *Namespace);
3071
3072   static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3073
3074   using redecl_range = redeclarable_base::redecl_range;
3075   using redecl_iterator = redeclarable_base::redecl_iterator;
3076
3077   using redeclarable_base::redecls_begin;
3078   using redeclarable_base::redecls_end;
3079   using redeclarable_base::redecls;
3080   using redeclarable_base::getPreviousDecl;
3081   using redeclarable_base::getMostRecentDecl;
3082
3083   NamespaceAliasDecl *getCanonicalDecl() override {
3084     return getFirstDecl();
3085   }
3086   const NamespaceAliasDecl *getCanonicalDecl() const {
3087     return getFirstDecl();
3088   }
3089
3090   /// Retrieve the nested-name-specifier that qualifies the
3091   /// name of the namespace, with source-location information.
3092   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3093
3094   /// Retrieve the nested-name-specifier that qualifies the
3095   /// name of the namespace.
3096   NestedNameSpecifier *getQualifier() const {
3097     return QualifierLoc.getNestedNameSpecifier();
3098   }
3099
3100   /// Retrieve the namespace declaration aliased by this directive.
3101   NamespaceDecl *getNamespace() {
3102     if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3103       return AD->getNamespace();
3104
3105     return cast<NamespaceDecl>(Namespace);
3106   }
3107
3108   const NamespaceDecl *getNamespace() const {
3109     return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3110   }
3111
3112   /// Returns the location of the alias name, i.e. 'foo' in
3113   /// "namespace foo = ns::bar;".
3114   SourceLocation getAliasLoc() const { return getLocation(); }
3115
3116   /// Returns the location of the \c namespace keyword.
3117   SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3118
3119   /// Returns the location of the identifier in the named namespace.
3120   SourceLocation getTargetNameLoc() const { return IdentLoc; }
3121
3122   /// Retrieve the namespace that this alias refers to, which
3123   /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3124   NamedDecl *getAliasedNamespace() const { return Namespace; }
3125
3126   SourceRange getSourceRange() const override LLVM_READONLY {
3127     return SourceRange(NamespaceLoc, IdentLoc);
3128   }
3129
3130   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3131   static bool classofKind(Kind K) { return K == NamespaceAlias; }
3132 };
3133
3134 /// Represents a shadow declaration introduced into a scope by a
3135 /// (resolved) using declaration.
3136 ///
3137 /// For example,
3138 /// \code
3139 /// namespace A {
3140 ///   void foo();
3141 /// }
3142 /// namespace B {
3143 ///   using A::foo; // <- a UsingDecl
3144 ///                 // Also creates a UsingShadowDecl for A::foo() in B
3145 /// }
3146 /// \endcode
3147 class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3148   friend class UsingDecl;
3149
3150   /// The referenced declaration.
3151   NamedDecl *Underlying = nullptr;
3152
3153   /// The using declaration which introduced this decl or the next using
3154   /// shadow declaration contained in the aforementioned using declaration.
3155   NamedDecl *UsingOrNextShadow = nullptr;
3156
3157   void anchor() override;
3158
3159   using redeclarable_base = Redeclarable<UsingShadowDecl>;
3160
3161   UsingShadowDecl *getNextRedeclarationImpl() override {
3162     return getNextRedeclaration();
3163   }
3164
3165   UsingShadowDecl *getPreviousDeclImpl() override {
3166     return getPreviousDecl();
3167   }
3168
3169   UsingShadowDecl *getMostRecentDeclImpl() override {
3170     return getMostRecentDecl();
3171   }
3172
3173 protected:
3174   UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3175                   UsingDecl *Using, NamedDecl *Target);
3176   UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3177
3178 public:
3179   friend class ASTDeclReader;
3180   friend class ASTDeclWriter;
3181
3182   static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3183                                  SourceLocation Loc, UsingDecl *Using,
3184                                  NamedDecl *Target) {
3185     return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3186   }
3187
3188   static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3189
3190   using redecl_range = redeclarable_base::redecl_range;
3191   using redecl_iterator = redeclarable_base::redecl_iterator;
3192
3193   using redeclarable_base::redecls_begin;
3194   using redeclarable_base::redecls_end;
3195   using redeclarable_base::redecls;
3196   using redeclarable_base::getPreviousDecl;
3197   using redeclarable_base::getMostRecentDecl;
3198   using redeclarable_base::isFirstDecl;
3199
3200   UsingShadowDecl *getCanonicalDecl() override {
3201     return getFirstDecl();
3202   }
3203   const UsingShadowDecl *getCanonicalDecl() const {
3204     return getFirstDecl();
3205   }
3206
3207   /// Gets the underlying declaration which has been brought into the
3208   /// local scope.
3209   NamedDecl *getTargetDecl() const { return Underlying; }
3210
3211   /// Sets the underlying declaration which has been brought into the
3212   /// local scope.
3213   void setTargetDecl(NamedDecl *ND) {
3214     assert(ND && "Target decl is null!");
3215     Underlying = ND;
3216     // A UsingShadowDecl is never a friend or local extern declaration, even
3217     // if it is a shadow declaration for one.
3218     IdentifierNamespace =
3219         ND->getIdentifierNamespace() &
3220         ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3221   }
3222
3223   /// Gets the using declaration to which this declaration is tied.
3224   UsingDecl *getUsingDecl() const;
3225
3226   /// The next using shadow declaration contained in the shadow decl
3227   /// chain of the using declaration which introduced this decl.
3228   UsingShadowDecl *getNextUsingShadowDecl() const {
3229     return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3230   }
3231
3232   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3233   static bool classofKind(Kind K) {
3234     return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3235   }
3236 };
3237
3238 /// Represents a shadow constructor declaration introduced into a
3239 /// class by a C++11 using-declaration that names a constructor.
3240 ///
3241 /// For example:
3242 /// \code
3243 /// struct Base { Base(int); };
3244 /// struct Derived {
3245 ///    using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3246 /// };
3247 /// \endcode
3248 class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3249   /// If this constructor using declaration inherted the constructor
3250   /// from an indirect base class, this is the ConstructorUsingShadowDecl
3251   /// in the named direct base class from which the declaration was inherited.
3252   ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3253
3254   /// If this constructor using declaration inherted the constructor
3255   /// from an indirect base class, this is the ConstructorUsingShadowDecl
3256   /// that will be used to construct the unique direct or virtual base class
3257   /// that receives the constructor arguments.
3258   ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3259
3260   /// \c true if the constructor ultimately named by this using shadow
3261   /// declaration is within a virtual base class subobject of the class that
3262   /// contains this declaration.
3263   unsigned IsVirtual : 1;
3264
3265   ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3266                              UsingDecl *Using, NamedDecl *Target,
3267                              bool TargetInVirtualBase)
3268       : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3269                         Target->getUnderlyingDecl()),
3270         NominatedBaseClassShadowDecl(
3271             dyn_cast<ConstructorUsingShadowDecl>(Target)),
3272         ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3273         IsVirtual(TargetInVirtualBase) {
3274     // If we found a constructor that chains to a constructor for a virtual
3275     // base, we should directly call that virtual base constructor instead.
3276     // FIXME: This logic belongs in Sema.
3277     if (NominatedBaseClassShadowDecl &&
3278         NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3279       ConstructedBaseClassShadowDecl =
3280           NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3281       IsVirtual = true;
3282     }
3283   }
3284
3285   ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3286       : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3287
3288   void anchor() override;
3289
3290 public:
3291   friend class ASTDeclReader;
3292   friend class ASTDeclWriter;
3293
3294   static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3295                                             SourceLocation Loc,
3296                                             UsingDecl *Using, NamedDecl *Target,
3297                                             bool IsVirtual);
3298   static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3299                                                         unsigned ID);
3300
3301   /// Returns the parent of this using shadow declaration, which
3302   /// is the class in which this is declared.
3303   //@{
3304   const CXXRecordDecl *getParent() const {
3305     return cast<CXXRecordDecl>(getDeclContext());
3306   }
3307   CXXRecordDecl *getParent() {
3308     return cast<CXXRecordDecl>(getDeclContext());
3309   }
3310   //@}
3311
3312   /// Get the inheriting constructor declaration for the direct base
3313   /// class from which this using shadow declaration was inherited, if there is
3314   /// one. This can be different for each redeclaration of the same shadow decl.
3315   ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3316     return NominatedBaseClassShadowDecl;
3317   }
3318
3319   /// Get the inheriting constructor declaration for the base class
3320   /// for which we don't have an explicit initializer, if there is one.
3321   ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3322     return ConstructedBaseClassShadowDecl;
3323   }
3324
3325   /// Get the base class that was named in the using declaration. This
3326   /// can be different for each redeclaration of this same shadow decl.
3327   CXXRecordDecl *getNominatedBaseClass() const;
3328
3329   /// Get the base class whose constructor or constructor shadow
3330   /// declaration is passed the constructor arguments.
3331   CXXRecordDecl *getConstructedBaseClass() const {
3332     return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3333                                     ? ConstructedBaseClassShadowDecl
3334                                     : getTargetDecl())
3335                                    ->getDeclContext());
3336   }
3337
3338   /// Returns \c true if the constructed base class is a virtual base
3339   /// class subobject of this declaration's class.
3340   bool constructsVirtualBase() const {
3341     return IsVirtual;
3342   }
3343
3344   /// Get the constructor or constructor template in the derived class
3345   /// correspnding to this using shadow declaration, if it has been implicitly
3346   /// declared already.
3347   CXXConstructorDecl *getConstructor() const;
3348   void setConstructor(NamedDecl *Ctor);
3349
3350   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3351   static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3352 };
3353
3354 /// Represents a C++ using-declaration.
3355 ///
3356 /// For example:
3357 /// \code
3358 ///    using someNameSpace::someIdentifier;
3359 /// \endcode
3360 class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3361   /// The source location of the 'using' keyword itself.
3362   SourceLocation UsingLocation;
3363
3364   /// The nested-name-specifier that precedes the name.
3365   NestedNameSpecifierLoc QualifierLoc;
3366
3367   /// Provides source/type location info for the declaration name
3368   /// embedded in the ValueDecl base class.
3369   DeclarationNameLoc DNLoc;
3370
3371   /// The first shadow declaration of the shadow decl chain associated
3372   /// with this using declaration.
3373   ///
3374   /// The bool member of the pair store whether this decl has the \c typename
3375   /// keyword.
3376   llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3377
3378   UsingDecl(DeclContext *DC, SourceLocation UL,
3379             NestedNameSpecifierLoc QualifierLoc,
3380             const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3381     : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3382       UsingLocation(UL), QualifierLoc(QualifierLoc),
3383       DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3384   }
3385
3386   void anchor() override;
3387
3388 public:
3389   friend class ASTDeclReader;
3390   friend class ASTDeclWriter;
3391
3392   /// Return the source location of the 'using' keyword.
3393   SourceLocation getUsingLoc() const { return UsingLocation; }
3394
3395   /// Set the source location of the 'using' keyword.
3396   void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3397
3398   /// Retrieve the nested-name-specifier that qualifies the name,
3399   /// with source-location information.
3400   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3401
3402   /// Retrieve the nested-name-specifier that qualifies the name.
3403   NestedNameSpecifier *getQualifier() const {
3404     return QualifierLoc.getNestedNameSpecifier();
3405   }
3406
3407   DeclarationNameInfo getNameInfo() const {
3408     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3409   }
3410
3411   /// Return true if it is a C++03 access declaration (no 'using').
3412   bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3413
3414   /// Return true if the using declaration has 'typename'.
3415   bool hasTypename() const { return FirstUsingShadow.getInt(); }
3416
3417   /// Sets whether the using declaration has 'typename'.
3418   void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3419
3420   /// Iterates through the using shadow declarations associated with
3421   /// this using declaration.
3422   class shadow_iterator {
3423     /// The current using shadow declaration.
3424     UsingShadowDecl *Current = nullptr;
3425
3426   public:
3427     using value_type = UsingShadowDecl *;
3428     using reference = UsingShadowDecl *;
3429     using pointer = UsingShadowDecl *;
3430     using iterator_category = std::forward_iterator_tag;
3431     using difference_type = std::ptrdiff_t;
3432
3433     shadow_iterator() = default;
3434     explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3435
3436     reference operator*() const { return Current; }
3437     pointer operator->() const { return Current; }
3438
3439     shadow_iterator& operator++() {
3440       Current = Current->getNextUsingShadowDecl();
3441       return *this;
3442     }
3443
3444     shadow_iterator operator++(int) {
3445       shadow_iterator tmp(*this);
3446       ++(*this);
3447       return tmp;
3448     }
3449
3450     friend bool operator==(shadow_iterator x, shadow_iterator y) {
3451       return x.Current == y.Current;
3452     }
3453     friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3454       return x.Current != y.Current;
3455     }
3456   };
3457
3458   using shadow_range = llvm::iterator_range<shadow_iterator>;
3459
3460   shadow_range shadows() const {
3461     return shadow_range(shadow_begin(), shadow_end());
3462   }
3463
3464   shadow_iterator shadow_begin() const {
3465     return shadow_iterator(FirstUsingShadow.getPointer());
3466   }
3467
3468   shadow_iterator shadow_end() const { return shadow_iterator(); }
3469
3470   /// Return the number of shadowed declarations associated with this
3471   /// using declaration.
3472   unsigned shadow_size() const {
3473     return std::distance(shadow_begin(), shadow_end());
3474   }
3475
3476   void addShadowDecl(UsingShadowDecl *S);
3477   void removeShadowDecl(UsingShadowDecl *S);
3478
3479   static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3480                            SourceLocation UsingL,
3481                            NestedNameSpecifierLoc QualifierLoc,
3482                            const DeclarationNameInfo &NameInfo,
3483                            bool HasTypenameKeyword);
3484
3485   static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3486
3487   SourceRange getSourceRange() const override LLVM_READONLY;
3488
3489   /// Retrieves the canonical declaration of this declaration.
3490   UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3491   const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3492
3493   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3494   static bool classofKind(Kind K) { return K == Using; }
3495 };
3496
3497 /// Represents a pack of using declarations that a single
3498 /// using-declarator pack-expanded into.
3499 ///
3500 /// \code
3501 /// template<typename ...T> struct X : T... {
3502 ///   using T::operator()...;
3503 ///   using T::operator T...;
3504 /// };
3505 /// \endcode
3506 ///
3507 /// In the second case above, the UsingPackDecl will have the name
3508 /// 'operator T' (which contains an unexpanded pack), but the individual
3509 /// UsingDecls and UsingShadowDecls will have more reasonable names.
3510 class UsingPackDecl final
3511     : public NamedDecl, public Mergeable<UsingPackDecl>,
3512       private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3513   /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3514   /// which this waas instantiated.
3515   NamedDecl *InstantiatedFrom;
3516
3517   /// The number of using-declarations created by this pack expansion.
3518   unsigned NumExpansions;
3519
3520   UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3521                 ArrayRef<NamedDecl *> UsingDecls)
3522       : NamedDecl(UsingPack, DC,
3523                   InstantiatedFrom ? InstantiatedFrom->getLocation()
3524                                    : SourceLocation(),
3525                   InstantiatedFrom ? InstantiatedFrom->getDeclName()
3526                                    : DeclarationName()),
3527         InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3528     std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3529                             getTrailingObjects<NamedDecl *>());
3530   }
3531
3532   void anchor() override;
3533
3534 public:
3535   friend class ASTDeclReader;
3536   friend class ASTDeclWriter;
3537   friend TrailingObjects;
3538
3539   /// Get the using declaration from which this was instantiated. This will
3540   /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3541   /// that is a pack expansion.
3542   NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3543
3544   /// Get the set of using declarations that this pack expanded into. Note that
3545   /// some of these may still be unresolved.
3546   ArrayRef<NamedDecl *> expansions() const {
3547     return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3548   }
3549
3550   static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3551                                NamedDecl *InstantiatedFrom,
3552                                ArrayRef<NamedDecl *> UsingDecls);
3553
3554   static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3555                                            unsigned NumExpansions);
3556
3557   SourceRange getSourceRange() const override LLVM_READONLY {
3558     return InstantiatedFrom->getSourceRange();
3559   }
3560
3561   UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3562   const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3563
3564   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3565   static bool classofKind(Kind K) { return K == UsingPack; }
3566 };
3567
3568 /// Represents a dependent using declaration which was not marked with
3569 /// \c typename.
3570 ///
3571 /// Unlike non-dependent using declarations, these *only* bring through
3572 /// non-types; otherwise they would break two-phase lookup.
3573 ///
3574 /// \code
3575 /// template \<class T> class A : public Base<T> {
3576 ///   using Base<T>::foo;
3577 /// };
3578 /// \endcode
3579 class UnresolvedUsingValueDecl : public ValueDecl,
3580                                  public Mergeable<UnresolvedUsingValueDecl> {
3581   /// The source location of the 'using' keyword
3582   SourceLocation UsingLocation;
3583
3584   /// If this is a pack expansion, the location of the '...'.
3585   SourceLocation EllipsisLoc;
3586
3587   /// The nested-name-specifier that precedes the name.
3588   NestedNameSpecifierLoc QualifierLoc;
3589
3590   /// Provides source/type location info for the declaration name
3591   /// embedded in the ValueDecl base class.
3592   DeclarationNameLoc DNLoc;
3593
3594   UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3595                            SourceLocation UsingLoc,
3596                            NestedNameSpecifierLoc QualifierLoc,
3597                            const DeclarationNameInfo &NameInfo,
3598                            SourceLocation EllipsisLoc)
3599       : ValueDecl(UnresolvedUsingValue, DC,
3600                   NameInfo.getLoc(), NameInfo.getName(), Ty),
3601         UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3602         QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3603
3604   void anchor() override;
3605
3606 public:
3607   friend class ASTDeclReader;
3608   friend class ASTDeclWriter;
3609
3610   /// Returns the source location of the 'using' keyword.
3611   SourceLocation getUsingLoc() const { return UsingLocation; }
3612
3613   /// Set the source location of the 'using' keyword.
3614   void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3615
3616   /// Return true if it is a C++03 access declaration (no 'using').
3617   bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3618
3619   /// Retrieve the nested-name-specifier that qualifies the name,
3620   /// with source-location information.
3621   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3622
3623   /// Retrieve the nested-name-specifier that qualifies the name.
3624   NestedNameSpecifier *getQualifier() const {
3625     return QualifierLoc.getNestedNameSpecifier();
3626   }
3627
3628   DeclarationNameInfo getNameInfo() const {
3629     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3630   }
3631
3632   /// Determine whether this is a pack expansion.
3633   bool isPackExpansion() const {
3634     return EllipsisLoc.isValid();
3635   }
3636
3637   /// Get the location of the ellipsis if this is a pack expansion.
3638   SourceLocation getEllipsisLoc() const {
3639     return EllipsisLoc;
3640   }
3641
3642   static UnresolvedUsingValueDecl *
3643     Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3644            NestedNameSpecifierLoc QualifierLoc,
3645            const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3646
3647   static UnresolvedUsingValueDecl *
3648   CreateDeserialized(ASTContext &C, unsigned ID);
3649
3650   SourceRange getSourceRange() const override LLVM_READONLY;
3651
3652   /// Retrieves the canonical declaration of this declaration.
3653   UnresolvedUsingValueDecl *getCanonicalDecl() override {
3654     return getFirstDecl();
3655   }
3656   const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3657     return getFirstDecl();
3658   }
3659
3660   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3661   static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3662 };
3663
3664 /// Represents a dependent using declaration which was marked with
3665 /// \c typename.
3666 ///
3667 /// \code
3668 /// template \<class T> class A : public Base<T> {
3669 ///   using typename Base<T>::foo;
3670 /// };
3671 /// \endcode
3672 ///
3673 /// The type associated with an unresolved using typename decl is
3674 /// currently always a typename type.
3675 class UnresolvedUsingTypenameDecl
3676     : public TypeDecl,
3677       public Mergeable<UnresolvedUsingTypenameDecl> {
3678   friend class ASTDeclReader;
3679
3680   /// The source location of the 'typename' keyword
3681   SourceLocation TypenameLocation;
3682
3683   /// If this is a pack expansion, the location of the '...'.
3684   SourceLocation EllipsisLoc;
3685
3686   /// The nested-name-specifier that precedes the name.
3687   NestedNameSpecifierLoc QualifierLoc;
3688
3689   UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3690                               SourceLocation TypenameLoc,
3691                               NestedNameSpecifierLoc QualifierLoc,
3692                               SourceLocation TargetNameLoc,
3693                               IdentifierInfo *TargetName,
3694                               SourceLocation EllipsisLoc)
3695     : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3696                UsingLoc),
3697       TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3698       QualifierLoc(QualifierLoc) {}
3699
3700   void anchor() override;
3701
3702 public:
3703   /// Returns the source location of the 'using' keyword.
3704   SourceLocation getUsingLoc() const { return getLocStart(); }
3705
3706   /// Returns the source location of the 'typename' keyword.
3707   SourceLocation getTypenameLoc() const { return TypenameLocation; }
3708
3709   /// Retrieve the nested-name-specifier that qualifies the name,
3710   /// with source-location information.
3711   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3712
3713   /// Retrieve the nested-name-specifier that qualifies the name.
3714   NestedNameSpecifier *getQualifier() const {
3715     return QualifierLoc.getNestedNameSpecifier();
3716   }
3717
3718   DeclarationNameInfo getNameInfo() const {
3719     return DeclarationNameInfo(getDeclName(), getLocation());
3720   }
3721
3722   /// Determine whether this is a pack expansion.
3723   bool isPackExpansion() const {
3724     return EllipsisLoc.isValid();
3725   }
3726
3727   /// Get the location of the ellipsis if this is a pack expansion.
3728   SourceLocation getEllipsisLoc() const {
3729     return EllipsisLoc;
3730   }
3731
3732   static UnresolvedUsingTypenameDecl *
3733     Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3734            SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3735            SourceLocation TargetNameLoc, DeclarationName TargetName,
3736            SourceLocation EllipsisLoc);
3737
3738   static UnresolvedUsingTypenameDecl *
3739   CreateDeserialized(ASTContext &C, unsigned ID);
3740
3741   /// Retrieves the canonical declaration of this declaration.
3742   UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3743     return getFirstDecl();
3744   }
3745   const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3746     return getFirstDecl();
3747   }
3748
3749   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3750   static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3751 };
3752
3753 /// Represents a C++11 static_assert declaration.
3754 class StaticAssertDecl : public Decl {
3755   llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3756   StringLiteral *Message;
3757   SourceLocation RParenLoc;
3758
3759   StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3760                    Expr *AssertExpr, StringLiteral *Message,
3761                    SourceLocation RParenLoc, bool Failed)
3762       : Decl(StaticAssert, DC, StaticAssertLoc),
3763         AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3764         RParenLoc(RParenLoc) {}
3765
3766   virtual void anchor();
3767
3768 public:
3769   friend class ASTDeclReader;
3770
3771   static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3772                                   SourceLocation StaticAssertLoc,
3773                                   Expr *AssertExpr, StringLiteral *Message,
3774                                   SourceLocation RParenLoc, bool Failed);
3775   static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3776
3777   Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3778   const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3779
3780   StringLiteral *getMessage() { return Message; }
3781   const StringLiteral *getMessage() const { return Message; }
3782
3783   bool isFailed() const { return AssertExprAndFailed.getInt(); }
3784
3785   SourceLocation getRParenLoc() const { return RParenLoc; }
3786
3787   SourceRange getSourceRange() const override LLVM_READONLY {
3788     return SourceRange(getLocation(), getRParenLoc());
3789   }
3790
3791   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3792   static bool classofKind(Kind K) { return K == StaticAssert; }
3793 };
3794
3795 /// A binding in a decomposition declaration. For instance, given:
3796 ///
3797 ///   int n[3];
3798 ///   auto &[a, b, c] = n;
3799 ///
3800 /// a, b, and c are BindingDecls, whose bindings are the expressions
3801 /// x[0], x[1], and x[2] respectively, where x is the implicit
3802 /// DecompositionDecl of type 'int (&)[3]'.
3803 class BindingDecl : public ValueDecl {
3804   /// The binding represented by this declaration. References to this
3805   /// declaration are effectively equivalent to this expression (except
3806   /// that it is only evaluated once at the point of declaration of the
3807   /// binding).
3808   Expr *Binding = nullptr;
3809
3810   BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3811       : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3812
3813   void anchor() override;
3814
3815 public:
3816   friend class ASTDeclReader;
3817
3818   static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3819                              SourceLocation IdLoc, IdentifierInfo *Id);
3820   static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3821
3822   /// Get the expression to which this declaration is bound. This may be null
3823   /// in two different cases: while parsing the initializer for the
3824   /// decomposition declaration, and when the initializer is type-dependent.
3825   Expr *getBinding() const { return Binding; }
3826
3827   /// Get the variable (if any) that holds the value of evaluating the binding.
3828   /// Only present for user-defined bindings for tuple-like types.
3829   VarDecl *getHoldingVar() const;
3830
3831   /// Set the binding for this BindingDecl, along with its declared type (which
3832   /// should be a possibly-cv-qualified form of the type of the binding, or a
3833   /// reference to such a type).
3834   void setBinding(QualType DeclaredType, Expr *Binding) {
3835     setType(DeclaredType);
3836     this->Binding = Binding;
3837   }
3838
3839   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3840   static bool classofKind(Kind K) { return K == Decl::Binding; }
3841 };
3842
3843 /// A decomposition declaration. For instance, given:
3844 ///
3845 ///   int n[3];
3846 ///   auto &[a, b, c] = n;
3847 ///
3848 /// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3849 /// three BindingDecls (named a, b, and c). An instance of this class is always
3850 /// unnamed, but behaves in almost all other respects like a VarDecl.
3851 class DecompositionDecl final
3852     : public VarDecl,
3853       private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3854   /// The number of BindingDecl*s following this object.
3855   unsigned NumBindings;
3856
3857   DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3858                     SourceLocation LSquareLoc, QualType T,
3859                     TypeSourceInfo *TInfo, StorageClass SC,
3860                     ArrayRef<BindingDecl *> Bindings)
3861       : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
3862                 SC),
3863         NumBindings(Bindings.size()) {
3864     std::uninitialized_copy(Bindings.begin(), Bindings.end(),
3865                             getTrailingObjects<BindingDecl *>());
3866   }
3867
3868   void anchor() override;
3869
3870 public:
3871   friend class ASTDeclReader;
3872   friend TrailingObjects;
3873
3874   static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
3875                                    SourceLocation StartLoc,
3876                                    SourceLocation LSquareLoc,
3877                                    QualType T, TypeSourceInfo *TInfo,
3878                                    StorageClass S,
3879                                    ArrayRef<BindingDecl *> Bindings);
3880   static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3881                                                unsigned NumBindings);
3882
3883   ArrayRef<BindingDecl *> bindings() const {
3884     return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
3885   }
3886
3887   void printName(raw_ostream &os) const override;
3888
3889   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3890   static bool classofKind(Kind K) { return K == Decomposition; }
3891 };
3892
3893 /// An instance of this class represents the declaration of a property
3894 /// member.  This is a Microsoft extension to C++, first introduced in
3895 /// Visual Studio .NET 2003 as a parallel to similar features in C#
3896 /// and Managed C++.
3897 ///
3898 /// A property must always be a non-static class member.
3899 ///
3900 /// A property member superficially resembles a non-static data
3901 /// member, except preceded by a property attribute:
3902 ///   __declspec(property(get=GetX, put=PutX)) int x;
3903 /// Either (but not both) of the 'get' and 'put' names may be omitted.
3904 ///
3905 /// A reference to a property is always an lvalue.  If the lvalue
3906 /// undergoes lvalue-to-rvalue conversion, then a getter name is
3907 /// required, and that member is called with no arguments.
3908 /// If the lvalue is assigned into, then a setter name is required,
3909 /// and that member is called with one argument, the value assigned.
3910 /// Both operations are potentially overloaded.  Compound assignments
3911 /// are permitted, as are the increment and decrement operators.
3912 ///
3913 /// The getter and putter methods are permitted to be overloaded,
3914 /// although their return and parameter types are subject to certain
3915 /// restrictions according to the type of the property.
3916 ///
3917 /// A property declared using an incomplete array type may
3918 /// additionally be subscripted, adding extra parameters to the getter
3919 /// and putter methods.
3920 class MSPropertyDecl : public DeclaratorDecl {
3921   IdentifierInfo *GetterId, *SetterId;
3922
3923   MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
3924                  QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
3925                  IdentifierInfo *Getter, IdentifierInfo *Setter)
3926       : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
3927         GetterId(Getter), SetterId(Setter) {}
3928
3929 public:
3930   friend class ASTDeclReader;
3931
3932   static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
3933                                 SourceLocation L, DeclarationName N, QualType T,
3934                                 TypeSourceInfo *TInfo, SourceLocation StartL,
3935                                 IdentifierInfo *Getter, IdentifierInfo *Setter);
3936   static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3937
3938   static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
3939
3940   bool hasGetter() const { return GetterId != nullptr; }
3941   IdentifierInfo* getGetterId() const { return GetterId; }
3942   bool hasSetter() const { return SetterId != nullptr; }
3943   IdentifierInfo* getSetterId() const { return SetterId; }
3944 };
3945
3946 /// Insertion operator for diagnostics.  This allows sending an AccessSpecifier
3947 /// into a diagnostic with <<.
3948 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3949                                     AccessSpecifier AS);
3950
3951 const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
3952                                     AccessSpecifier AS);
3953
3954 } // namespace clang
3955
3956 #endif // LLVM_CLANG_AST_DECLCXX_H