Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:28

0001 //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// Defines the clang::ASTContext interface.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
0015 #define LLVM_CLANG_AST_ASTCONTEXT_H
0016 
0017 #include "clang/AST/ASTFwd.h"
0018 #include "clang/AST/CanonicalType.h"
0019 #include "clang/AST/CommentCommandTraits.h"
0020 #include "clang/AST/ComparisonCategories.h"
0021 #include "clang/AST/Decl.h"
0022 #include "clang/AST/DeclarationName.h"
0023 #include "clang/AST/ExternalASTSource.h"
0024 #include "clang/AST/PrettyPrinter.h"
0025 #include "clang/AST/RawCommentList.h"
0026 #include "clang/AST/SYCLKernelInfo.h"
0027 #include "clang/AST/TemplateName.h"
0028 #include "clang/Basic/LLVM.h"
0029 #include "clang/Basic/PartialDiagnostic.h"
0030 #include "clang/Basic/SourceLocation.h"
0031 #include "llvm/ADT/DenseMap.h"
0032 #include "llvm/ADT/DenseSet.h"
0033 #include "llvm/ADT/FoldingSet.h"
0034 #include "llvm/ADT/IntrusiveRefCntPtr.h"
0035 #include "llvm/ADT/MapVector.h"
0036 #include "llvm/ADT/PointerIntPair.h"
0037 #include "llvm/ADT/PointerUnion.h"
0038 #include "llvm/ADT/SetVector.h"
0039 #include "llvm/ADT/SmallVector.h"
0040 #include "llvm/ADT/StringMap.h"
0041 #include "llvm/ADT/StringRef.h"
0042 #include "llvm/ADT/StringSet.h"
0043 #include "llvm/ADT/TinyPtrVector.h"
0044 #include "llvm/Support/TypeSize.h"
0045 #include <optional>
0046 
0047 namespace llvm {
0048 
0049 class APFixedPoint;
0050 class FixedPointSemantics;
0051 struct fltSemantics;
0052 template <typename T, unsigned N> class SmallPtrSet;
0053 
0054 } // namespace llvm
0055 
0056 namespace clang {
0057 
0058 class APValue;
0059 class ASTMutationListener;
0060 class ASTRecordLayout;
0061 class AtomicExpr;
0062 class BlockExpr;
0063 struct BlockVarCopyInit;
0064 class BuiltinTemplateDecl;
0065 class CharUnits;
0066 class ConceptDecl;
0067 class CXXABI;
0068 class CXXConstructorDecl;
0069 class CXXMethodDecl;
0070 class CXXRecordDecl;
0071 class DiagnosticsEngine;
0072 class DynTypedNodeList;
0073 class Expr;
0074 enum class FloatModeKind;
0075 class GlobalDecl;
0076 class IdentifierTable;
0077 class LangOptions;
0078 class MangleContext;
0079 class MangleNumberingContext;
0080 class MemberSpecializationInfo;
0081 class Module;
0082 struct MSGuidDeclParts;
0083 class NestedNameSpecifier;
0084 class NoSanitizeList;
0085 class ObjCCategoryDecl;
0086 class ObjCCategoryImplDecl;
0087 class ObjCContainerDecl;
0088 class ObjCImplDecl;
0089 class ObjCImplementationDecl;
0090 class ObjCInterfaceDecl;
0091 class ObjCIvarDecl;
0092 class ObjCMethodDecl;
0093 class ObjCPropertyDecl;
0094 class ObjCPropertyImplDecl;
0095 class ObjCProtocolDecl;
0096 class ObjCTypeParamDecl;
0097 class OMPTraitInfo;
0098 class ParentMapContext;
0099 struct ParsedTargetAttr;
0100 class Preprocessor;
0101 class ProfileList;
0102 class StoredDeclsMap;
0103 class TargetAttr;
0104 class TargetInfo;
0105 class TemplateDecl;
0106 class TemplateParameterList;
0107 class TemplateTemplateParmDecl;
0108 class TemplateTypeParmDecl;
0109 class TypeConstraint;
0110 class UnresolvedSetIterator;
0111 class UsingShadowDecl;
0112 class VarTemplateDecl;
0113 class VTableContextBase;
0114 class XRayFunctionFilter;
0115 
0116 /// A simple array of base specifiers.
0117 typedef SmallVector<CXXBaseSpecifier *, 4> CXXCastPath;
0118 
0119 namespace Builtin {
0120 
0121 class Context;
0122 
0123 } // namespace Builtin
0124 
0125 enum BuiltinTemplateKind : int;
0126 enum OpenCLTypeKind : uint8_t;
0127 
0128 namespace comments {
0129 
0130 class FullComment;
0131 
0132 } // namespace comments
0133 
0134 namespace interp {
0135 
0136 class Context;
0137 
0138 } // namespace interp
0139 
0140 namespace serialization {
0141 template <class> class AbstractTypeReader;
0142 } // namespace serialization
0143 
0144 enum class AlignRequirementKind {
0145   /// The alignment was not explicit in code.
0146   None,
0147 
0148   /// The alignment comes from an alignment attribute on a typedef.
0149   RequiredByTypedef,
0150 
0151   /// The alignment comes from an alignment attribute on a record type.
0152   RequiredByRecord,
0153 
0154   /// The alignment comes from an alignment attribute on a enum type.
0155   RequiredByEnum,
0156 };
0157 
0158 struct TypeInfo {
0159   uint64_t Width = 0;
0160   unsigned Align = 0;
0161   AlignRequirementKind AlignRequirement;
0162 
0163   TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
0164   TypeInfo(uint64_t Width, unsigned Align,
0165            AlignRequirementKind AlignRequirement)
0166       : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
0167   bool isAlignRequired() {
0168     return AlignRequirement != AlignRequirementKind::None;
0169   }
0170 };
0171 
0172 struct TypeInfoChars {
0173   CharUnits Width;
0174   CharUnits Align;
0175   AlignRequirementKind AlignRequirement;
0176 
0177   TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
0178   TypeInfoChars(CharUnits Width, CharUnits Align,
0179                 AlignRequirementKind AlignRequirement)
0180       : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
0181   bool isAlignRequired() {
0182     return AlignRequirement != AlignRequirementKind::None;
0183   }
0184 };
0185 
0186 /// Holds long-lived AST nodes (such as types and decls) that can be
0187 /// referred to throughout the semantic analysis of a file.
0188 class ASTContext : public RefCountedBase<ASTContext> {
0189   friend class NestedNameSpecifier;
0190 
0191   mutable SmallVector<Type *, 0> Types;
0192   mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
0193   mutable llvm::FoldingSet<ComplexType> ComplexTypes;
0194   mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize};
0195   mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
0196   mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
0197   mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
0198   mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
0199   mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
0200   mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
0201       ConstantArrayTypes;
0202   mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
0203   mutable std::vector<VariableArrayType*> VariableArrayTypes;
0204   mutable llvm::ContextualFoldingSet<DependentSizedArrayType, ASTContext &>
0205       DependentSizedArrayTypes;
0206   mutable llvm::ContextualFoldingSet<DependentSizedExtVectorType, ASTContext &>
0207       DependentSizedExtVectorTypes;
0208   mutable llvm::ContextualFoldingSet<DependentAddressSpaceType, ASTContext &>
0209       DependentAddressSpaceTypes;
0210   mutable llvm::FoldingSet<VectorType> VectorTypes;
0211   mutable llvm::ContextualFoldingSet<DependentVectorType, ASTContext &>
0212       DependentVectorTypes;
0213   mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
0214   mutable llvm::ContextualFoldingSet<DependentSizedMatrixType, ASTContext &>
0215       DependentSizedMatrixTypes;
0216   mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
0217   mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
0218     FunctionProtoTypes;
0219   mutable llvm::ContextualFoldingSet<DependentTypeOfExprType, ASTContext &>
0220       DependentTypeOfExprTypes;
0221   mutable llvm::ContextualFoldingSet<DependentDecltypeType, ASTContext &>
0222       DependentDecltypeTypes;
0223 
0224   mutable llvm::FoldingSet<PackIndexingType> DependentPackIndexingTypes;
0225 
0226   mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
0227   mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
0228   mutable llvm::FoldingSet<SubstTemplateTypeParmType>
0229     SubstTemplateTypeParmTypes;
0230   mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
0231     SubstTemplateTypeParmPackTypes;
0232   mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
0233     TemplateSpecializationTypes;
0234   mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
0235   mutable llvm::FoldingSet<UsingType> UsingTypes;
0236   mutable llvm::FoldingSet<TypedefType> TypedefTypes;
0237   mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{
0238       GeneralTypesLog2InitSize};
0239   mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
0240   mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
0241                                      ASTContext&>
0242     DependentTemplateSpecializationTypes;
0243   mutable llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
0244   mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
0245   mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
0246   mutable llvm::FoldingSet<DependentUnaryTransformType>
0247     DependentUnaryTransformTypes;
0248   // An AutoType can have a dependency on another AutoType via its template
0249   // arguments. Since both dependent and dependency are on the same set,
0250   // we can end up in an infinite recursion when looking for a node if we used
0251   // a `FoldingSet`, since both could end up in the same bucket.
0252   mutable llvm::DenseMap<llvm::FoldingSetNodeID, AutoType *> AutoTypes;
0253   mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
0254     DeducedTemplateSpecializationTypes;
0255   mutable llvm::FoldingSet<AtomicType> AtomicTypes;
0256   mutable llvm::FoldingSet<AttributedType> AttributedTypes;
0257   mutable llvm::FoldingSet<PipeType> PipeTypes;
0258   mutable llvm::FoldingSet<BitIntType> BitIntTypes;
0259   mutable llvm::ContextualFoldingSet<DependentBitIntType, ASTContext &>
0260       DependentBitIntTypes;
0261   mutable llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes;
0262   llvm::FoldingSet<HLSLAttributedResourceType> HLSLAttributedResourceTypes;
0263 
0264   mutable llvm::FoldingSet<CountAttributedType> CountAttributedTypes;
0265 
0266   mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
0267   mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
0268   mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
0269     SubstTemplateTemplateParms;
0270   mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
0271                                      ASTContext&>
0272     SubstTemplateTemplateParmPacks;
0273   mutable llvm::ContextualFoldingSet<DeducedTemplateStorage, ASTContext &>
0274       DeducedTemplates;
0275 
0276   mutable llvm::ContextualFoldingSet<ArrayParameterType, ASTContext &>
0277       ArrayParameterTypes;
0278 
0279   /// The set of nested name specifiers.
0280   ///
0281   /// This set is managed by the NestedNameSpecifier class.
0282   mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
0283   mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
0284 
0285   /// A cache mapping from RecordDecls to ASTRecordLayouts.
0286   ///
0287   /// This is lazily created.  This is intentionally not serialized.
0288   mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
0289     ASTRecordLayouts;
0290   mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
0291     ObjCLayouts;
0292 
0293   /// A cache from types to size and alignment information.
0294   using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
0295   mutable TypeInfoMap MemoizedTypeInfo;
0296 
0297   /// A cache from types to unadjusted alignment information. Only ARM and
0298   /// AArch64 targets need this information, keeping it separate prevents
0299   /// imposing overhead on TypeInfo size.
0300   using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
0301   mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
0302 
0303   /// A cache mapping from CXXRecordDecls to key functions.
0304   llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
0305 
0306   /// Mapping from ObjCContainers to their ObjCImplementations.
0307   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
0308 
0309   /// Mapping from ObjCMethod to its duplicate declaration in the same
0310   /// interface.
0311   llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
0312 
0313   /// Mapping from __block VarDecls to BlockVarCopyInit.
0314   llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
0315 
0316   /// Mapping from GUIDs to the corresponding MSGuidDecl.
0317   mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
0318 
0319   /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl.
0320   mutable llvm::FoldingSet<UnnamedGlobalConstantDecl>
0321       UnnamedGlobalConstantDecls;
0322 
0323   /// Mapping from APValues to the corresponding TemplateParamObjects.
0324   mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
0325 
0326   /// A cache mapping a string value to a StringLiteral object with the same
0327   /// value.
0328   ///
0329   /// This is lazily created.  This is intentionally not serialized.
0330   mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
0331 
0332   /// The next string literal "version" to allocate during constant evaluation.
0333   /// This is used to distinguish between repeated evaluations of the same
0334   /// string literal.
0335   ///
0336   /// We don't need to serialize this because constants get re-evaluated in the
0337   /// current file before they are compared locally.
0338   unsigned NextStringLiteralVersion = 0;
0339 
0340   /// MD5 hash of CUID. It is calculated when first used and cached by this
0341   /// data member.
0342   mutable std::string CUIDHash;
0343 
0344   /// Representation of a "canonical" template template parameter that
0345   /// is used in canonical template names.
0346   class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
0347     TemplateTemplateParmDecl *Parm;
0348 
0349   public:
0350     CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
0351         : Parm(Parm) {}
0352 
0353     TemplateTemplateParmDecl *getParam() const { return Parm; }
0354 
0355     void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
0356       Profile(ID, C, Parm);
0357     }
0358 
0359     static void Profile(llvm::FoldingSetNodeID &ID,
0360                         const ASTContext &C,
0361                         TemplateTemplateParmDecl *Parm);
0362   };
0363   mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
0364                                      const ASTContext&>
0365     CanonTemplateTemplateParms;
0366 
0367   TemplateTemplateParmDecl *
0368     getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
0369 
0370   /// The typedef for the __int128_t type.
0371   mutable TypedefDecl *Int128Decl = nullptr;
0372 
0373   /// The typedef for the __uint128_t type.
0374   mutable TypedefDecl *UInt128Decl = nullptr;
0375 
0376   /// The typedef for the target specific predefined
0377   /// __builtin_va_list type.
0378   mutable TypedefDecl *BuiltinVaListDecl = nullptr;
0379 
0380   /// The typedef for the predefined \c __builtin_ms_va_list type.
0381   mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
0382 
0383   /// The typedef for the predefined \c id type.
0384   mutable TypedefDecl *ObjCIdDecl = nullptr;
0385 
0386   /// The typedef for the predefined \c SEL type.
0387   mutable TypedefDecl *ObjCSelDecl = nullptr;
0388 
0389   /// The typedef for the predefined \c Class type.
0390   mutable TypedefDecl *ObjCClassDecl = nullptr;
0391 
0392   /// The typedef for the predefined \c Protocol class in Objective-C.
0393   mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
0394 
0395   /// The typedef for the predefined 'BOOL' type.
0396   mutable TypedefDecl *BOOLDecl = nullptr;
0397 
0398   // Typedefs which may be provided defining the structure of Objective-C
0399   // pseudo-builtins
0400   QualType ObjCIdRedefinitionType;
0401   QualType ObjCClassRedefinitionType;
0402   QualType ObjCSelRedefinitionType;
0403 
0404   /// The identifier 'bool'.
0405   mutable IdentifierInfo *BoolName = nullptr;
0406 
0407   /// The identifier 'NSObject'.
0408   mutable IdentifierInfo *NSObjectName = nullptr;
0409 
0410   /// The identifier 'NSCopying'.
0411   IdentifierInfo *NSCopyingName = nullptr;
0412 
0413   /// The identifier '__make_integer_seq'.
0414   mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
0415 
0416   /// The identifier '__type_pack_element'.
0417   mutable IdentifierInfo *TypePackElementName = nullptr;
0418 
0419   /// The identifier '__builtin_common_type'.
0420   mutable IdentifierInfo *BuiltinCommonTypeName = nullptr;
0421 
0422   QualType ObjCConstantStringType;
0423   mutable RecordDecl *CFConstantStringTagDecl = nullptr;
0424   mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
0425 
0426   mutable QualType ObjCSuperType;
0427 
0428   QualType ObjCNSStringType;
0429 
0430   /// The typedef declaration for the Objective-C "instancetype" type.
0431   TypedefDecl *ObjCInstanceTypeDecl = nullptr;
0432 
0433   /// The type for the C FILE type.
0434   TypeDecl *FILEDecl = nullptr;
0435 
0436   /// The type for the C jmp_buf type.
0437   TypeDecl *jmp_bufDecl = nullptr;
0438 
0439   /// The type for the C sigjmp_buf type.
0440   TypeDecl *sigjmp_bufDecl = nullptr;
0441 
0442   /// The type for the C ucontext_t type.
0443   TypeDecl *ucontext_tDecl = nullptr;
0444 
0445   /// Type for the Block descriptor for Blocks CodeGen.
0446   ///
0447   /// Since this is only used for generation of debug info, it is not
0448   /// serialized.
0449   mutable RecordDecl *BlockDescriptorType = nullptr;
0450 
0451   /// Type for the Block descriptor for Blocks CodeGen.
0452   ///
0453   /// Since this is only used for generation of debug info, it is not
0454   /// serialized.
0455   mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
0456 
0457   /// Declaration for the CUDA cudaConfigureCall function.
0458   FunctionDecl *cudaConfigureCallDecl = nullptr;
0459 
0460   /// Keeps track of all declaration attributes.
0461   ///
0462   /// Since so few decls have attrs, we keep them in a hash map instead of
0463   /// wasting space in the Decl class.
0464   llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
0465 
0466   /// A mapping from non-redeclarable declarations in modules that were
0467   /// merged with other declarations to the canonical declaration that they were
0468   /// merged into.
0469   llvm::DenseMap<Decl*, Decl*> MergedDecls;
0470 
0471   /// A mapping from a defining declaration to a list of modules (other
0472   /// than the owning module of the declaration) that contain merged
0473   /// definitions of that entity.
0474   llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
0475 
0476   /// Initializers for a module, in order. Each Decl will be either
0477   /// something that has a semantic effect on startup (such as a variable with
0478   /// a non-constant initializer), or an ImportDecl (which recursively triggers
0479   /// initialization of another module).
0480   struct PerModuleInitializers {
0481     llvm::SmallVector<Decl*, 4> Initializers;
0482     llvm::SmallVector<GlobalDeclID, 4> LazyInitializers;
0483 
0484     void resolve(ASTContext &Ctx);
0485   };
0486   llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
0487 
0488   /// This is the top-level (C++20) Named module we are building.
0489   Module *CurrentCXXNamedModule = nullptr;
0490 
0491   /// Help structures to decide whether two `const Module *` belongs
0492   /// to the same conceptual module to avoid the expensive to string comparison
0493   /// if possible.
0494   ///
0495   /// Not serialized intentionally.
0496   llvm::StringMap<const Module *> PrimaryModuleNameMap;
0497   llvm::DenseMap<const Module *, const Module *> SameModuleLookupSet;
0498 
0499   static constexpr unsigned ConstantArrayTypesLog2InitSize = 8;
0500   static constexpr unsigned GeneralTypesLog2InitSize = 9;
0501   static constexpr unsigned FunctionProtoTypesLog2InitSize = 12;
0502 
0503   ASTContext &this_() { return *this; }
0504 
0505 public:
0506   /// A type synonym for the TemplateOrInstantiation mapping.
0507   using TemplateOrSpecializationInfo =
0508       llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
0509 
0510 private:
0511   friend class ASTDeclReader;
0512   friend class ASTReader;
0513   friend class ASTWriter;
0514   template <class> friend class serialization::AbstractTypeReader;
0515   friend class CXXRecordDecl;
0516   friend class IncrementalParser;
0517 
0518   /// A mapping to contain the template or declaration that
0519   /// a variable declaration describes or was instantiated from,
0520   /// respectively.
0521   ///
0522   /// For non-templates, this value will be NULL. For variable
0523   /// declarations that describe a variable template, this will be a
0524   /// pointer to a VarTemplateDecl. For static data members
0525   /// of class template specializations, this will be the
0526   /// MemberSpecializationInfo referring to the member variable that was
0527   /// instantiated or specialized. Thus, the mapping will keep track of
0528   /// the static data member templates from which static data members of
0529   /// class template specializations were instantiated.
0530   ///
0531   /// Given the following example:
0532   ///
0533   /// \code
0534   /// template<typename T>
0535   /// struct X {
0536   ///   static T value;
0537   /// };
0538   ///
0539   /// template<typename T>
0540   ///   T X<T>::value = T(17);
0541   ///
0542   /// int *x = &X<int>::value;
0543   /// \endcode
0544   ///
0545   /// This mapping will contain an entry that maps from the VarDecl for
0546   /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
0547   /// class template X) and will be marked TSK_ImplicitInstantiation.
0548   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
0549   TemplateOrInstantiation;
0550 
0551   /// Keeps track of the declaration from which a using declaration was
0552   /// created during instantiation.
0553   ///
0554   /// The source and target declarations are always a UsingDecl, an
0555   /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
0556   ///
0557   /// For example:
0558   /// \code
0559   /// template<typename T>
0560   /// struct A {
0561   ///   void f();
0562   /// };
0563   ///
0564   /// template<typename T>
0565   /// struct B : A<T> {
0566   ///   using A<T>::f;
0567   /// };
0568   ///
0569   /// template struct B<int>;
0570   /// \endcode
0571   ///
0572   /// This mapping will contain an entry that maps from the UsingDecl in
0573   /// B<int> to the UnresolvedUsingDecl in B<T>.
0574   llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
0575 
0576   /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
0577   /// from the instantiated using-enum to the templated decl from whence it
0578   /// came.
0579   /// Note that using-enum-declarations cannot be dependent and
0580   /// thus will never be instantiated from an "unresolved"
0581   /// version thereof (as with using-declarations), so each mapping is from
0582   /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
0583   llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
0584       InstantiatedFromUsingEnumDecl;
0585 
0586   /// Simlarly maps instantiated UsingShadowDecls to their origin.
0587   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
0588     InstantiatedFromUsingShadowDecl;
0589 
0590   llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
0591 
0592   /// Mapping that stores the methods overridden by a given C++
0593   /// member function.
0594   ///
0595   /// Since most C++ member functions aren't virtual and therefore
0596   /// don't override anything, we store the overridden functions in
0597   /// this map on the side rather than within the CXXMethodDecl structure.
0598   using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
0599   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
0600 
0601   /// Mapping from each declaration context to its corresponding
0602   /// mangling numbering context (used for constructs like lambdas which
0603   /// need to be consistently numbered for the mangler).
0604   llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
0605       MangleNumberingContexts;
0606   llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
0607       ExtraMangleNumberingContexts;
0608 
0609   /// Side-table of mangling numbers for declarations which rarely
0610   /// need them (like static local vars).
0611   llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
0612   llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
0613   /// Mapping the associated device lambda mangling number if present.
0614   mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
0615       DeviceLambdaManglingNumbers;
0616 
0617   /// Mapping that stores parameterIndex values for ParmVarDecls when
0618   /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
0619   using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
0620   ParameterIndexTable ParamIndices;
0621 
0622   ImportDecl *FirstLocalImport = nullptr;
0623   ImportDecl *LastLocalImport = nullptr;
0624 
0625   TranslationUnitDecl *TUDecl = nullptr;
0626   mutable ExternCContextDecl *ExternCContext = nullptr;
0627   mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
0628   mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
0629   mutable BuiltinTemplateDecl *BuiltinCommonTypeDecl = nullptr;
0630 
0631   /// The associated SourceManager object.
0632   SourceManager &SourceMgr;
0633 
0634   /// The language options used to create the AST associated with
0635   ///  this ASTContext object.
0636   LangOptions &LangOpts;
0637 
0638   /// NoSanitizeList object that is used by sanitizers to decide which
0639   /// entities should not be instrumented.
0640   std::unique_ptr<NoSanitizeList> NoSanitizeL;
0641 
0642   /// Function filtering mechanism to determine whether a given function
0643   /// should be imbued with the XRay "always" or "never" attributes.
0644   std::unique_ptr<XRayFunctionFilter> XRayFilter;
0645 
0646   /// ProfileList object that is used by the profile instrumentation
0647   /// to decide which entities should be instrumented.
0648   std::unique_ptr<ProfileList> ProfList;
0649 
0650   /// The allocator used to create AST objects.
0651   ///
0652   /// AST objects are never destructed; rather, all memory associated with the
0653   /// AST objects will be released when the ASTContext itself is destroyed.
0654   mutable llvm::BumpPtrAllocator BumpAlloc;
0655 
0656   /// Allocator for partial diagnostics.
0657   PartialDiagnostic::DiagStorageAllocator DiagAllocator;
0658 
0659   /// The current C++ ABI.
0660   std::unique_ptr<CXXABI> ABI;
0661   CXXABI *createCXXABI(const TargetInfo &T);
0662 
0663   /// Address space map mangling must be used with language specific
0664   /// address spaces (e.g. OpenCL/CUDA)
0665   bool AddrSpaceMapMangling;
0666 
0667   /// For performance, track whether any function effects are in use.
0668   mutable bool AnyFunctionEffects = false;
0669 
0670   const TargetInfo *Target = nullptr;
0671   const TargetInfo *AuxTarget = nullptr;
0672   clang::PrintingPolicy PrintingPolicy;
0673   std::unique_ptr<interp::Context> InterpContext;
0674   std::unique_ptr<ParentMapContext> ParentMapCtx;
0675 
0676   /// Keeps track of the deallocated DeclListNodes for future reuse.
0677   DeclListNode *ListNodeFreeList = nullptr;
0678 
0679 public:
0680   IdentifierTable &Idents;
0681   SelectorTable &Selectors;
0682   Builtin::Context &BuiltinInfo;
0683   const TranslationUnitKind TUKind;
0684   mutable DeclarationNameTable DeclarationNames;
0685   IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
0686   ASTMutationListener *Listener = nullptr;
0687 
0688   /// Returns the clang bytecode interpreter context.
0689   interp::Context &getInterpContext();
0690 
0691   struct CUDAConstantEvalContext {
0692     /// Do not allow wrong-sided variables in constant expressions.
0693     bool NoWrongSidedVars = false;
0694   } CUDAConstantEvalCtx;
0695   struct CUDAConstantEvalContextRAII {
0696     ASTContext &Ctx;
0697     CUDAConstantEvalContext SavedCtx;
0698     CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars)
0699         : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) {
0700       Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars;
0701     }
0702     ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; }
0703   };
0704 
0705   /// Returns the dynamic AST node parent map context.
0706   ParentMapContext &getParentMapContext();
0707 
0708   // A traversal scope limits the parts of the AST visible to certain analyses.
0709   // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
0710   // getParents() will only observe reachable parent edges.
0711   //
0712   // The scope is defined by a set of "top-level" declarations which will be
0713   // visible under the TranslationUnitDecl.
0714   // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
0715   //
0716   // After setTraversalScope({foo, bar}), the exposed AST looks like:
0717   // TranslationUnitDecl
0718   //  - foo
0719   //    - ...
0720   //  - bar
0721   //    - ...
0722   // All other siblings of foo and bar are pruned from the tree.
0723   // (However they are still accessible via TranslationUnitDecl->decls())
0724   //
0725   // Changing the scope clears the parent cache, which is expensive to rebuild.
0726   std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
0727   void setTraversalScope(const std::vector<Decl *> &);
0728 
0729   /// Forwards to get node parents from the ParentMapContext. New callers should
0730   /// use ParentMapContext::getParents() directly.
0731   template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
0732 
0733   const clang::PrintingPolicy &getPrintingPolicy() const {
0734     return PrintingPolicy;
0735   }
0736 
0737   void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
0738     PrintingPolicy = Policy;
0739   }
0740 
0741   SourceManager& getSourceManager() { return SourceMgr; }
0742   const SourceManager& getSourceManager() const { return SourceMgr; }
0743 
0744   // Cleans up some of the data structures. This allows us to do cleanup
0745   // normally done in the destructor earlier. Renders much of the ASTContext
0746   // unusable, mostly the actual AST nodes, so should be called when we no
0747   // longer need access to the AST.
0748   void cleanup();
0749 
0750   llvm::BumpPtrAllocator &getAllocator() const {
0751     return BumpAlloc;
0752   }
0753 
0754   void *Allocate(size_t Size, unsigned Align = 8) const {
0755     return BumpAlloc.Allocate(Size, Align);
0756   }
0757   template <typename T> T *Allocate(size_t Num = 1) const {
0758     return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
0759   }
0760   void Deallocate(void *Ptr) const {}
0761 
0762   llvm::StringRef backupStr(llvm::StringRef S) const {
0763     char *Buf = new (*this) char[S.size()];
0764     std::copy(S.begin(), S.end(), Buf);
0765     return llvm::StringRef(Buf, S.size());
0766   }
0767 
0768   /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
0769   /// pool.
0770   DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
0771     if (DeclListNode *Alloc = ListNodeFreeList) {
0772       ListNodeFreeList = dyn_cast_if_present<DeclListNode *>(Alloc->Rest);
0773       Alloc->D = ND;
0774       Alloc->Rest = nullptr;
0775       return Alloc;
0776     }
0777     return new (*this) DeclListNode(ND);
0778   }
0779   /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList
0780   /// pool.
0781   void DeallocateDeclListNode(DeclListNode *N) {
0782     N->Rest = ListNodeFreeList;
0783     ListNodeFreeList = N;
0784   }
0785 
0786   /// Return the total amount of physical memory allocated for representing
0787   /// AST nodes and type information.
0788   size_t getASTAllocatedMemory() const {
0789     return BumpAlloc.getTotalMemory();
0790   }
0791 
0792   /// Return the total memory used for various side tables.
0793   size_t getSideTableAllocatedMemory() const;
0794 
0795   PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
0796     return DiagAllocator;
0797   }
0798 
0799   const TargetInfo &getTargetInfo() const { return *Target; }
0800   const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
0801 
0802   const QualType GetHigherPrecisionFPType(QualType ElementType) const {
0803     const auto *CurrentBT = cast<BuiltinType>(ElementType);
0804     switch (CurrentBT->getKind()) {
0805     case BuiltinType::Kind::Half:
0806     case BuiltinType::Kind::Float16:
0807       return FloatTy;
0808     case BuiltinType::Kind::Float:
0809     case BuiltinType::Kind::BFloat16:
0810       return DoubleTy;
0811     case BuiltinType::Kind::Double:
0812       return LongDoubleTy;
0813     default:
0814       return ElementType;
0815     }
0816     return ElementType;
0817   }
0818 
0819   /// getIntTypeForBitwidth -
0820   /// sets integer QualTy according to specified details:
0821   /// bitwidth, signed/unsigned.
0822   /// Returns empty type if there is no appropriate target types.
0823   QualType getIntTypeForBitwidth(unsigned DestWidth,
0824                                  unsigned Signed) const;
0825 
0826   /// getRealTypeForBitwidth -
0827   /// sets floating point QualTy according to specified bitwidth.
0828   /// Returns empty type if there is no appropriate target types.
0829   QualType getRealTypeForBitwidth(unsigned DestWidth,
0830                                   FloatModeKind ExplicitType) const;
0831 
0832   bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
0833 
0834   const LangOptions& getLangOpts() const { return LangOpts; }
0835 
0836   // If this condition is false, typo correction must be performed eagerly
0837   // rather than delayed in many places, as it makes use of dependent types.
0838   // the condition is false for clang's C-only codepath, as it doesn't support
0839   // dependent types yet.
0840   bool isDependenceAllowed() const {
0841     return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
0842   }
0843 
0844   const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
0845 
0846   bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
0847                                 const QualType &Ty) const;
0848 
0849   const XRayFunctionFilter &getXRayFilter() const {
0850     return *XRayFilter;
0851   }
0852 
0853   const ProfileList &getProfileList() const { return *ProfList; }
0854 
0855   DiagnosticsEngine &getDiagnostics() const;
0856 
0857   FullSourceLoc getFullLoc(SourceLocation Loc) const {
0858     return FullSourceLoc(Loc,SourceMgr);
0859   }
0860 
0861   /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
0862   /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
0863   /// the default ABI set by the target.
0864   TargetCXXABI::Kind getCXXABIKind() const;
0865 
0866   /// All comments in this translation unit.
0867   RawCommentList Comments;
0868 
0869   /// True if comments are already loaded from ExternalASTSource.
0870   mutable bool CommentsLoaded = false;
0871 
0872   /// Mapping from declaration to directly attached comment.
0873   ///
0874   /// Raw comments are owned by Comments list.  This mapping is populated
0875   /// lazily.
0876   mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
0877 
0878   /// Mapping from canonical declaration to the first redeclaration in chain
0879   /// that has a comment attached.
0880   ///
0881   /// Raw comments are owned by Comments list.  This mapping is populated
0882   /// lazily.
0883   mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
0884 
0885   /// Keeps track of redeclaration chains that don't have any comment attached.
0886   /// Mapping from canonical declaration to redeclaration chain that has no
0887   /// comments attached to any redeclaration. Specifically it's mapping to
0888   /// the last redeclaration we've checked.
0889   ///
0890   /// Shall not contain declarations that have comments attached to any
0891   /// redeclaration in their chain.
0892   mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
0893 
0894   /// Mapping from declarations to parsed comments attached to any
0895   /// redeclaration.
0896   mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
0897 
0898   /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
0899   /// and removes the redeclaration chain from the set of commentless chains.
0900   ///
0901   /// Don't do anything if a comment has already been attached to \p OriginalD
0902   /// or its redeclaration chain.
0903   void cacheRawCommentForDecl(const Decl &OriginalD,
0904                               const RawComment &Comment) const;
0905 
0906   /// \returns searches \p CommentsInFile for doc comment for \p D.
0907   ///
0908   /// \p RepresentativeLocForDecl is used as a location for searching doc
0909   /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
0910   /// same file where \p RepresentativeLocForDecl is.
0911   RawComment *getRawCommentForDeclNoCacheImpl(
0912       const Decl *D, const SourceLocation RepresentativeLocForDecl,
0913       const std::map<unsigned, RawComment *> &CommentsInFile) const;
0914 
0915   /// Return the documentation comment attached to a given declaration,
0916   /// without looking into cache.
0917   RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
0918 
0919 public:
0920   void addComment(const RawComment &RC);
0921 
0922   /// Return the documentation comment attached to a given declaration.
0923   /// Returns nullptr if no comment is attached.
0924   ///
0925   /// \param OriginalDecl if not nullptr, is set to declaration AST node that
0926   /// had the comment, if the comment we found comes from a redeclaration.
0927   const RawComment *
0928   getRawCommentForAnyRedecl(const Decl *D,
0929                             const Decl **OriginalDecl = nullptr) const;
0930 
0931   /// Searches existing comments for doc comments that should be attached to \p
0932   /// Decls. If any doc comment is found, it is parsed.
0933   ///
0934   /// Requirement: All \p Decls are in the same file.
0935   ///
0936   /// If the last comment in the file is already attached we assume
0937   /// there are not comments left to be attached to \p Decls.
0938   void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
0939                                        const Preprocessor *PP);
0940 
0941   /// Return parsed documentation comment attached to a given declaration.
0942   /// Returns nullptr if no comment is attached.
0943   ///
0944   /// \param PP the Preprocessor used with this TU.  Could be nullptr if
0945   /// preprocessor is not available.
0946   comments::FullComment *getCommentForDecl(const Decl *D,
0947                                            const Preprocessor *PP) const;
0948 
0949   /// Return parsed documentation comment attached to a given declaration.
0950   /// Returns nullptr if no comment is attached. Does not look at any
0951   /// redeclarations of the declaration.
0952   comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
0953 
0954   comments::FullComment *cloneFullComment(comments::FullComment *FC,
0955                                          const Decl *D) const;
0956 
0957 private:
0958   mutable comments::CommandTraits CommentCommandTraits;
0959 
0960   /// Iterator that visits import declarations.
0961   class import_iterator {
0962     ImportDecl *Import = nullptr;
0963 
0964   public:
0965     using value_type = ImportDecl *;
0966     using reference = ImportDecl *;
0967     using pointer = ImportDecl *;
0968     using difference_type = int;
0969     using iterator_category = std::forward_iterator_tag;
0970 
0971     import_iterator() = default;
0972     explicit import_iterator(ImportDecl *Import) : Import(Import) {}
0973 
0974     reference operator*() const { return Import; }
0975     pointer operator->() const { return Import; }
0976 
0977     import_iterator &operator++() {
0978       Import = ASTContext::getNextLocalImport(Import);
0979       return *this;
0980     }
0981 
0982     import_iterator operator++(int) {
0983       import_iterator Other(*this);
0984       ++(*this);
0985       return Other;
0986     }
0987 
0988     friend bool operator==(import_iterator X, import_iterator Y) {
0989       return X.Import == Y.Import;
0990     }
0991 
0992     friend bool operator!=(import_iterator X, import_iterator Y) {
0993       return X.Import != Y.Import;
0994     }
0995   };
0996 
0997 public:
0998   comments::CommandTraits &getCommentCommandTraits() const {
0999     return CommentCommandTraits;
1000   }
1001 
1002   /// Retrieve the attributes for the given declaration.
1003   AttrVec& getDeclAttrs(const Decl *D);
1004 
1005   /// Erase the attributes corresponding to the given declaration.
1006   void eraseDeclAttrs(const Decl *D);
1007 
1008   /// If this variable is an instantiated static data member of a
1009   /// class template specialization, returns the templated static data member
1010   /// from which it was instantiated.
1011   // FIXME: Remove ?
1012   MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
1013                                                            const VarDecl *Var);
1014 
1015   /// Note that the static data member \p Inst is an instantiation of
1016   /// the static data member template \p Tmpl of a class template.
1017   void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1018                                            TemplateSpecializationKind TSK,
1019                         SourceLocation PointOfInstantiation = SourceLocation());
1020 
1021   TemplateOrSpecializationInfo
1022   getTemplateOrSpecializationInfo(const VarDecl *Var);
1023 
1024   void setTemplateOrSpecializationInfo(VarDecl *Inst,
1025                                        TemplateOrSpecializationInfo TSI);
1026 
1027   /// If the given using decl \p Inst is an instantiation of
1028   /// another (possibly unresolved) using decl, return it.
1029   NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
1030 
1031   /// Remember that the using decl \p Inst is an instantiation
1032   /// of the using decl \p Pattern of a class template.
1033   void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
1034 
1035   /// If the given using-enum decl \p Inst is an instantiation of
1036   /// another using-enum decl, return it.
1037   UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst);
1038 
1039   /// Remember that the using enum decl \p Inst is an instantiation
1040   /// of the using enum decl \p Pattern of a class template.
1041   void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1042                                         UsingEnumDecl *Pattern);
1043 
1044   UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
1045   void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1046                                           UsingShadowDecl *Pattern);
1047 
1048   FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const;
1049 
1050   void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
1051 
1052   // Access to the set of methods overridden by the given C++ method.
1053   using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
1054   overridden_cxx_method_iterator
1055   overridden_methods_begin(const CXXMethodDecl *Method) const;
1056 
1057   overridden_cxx_method_iterator
1058   overridden_methods_end(const CXXMethodDecl *Method) const;
1059 
1060   unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
1061 
1062   using overridden_method_range =
1063       llvm::iterator_range<overridden_cxx_method_iterator>;
1064 
1065   overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
1066 
1067   /// Note that the given C++ \p Method overrides the given \p
1068   /// Overridden method.
1069   void addOverriddenMethod(const CXXMethodDecl *Method,
1070                            const CXXMethodDecl *Overridden);
1071 
1072   /// Return C++ or ObjC overridden methods for the given \p Method.
1073   ///
1074   /// An ObjC method is considered to override any method in the class's
1075   /// base classes, its protocols, or its categories' protocols, that has
1076   /// the same selector and is of the same kind (class or instance).
1077   /// A method in an implementation is not considered as overriding the same
1078   /// method in the interface or its categories.
1079   void getOverriddenMethods(
1080                         const NamedDecl *Method,
1081                         SmallVectorImpl<const NamedDecl *> &Overridden) const;
1082 
1083   /// Notify the AST context that a new import declaration has been
1084   /// parsed or implicitly created within this translation unit.
1085   void addedLocalImportDecl(ImportDecl *Import);
1086 
1087   static ImportDecl *getNextLocalImport(ImportDecl *Import) {
1088     return Import->getNextLocalImport();
1089   }
1090 
1091   using import_range = llvm::iterator_range<import_iterator>;
1092 
1093   import_range local_imports() const {
1094     return import_range(import_iterator(FirstLocalImport), import_iterator());
1095   }
1096 
1097   Decl *getPrimaryMergedDecl(Decl *D) {
1098     Decl *Result = MergedDecls.lookup(D);
1099     return Result ? Result : D;
1100   }
1101   void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
1102     MergedDecls[D] = Primary;
1103   }
1104 
1105   /// Note that the definition \p ND has been merged into module \p M,
1106   /// and should be visible whenever \p M is visible.
1107   void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1108                                  bool NotifyListeners = true);
1109 
1110   /// Clean up the merged definition list. Call this if you might have
1111   /// added duplicates into the list.
1112   void deduplicateMergedDefinitonsFor(NamedDecl *ND);
1113 
1114   /// Get the additional modules in which the definition \p Def has
1115   /// been merged.
1116   ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
1117 
1118   /// Add a declaration to the list of declarations that are initialized
1119   /// for a module. This will typically be a global variable (with internal
1120   /// linkage) that runs module initializers, such as the iostream initializer,
1121   /// or an ImportDecl nominating another module that has initializers.
1122   void addModuleInitializer(Module *M, Decl *Init);
1123 
1124   void addLazyModuleInitializers(Module *M, ArrayRef<GlobalDeclID> IDs);
1125 
1126   /// Get the initializations to perform when importing a module, if any.
1127   ArrayRef<Decl*> getModuleInitializers(Module *M);
1128 
1129   /// Set the (C++20) module we are building.
1130   void setCurrentNamedModule(Module *M);
1131 
1132   /// Get module under construction, nullptr if this is not a C++20 module.
1133   Module *getCurrentNamedModule() const { return CurrentCXXNamedModule; }
1134 
1135   /// If the two module \p M1 and \p M2 are in the same module.
1136   ///
1137   /// FIXME: The signature may be confusing since `clang::Module` means to
1138   /// a module fragment or a module unit but not a C++20 module.
1139   bool isInSameModule(const Module *M1, const Module *M2);
1140 
1141   TranslationUnitDecl *getTranslationUnitDecl() const {
1142     return TUDecl->getMostRecentDecl();
1143   }
1144   void addTranslationUnitDecl() {
1145     assert(!TUDecl || TUKind == TU_Incremental);
1146     TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this);
1147     if (TraversalScope.empty() || TraversalScope.back() == TUDecl)
1148       TraversalScope = {NewTUDecl};
1149     if (TUDecl)
1150       NewTUDecl->setPreviousDecl(TUDecl);
1151     TUDecl = NewTUDecl;
1152   }
1153 
1154   ExternCContextDecl *getExternCContextDecl() const;
1155   BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1156   BuiltinTemplateDecl *getTypePackElementDecl() const;
1157   BuiltinTemplateDecl *getBuiltinCommonTypeDecl() const;
1158 
1159   // Builtin Types.
1160   CanQualType VoidTy;
1161   CanQualType BoolTy;
1162   CanQualType CharTy;
1163   CanQualType WCharTy;  // [C++ 3.9.1p5].
1164   CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1165   CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
1166   CanQualType Char8Ty;  // [C++20 proposal]
1167   CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1168   CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1169   CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1170   CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1171   CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1172   CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
1173   CanQualType ShortAccumTy, AccumTy,
1174       LongAccumTy;  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1175   CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1176   CanQualType ShortFractTy, FractTy, LongFractTy;
1177   CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1178   CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1179   CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1180       SatUnsignedLongAccumTy;
1181   CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1182   CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1183       SatUnsignedLongFractTy;
1184   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1185   CanQualType BFloat16Ty;
1186   CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1187   CanQualType VoidPtrTy, NullPtrTy;
1188   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
1189       UnknownAnyTy;
1190   CanQualType BuiltinFnTy;
1191   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1192   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1193   CanQualType ObjCBuiltinBoolTy;
1194 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1195   CanQualType SingletonId;
1196 #include "clang/Basic/OpenCLImageTypes.def"
1197   CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1198   CanQualType OCLQueueTy, OCLReserveIDTy;
1199   CanQualType IncompleteMatrixIdxTy;
1200   CanQualType ArraySectionTy;
1201   CanQualType OMPArrayShapingTy, OMPIteratorTy;
1202 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1203   CanQualType Id##Ty;
1204 #include "clang/Basic/OpenCLExtensionTypes.def"
1205 #define SVE_TYPE(Name, Id, SingletonId) \
1206   CanQualType SingletonId;
1207 #include "clang/Basic/AArch64SVEACLETypes.def"
1208 #define PPC_VECTOR_TYPE(Name, Id, Size) \
1209   CanQualType Id##Ty;
1210 #include "clang/Basic/PPCTypes.def"
1211 #define RVV_TYPE(Name, Id, SingletonId) \
1212   CanQualType SingletonId;
1213 #include "clang/Basic/RISCVVTypes.def"
1214 #define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
1215 #include "clang/Basic/WebAssemblyReferenceTypes.def"
1216 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align)                       \
1217   CanQualType SingletonId;
1218 #include "clang/Basic/AMDGPUTypes.def"
1219 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
1220 #include "clang/Basic/HLSLIntangibleTypes.def"
1221 
1222   // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1223   mutable QualType AutoDeductTy;     // Deduction against 'auto'.
1224   mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1225 
1226   // Decl used to help define __builtin_va_list for some targets.
1227   // The decl is built when constructing 'BuiltinVaListDecl'.
1228   mutable Decl *VaListTagDecl = nullptr;
1229 
1230   // Implicitly-declared type 'struct _GUID'.
1231   mutable TagDecl *MSGuidTagDecl = nullptr;
1232 
1233   /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
1234   /// This does not include extern shared variables used by device host
1235   /// functions as addresses of shared variables are per warp, therefore
1236   /// cannot be accessed by host code.
1237   llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost;
1238 
1239   /// Keep track of CUDA/HIP external kernels or device variables ODR-used by
1240   /// host code. SetVector is used to maintain the order.
1241   llvm::SetVector<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost;
1242 
1243   /// Keep track of CUDA/HIP implicit host device functions used on device side
1244   /// in device compilation.
1245   llvm::DenseSet<const FunctionDecl *> CUDAImplicitHostDeviceFunUsedByDevice;
1246 
1247   /// Map of SYCL kernels indexed by the unique type used to name the kernel.
1248   /// Entries are not serialized but are recreated on deserialization of a
1249   /// sycl_kernel_entry_point attributed function declaration.
1250   llvm::DenseMap<CanQualType, SYCLKernelInfo> SYCLKernels;
1251 
1252   /// For capturing lambdas with an explicit object parameter whose type is
1253   /// derived from the lambda type, we need to perform derived-to-base
1254   /// conversion so we can access the captures; the cast paths for that
1255   /// are stored here.
1256   llvm::DenseMap<const CXXMethodDecl *, CXXCastPath> LambdaCastPaths;
1257 
1258   ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1259              SelectorTable &sels, Builtin::Context &builtins,
1260              TranslationUnitKind TUKind);
1261   ASTContext(const ASTContext &) = delete;
1262   ASTContext &operator=(const ASTContext &) = delete;
1263   ~ASTContext();
1264 
1265   /// Attach an external AST source to the AST context.
1266   ///
1267   /// The external AST source provides the ability to load parts of
1268   /// the abstract syntax tree as needed from some external storage,
1269   /// e.g., a precompiled header.
1270   void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1271 
1272   /// Retrieve a pointer to the external AST source associated
1273   /// with this AST context, if any.
1274   ExternalASTSource *getExternalSource() const {
1275     return ExternalSource.get();
1276   }
1277 
1278   /// Attach an AST mutation listener to the AST context.
1279   ///
1280   /// The AST mutation listener provides the ability to track modifications to
1281   /// the abstract syntax tree entities committed after they were initially
1282   /// created.
1283   void setASTMutationListener(ASTMutationListener *Listener) {
1284     this->Listener = Listener;
1285   }
1286 
1287   /// Retrieve a pointer to the AST mutation listener associated
1288   /// with this AST context, if any.
1289   ASTMutationListener *getASTMutationListener() const { return Listener; }
1290 
1291   void PrintStats() const;
1292   const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1293 
1294   BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1295                                                 const IdentifierInfo *II) const;
1296 
1297   /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1298   /// declaration.
1299   RecordDecl *buildImplicitRecord(
1300       StringRef Name,
1301       RecordDecl::TagKind TK = RecordDecl::TagKind::Struct) const;
1302 
1303   /// Create a new implicit TU-level typedef declaration.
1304   TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1305 
1306   /// Retrieve the declaration for the 128-bit signed integer type.
1307   TypedefDecl *getInt128Decl() const;
1308 
1309   /// Retrieve the declaration for the 128-bit unsigned integer type.
1310   TypedefDecl *getUInt128Decl() const;
1311 
1312   //===--------------------------------------------------------------------===//
1313   //                           Type Constructors
1314   //===--------------------------------------------------------------------===//
1315 
1316 private:
1317   /// Return a type with extended qualifiers.
1318   QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1319 
1320   QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1321 
1322   QualType getPipeType(QualType T, bool ReadOnly) const;
1323 
1324 public:
1325   /// Return the uniqued reference to the type for an address space
1326   /// qualified type with the specified type and address space.
1327   ///
1328   /// The resulting type has a union of the qualifiers from T and the address
1329   /// space. If T already has an address space specifier, it is silently
1330   /// replaced.
1331   QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1332 
1333   /// Remove any existing address space on the type and returns the type
1334   /// with qualifiers intact (or that's the idea anyway)
1335   ///
1336   /// The return type should be T with all prior qualifiers minus the address
1337   /// space.
1338   QualType removeAddrSpaceQualType(QualType T) const;
1339 
1340   /// Return the "other" discriminator used for the pointer auth schema used for
1341   /// vtable pointers in instances of the requested type.
1342   uint16_t
1343   getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
1344 
1345   /// Return the "other" type-specific discriminator for the given type.
1346   uint16_t getPointerAuthTypeDiscriminator(QualType T);
1347 
1348   /// Apply Objective-C protocol qualifiers to the given type.
1349   /// \param allowOnPointerType specifies if we can apply protocol
1350   /// qualifiers on ObjCObjectPointerType. It can be set to true when
1351   /// constructing the canonical type of a Objective-C type parameter.
1352   QualType applyObjCProtocolQualifiers(QualType type,
1353       ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1354       bool allowOnPointerType = false) const;
1355 
1356   /// Return the uniqued reference to the type for an Objective-C
1357   /// gc-qualified type.
1358   ///
1359   /// The resulting type has a union of the qualifiers from T and the gc
1360   /// attribute.
1361   QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1362 
1363   /// Remove the existing address space on the type if it is a pointer size
1364   /// address space and return the type with qualifiers intact.
1365   QualType removePtrSizeAddrSpace(QualType T) const;
1366 
1367   /// Return the uniqued reference to the type for a \c restrict
1368   /// qualified type.
1369   ///
1370   /// The resulting type has a union of the qualifiers from \p T and
1371   /// \c restrict.
1372   QualType getRestrictType(QualType T) const {
1373     return T.withFastQualifiers(Qualifiers::Restrict);
1374   }
1375 
1376   /// Return the uniqued reference to the type for a \c volatile
1377   /// qualified type.
1378   ///
1379   /// The resulting type has a union of the qualifiers from \p T and
1380   /// \c volatile.
1381   QualType getVolatileType(QualType T) const {
1382     return T.withFastQualifiers(Qualifiers::Volatile);
1383   }
1384 
1385   /// Return the uniqued reference to the type for a \c const
1386   /// qualified type.
1387   ///
1388   /// The resulting type has a union of the qualifiers from \p T and \c const.
1389   ///
1390   /// It can be reasonably expected that this will always be equivalent to
1391   /// calling T.withConst().
1392   QualType getConstType(QualType T) const { return T.withConst(); }
1393 
1394   /// Rebuild a type, preserving any existing type sugar. For function types,
1395   /// you probably want to just use \c adjustFunctionResultType and friends
1396   /// instead.
1397   QualType adjustType(QualType OldType,
1398                       llvm::function_ref<QualType(QualType)> Adjust) const;
1399 
1400   /// Change the ExtInfo on a function type.
1401   const FunctionType *adjustFunctionType(const FunctionType *Fn,
1402                                          FunctionType::ExtInfo EInfo);
1403 
1404   /// Change the result type of a function type, preserving sugar such as
1405   /// attributed types.
1406   QualType adjustFunctionResultType(QualType FunctionType,
1407                                     QualType NewResultType);
1408 
1409   /// Adjust the given function result type.
1410   CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1411 
1412   /// Change the result type of a function type once it is deduced.
1413   void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1414 
1415   /// Get a function type and produce the equivalent function type with the
1416   /// specified exception specification. Type sugar that can be present on a
1417   /// declaration of a function with an exception specification is permitted
1418   /// and preserved. Other type sugar (for instance, typedefs) is not.
1419   QualType getFunctionTypeWithExceptionSpec(
1420       QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const;
1421 
1422   /// Determine whether two function types are the same, ignoring
1423   /// exception specifications in cases where they're part of the type.
1424   bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const;
1425 
1426   /// Change the exception specification on a function once it is
1427   /// delay-parsed, instantiated, or computed.
1428   void adjustExceptionSpec(FunctionDecl *FD,
1429                            const FunctionProtoType::ExceptionSpecInfo &ESI,
1430                            bool AsWritten = false);
1431 
1432   /// Get a function type and produce the equivalent function type where
1433   /// pointer size address spaces in the return type and parameter types are
1434   /// replaced with the default address space.
1435   QualType getFunctionTypeWithoutPtrSizes(QualType T);
1436 
1437   /// Determine whether two function types are the same, ignoring pointer sizes
1438   /// in the return type and parameter types.
1439   bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1440 
1441   /// Get or construct a function type that is equivalent to the input type
1442   /// except that the parameter ABI annotations are stripped.
1443   QualType getFunctionTypeWithoutParamABIs(QualType T) const;
1444 
1445   /// Determine if two function types are the same, ignoring parameter ABI
1446   /// annotations.
1447   bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const;
1448 
1449   /// Return the uniqued reference to the type for a complex
1450   /// number with the specified element type.
1451   QualType getComplexType(QualType T) const;
1452   CanQualType getComplexType(CanQualType T) const {
1453     return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1454   }
1455 
1456   /// Return the uniqued reference to the type for a pointer to
1457   /// the specified type.
1458   QualType getPointerType(QualType T) const;
1459   CanQualType getPointerType(CanQualType T) const {
1460     return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1461   }
1462 
1463   QualType
1464   getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes,
1465                          bool OrNull,
1466                          ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const;
1467 
1468   /// Return the uniqued reference to a type adjusted from the original
1469   /// type to a new type.
1470   QualType getAdjustedType(QualType Orig, QualType New) const;
1471   CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1472     return CanQualType::CreateUnsafe(
1473         getAdjustedType((QualType)Orig, (QualType)New));
1474   }
1475 
1476   /// Return the uniqued reference to the decayed version of the given
1477   /// type.  Can only be called on array and function types which decay to
1478   /// pointer types.
1479   QualType getDecayedType(QualType T) const;
1480   CanQualType getDecayedType(CanQualType T) const {
1481     return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1482   }
1483   /// Return the uniqued reference to a specified decay from the original
1484   /// type to the decayed type.
1485   QualType getDecayedType(QualType Orig, QualType Decayed) const;
1486 
1487   /// Return the uniqued reference to a specified array parameter type from the
1488   /// original array type.
1489   QualType getArrayParameterType(QualType Ty) const;
1490 
1491   /// Return the uniqued reference to the atomic type for the specified
1492   /// type.
1493   QualType getAtomicType(QualType T) const;
1494 
1495   /// Return the uniqued reference to the type for a block of the
1496   /// specified type.
1497   QualType getBlockPointerType(QualType T) const;
1498 
1499   /// Gets the struct used to keep track of the descriptor for pointer to
1500   /// blocks.
1501   QualType getBlockDescriptorType() const;
1502 
1503   /// Return a read_only pipe type for the specified type.
1504   QualType getReadPipeType(QualType T) const;
1505 
1506   /// Return a write_only pipe type for the specified type.
1507   QualType getWritePipeType(QualType T) const;
1508 
1509   /// Return a bit-precise integer type with the specified signedness and bit
1510   /// count.
1511   QualType getBitIntType(bool Unsigned, unsigned NumBits) const;
1512 
1513   /// Return a dependent bit-precise integer type with the specified signedness
1514   /// and bit count.
1515   QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const;
1516 
1517   /// Gets the struct used to keep track of the extended descriptor for
1518   /// pointer to blocks.
1519   QualType getBlockDescriptorExtendedType() const;
1520 
1521   /// Map an AST Type to an OpenCLTypeKind enum value.
1522   OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1523 
1524   /// Get address space for OpenCL type.
1525   LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1526 
1527   /// Returns default address space based on OpenCL version and enabled features
1528   inline LangAS getDefaultOpenCLPointeeAddrSpace() {
1529     return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic
1530                                               : LangAS::opencl_private;
1531   }
1532 
1533   void setcudaConfigureCallDecl(FunctionDecl *FD) {
1534     cudaConfigureCallDecl = FD;
1535   }
1536 
1537   FunctionDecl *getcudaConfigureCallDecl() {
1538     return cudaConfigureCallDecl;
1539   }
1540 
1541   /// Returns true iff we need copy/dispose helpers for the given type.
1542   bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1543 
1544   /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1545   /// is set to false in this case. If HasByrefExtendedLayout returns true,
1546   /// byref variable has extended lifetime.
1547   bool getByrefLifetime(QualType Ty,
1548                         Qualifiers::ObjCLifetime &Lifetime,
1549                         bool &HasByrefExtendedLayout) const;
1550 
1551   /// Return the uniqued reference to the type for an lvalue reference
1552   /// to the specified type.
1553   QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1554     const;
1555 
1556   /// Return the uniqued reference to the type for an rvalue reference
1557   /// to the specified type.
1558   QualType getRValueReferenceType(QualType T) const;
1559 
1560   /// Return the uniqued reference to the type for a member pointer to
1561   /// the specified type in the specified class.
1562   ///
1563   /// The class \p Cls is a \c Type because it could be a dependent name.
1564   QualType getMemberPointerType(QualType T, const Type *Cls) const;
1565 
1566   /// Return a non-unique reference to the type for a variable array of
1567   /// the specified element type.
1568   QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1569                                 ArraySizeModifier ASM, unsigned IndexTypeQuals,
1570                                 SourceRange Brackets) const;
1571 
1572   /// Return a non-unique reference to the type for a dependently-sized
1573   /// array of the specified element type.
1574   ///
1575   /// FIXME: We will need these to be uniqued, or at least comparable, at some
1576   /// point.
1577   QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1578                                       ArraySizeModifier ASM,
1579                                       unsigned IndexTypeQuals,
1580                                       SourceRange Brackets) const;
1581 
1582   /// Return a unique reference to the type for an incomplete array of
1583   /// the specified element type.
1584   QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM,
1585                                   unsigned IndexTypeQuals) const;
1586 
1587   /// Return the unique reference to the type for a constant array of
1588   /// the specified element type.
1589   QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1590                                 const Expr *SizeExpr, ArraySizeModifier ASM,
1591                                 unsigned IndexTypeQuals) const;
1592 
1593   /// Return a type for a constant array for a string literal of the
1594   /// specified element type and length.
1595   QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1596 
1597   /// Returns a vla type where known sizes are replaced with [*].
1598   QualType getVariableArrayDecayedType(QualType Ty) const;
1599 
1600   // Convenience struct to return information about a builtin vector type.
1601   struct BuiltinVectorTypeInfo {
1602     QualType ElementType;
1603     llvm::ElementCount EC;
1604     unsigned NumVectors;
1605     BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1606                           unsigned NumVectors)
1607         : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1608   };
1609 
1610   /// Returns the element type, element count and number of vectors
1611   /// (in case of tuple) for a builtin vector type.
1612   BuiltinVectorTypeInfo
1613   getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1614 
1615   /// Return the unique reference to a scalable vector type of the specified
1616   /// element type and scalable number of elements.
1617   /// For RISC-V, number of fields is also provided when it fetching for
1618   /// tuple type.
1619   ///
1620   /// \pre \p EltTy must be a built-in type.
1621   QualType getScalableVectorType(QualType EltTy, unsigned NumElts,
1622                                  unsigned NumFields = 1) const;
1623 
1624   /// Return a WebAssembly externref type.
1625   QualType getWebAssemblyExternrefType() const;
1626 
1627   /// Return the unique reference to a vector type of the specified
1628   /// element type and size.
1629   ///
1630   /// \pre \p VectorType must be a built-in type.
1631   QualType getVectorType(QualType VectorType, unsigned NumElts,
1632                          VectorKind VecKind) const;
1633   /// Return the unique reference to the type for a dependently sized vector of
1634   /// the specified element type.
1635   QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1636                                   SourceLocation AttrLoc,
1637                                   VectorKind VecKind) const;
1638 
1639   /// Return the unique reference to an extended vector type
1640   /// of the specified element type and size.
1641   ///
1642   /// \pre \p VectorType must be a built-in type.
1643   QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1644 
1645   /// \pre Return a non-unique reference to the type for a dependently-sized
1646   /// vector of the specified element type.
1647   ///
1648   /// FIXME: We will need these to be uniqued, or at least comparable, at some
1649   /// point.
1650   QualType getDependentSizedExtVectorType(QualType VectorType,
1651                                           Expr *SizeExpr,
1652                                           SourceLocation AttrLoc) const;
1653 
1654   /// Return the unique reference to the matrix type of the specified element
1655   /// type and size
1656   ///
1657   /// \pre \p ElementType must be a valid matrix element type (see
1658   /// MatrixType::isValidElementType).
1659   QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1660                                  unsigned NumColumns) const;
1661 
1662   /// Return the unique reference to the matrix type of the specified element
1663   /// type and size
1664   QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1665                                        Expr *ColumnExpr,
1666                                        SourceLocation AttrLoc) const;
1667 
1668   QualType getDependentAddressSpaceType(QualType PointeeType,
1669                                         Expr *AddrSpaceExpr,
1670                                         SourceLocation AttrLoc) const;
1671 
1672   /// Return a K&R style C function type like 'int()'.
1673   QualType getFunctionNoProtoType(QualType ResultTy,
1674                                   const FunctionType::ExtInfo &Info) const;
1675 
1676   QualType getFunctionNoProtoType(QualType ResultTy) const {
1677     return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1678   }
1679 
1680   /// Return a normal function type with a typed argument list.
1681   QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1682                            const FunctionProtoType::ExtProtoInfo &EPI) const {
1683     return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1684   }
1685 
1686   QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1687 
1688 private:
1689   /// Return a normal function type with a typed argument list.
1690   QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1691                                    const FunctionProtoType::ExtProtoInfo &EPI,
1692                                    bool OnlyWantCanonical) const;
1693   QualType
1694   getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword,
1695                       bool IsDependent, bool IsPack = false,
1696                       ConceptDecl *TypeConstraintConcept = nullptr,
1697                       ArrayRef<TemplateArgument> TypeConstraintArgs = {},
1698                       bool IsCanon = false) const;
1699 
1700 public:
1701   /// Return the unique reference to the type for the specified type
1702   /// declaration.
1703   QualType getTypeDeclType(const TypeDecl *Decl,
1704                            const TypeDecl *PrevDecl = nullptr) const {
1705     assert(Decl && "Passed null for Decl param");
1706     if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1707 
1708     if (PrevDecl) {
1709       assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1710       Decl->TypeForDecl = PrevDecl->TypeForDecl;
1711       return QualType(PrevDecl->TypeForDecl, 0);
1712     }
1713 
1714     return getTypeDeclTypeSlow(Decl);
1715   }
1716 
1717   QualType getUsingType(const UsingShadowDecl *Found,
1718                         QualType Underlying) const;
1719 
1720   /// Return the unique reference to the type for the specified
1721   /// typedef-name decl.
1722   QualType getTypedefType(const TypedefNameDecl *Decl,
1723                           QualType Underlying = QualType()) const;
1724 
1725   QualType getRecordType(const RecordDecl *Decl) const;
1726 
1727   QualType getEnumType(const EnumDecl *Decl) const;
1728 
1729   /// Compute BestType and BestPromotionType for an enum based on the highest
1730   /// number of negative and positive bits of its elements.
1731   /// Returns true if enum width is too large.
1732   bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
1733                             unsigned NumPositiveBits, QualType &BestType,
1734                             QualType &BestPromotionType);
1735 
1736   QualType
1737   getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const;
1738 
1739   QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1740 
1741   QualType getAttributedType(attr::Kind attrKind, QualType modifiedType,
1742                              QualType equivalentType,
1743                              const Attr *attr = nullptr) const;
1744 
1745   QualType getAttributedType(const Attr *attr, QualType modifiedType,
1746                              QualType equivalentType) const;
1747 
1748   QualType getAttributedType(NullabilityKind nullability, QualType modifiedType,
1749                              QualType equivalentType);
1750 
1751   QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
1752                                    QualType Wrapped) const;
1753 
1754   QualType getHLSLAttributedResourceType(
1755       QualType Wrapped, QualType Contained,
1756       const HLSLAttributedResourceType::Attributes &Attrs);
1757 
1758   QualType
1759   getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
1760                                unsigned Index,
1761                                std::optional<unsigned> PackIndex,
1762                                SubstTemplateTypeParmTypeFlag Flag =
1763                                    SubstTemplateTypeParmTypeFlag::None) const;
1764   QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
1765                                             unsigned Index, bool Final,
1766                                             const TemplateArgument &ArgPack);
1767 
1768   QualType
1769   getTemplateTypeParmType(unsigned Depth, unsigned Index,
1770                           bool ParameterPack,
1771                           TemplateTypeParmDecl *ParmDecl = nullptr) const;
1772 
1773   QualType getTemplateSpecializationType(TemplateName T,
1774                                          ArrayRef<TemplateArgument> Args,
1775                                          QualType Canon = QualType()) const;
1776 
1777   QualType
1778   getCanonicalTemplateSpecializationType(TemplateName T,
1779                                          ArrayRef<TemplateArgument> Args) const;
1780 
1781   QualType getTemplateSpecializationType(TemplateName T,
1782                                          ArrayRef<TemplateArgumentLoc> Args,
1783                                          QualType Canon = QualType()) const;
1784 
1785   TypeSourceInfo *
1786   getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1787                                     const TemplateArgumentListInfo &Args,
1788                                     QualType Canon = QualType()) const;
1789 
1790   QualType getParenType(QualType NamedType) const;
1791 
1792   QualType getMacroQualifiedType(QualType UnderlyingTy,
1793                                  const IdentifierInfo *MacroII) const;
1794 
1795   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1796                              NestedNameSpecifier *NNS, QualType NamedType,
1797                              TagDecl *OwnedTagDecl = nullptr) const;
1798   QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1799                                 NestedNameSpecifier *NNS,
1800                                 const IdentifierInfo *Name,
1801                                 QualType Canon = QualType()) const;
1802 
1803   QualType getDependentTemplateSpecializationType(
1804       ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1805       const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const;
1806   QualType getDependentTemplateSpecializationType(
1807       ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1808       const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1809 
1810   TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const;
1811 
1812   /// Form a pack expansion type with the given pattern.
1813   /// \param NumExpansions The number of expansions for the pack, if known.
1814   /// \param ExpectPackInType If \c false, we should not expect \p Pattern to
1815   ///        contain an unexpanded pack. This only makes sense if the pack
1816   ///        expansion is used in a context where the arity is inferred from
1817   ///        elsewhere, such as if the pattern contains a placeholder type or
1818   ///        if this is the canonical type of another pack expansion type.
1819   QualType getPackExpansionType(QualType Pattern,
1820                                 std::optional<unsigned> NumExpansions,
1821                                 bool ExpectPackInType = true) const;
1822 
1823   QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1824                                 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1825 
1826   /// Legacy interface: cannot provide type arguments or __kindof.
1827   QualType getObjCObjectType(QualType Base,
1828                              ObjCProtocolDecl * const *Protocols,
1829                              unsigned NumProtocols) const;
1830 
1831   QualType getObjCObjectType(QualType Base,
1832                              ArrayRef<QualType> typeArgs,
1833                              ArrayRef<ObjCProtocolDecl *> protocols,
1834                              bool isKindOf) const;
1835 
1836   QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1837                                 ArrayRef<ObjCProtocolDecl *> protocols) const;
1838   void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1839                                     ObjCTypeParamDecl *New) const;
1840 
1841   bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1842 
1843   /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1844   /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1845   /// of protocols.
1846   bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1847                                             ObjCInterfaceDecl *IDecl);
1848 
1849   /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1850   QualType getObjCObjectPointerType(QualType OIT) const;
1851 
1852   /// C23 feature and GCC extension.
1853   QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const;
1854   QualType getTypeOfType(QualType QT, TypeOfKind Kind) const;
1855 
1856   QualType getReferenceQualifiedType(const Expr *e) const;
1857 
1858   /// C++11 decltype.
1859   QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1860 
1861   QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr,
1862                                bool FullySubstituted = false,
1863                                ArrayRef<QualType> Expansions = {},
1864                                int Index = -1) const;
1865 
1866   /// Unary type transforms
1867   QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1868                                  UnaryTransformType::UTTKind UKind) const;
1869 
1870   /// C++11 deduced auto type.
1871   QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1872                        bool IsDependent, bool IsPack = false,
1873                        ConceptDecl *TypeConstraintConcept = nullptr,
1874                        ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1875 
1876   /// C++11 deduction pattern for 'auto' type.
1877   QualType getAutoDeductType() const;
1878 
1879   /// C++11 deduction pattern for 'auto &&' type.
1880   QualType getAutoRRefDeductType() const;
1881 
1882   /// Remove any type constraints from a template parameter type, for
1883   /// equivalence comparison of template parameters.
1884   QualType getUnconstrainedType(QualType T) const;
1885 
1886   /// C++17 deduced class template specialization type.
1887   QualType getDeducedTemplateSpecializationType(TemplateName Template,
1888                                                 QualType DeducedType,
1889                                                 bool IsDependent) const;
1890 
1891 private:
1892   QualType getDeducedTemplateSpecializationTypeInternal(TemplateName Template,
1893                                                         QualType DeducedType,
1894                                                         bool IsDependent,
1895                                                         QualType Canon) const;
1896 
1897 public:
1898   /// Return the unique reference to the type for the specified TagDecl
1899   /// (struct/union/class/enum) decl.
1900   QualType getTagDeclType(const TagDecl *Decl) const;
1901 
1902   /// Return the unique type for "size_t" (C99 7.17), defined in
1903   /// <stddef.h>.
1904   ///
1905   /// The sizeof operator requires this (C99 6.5.3.4p4).
1906   CanQualType getSizeType() const;
1907 
1908   /// Return the unique signed counterpart of
1909   /// the integer type corresponding to size_t.
1910   CanQualType getSignedSizeType() const;
1911 
1912   /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1913   /// <stdint.h>.
1914   CanQualType getIntMaxType() const;
1915 
1916   /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1917   /// <stdint.h>.
1918   CanQualType getUIntMaxType() const;
1919 
1920   /// Return the unique wchar_t type available in C++ (and available as
1921   /// __wchar_t as a Microsoft extension).
1922   QualType getWCharType() const { return WCharTy; }
1923 
1924   /// Return the type of wide characters. In C++, this returns the
1925   /// unique wchar_t type. In C99, this returns a type compatible with the type
1926   /// defined in <stddef.h> as defined by the target.
1927   QualType getWideCharType() const { return WideCharTy; }
1928 
1929   /// Return the type of "signed wchar_t".
1930   ///
1931   /// Used when in C++, as a GCC extension.
1932   QualType getSignedWCharType() const;
1933 
1934   /// Return the type of "unsigned wchar_t".
1935   ///
1936   /// Used when in C++, as a GCC extension.
1937   QualType getUnsignedWCharType() const;
1938 
1939   /// In C99, this returns a type compatible with the type
1940   /// defined in <stddef.h> as defined by the target.
1941   QualType getWIntType() const { return WIntTy; }
1942 
1943   /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1944   /// as defined by the target.
1945   QualType getIntPtrType() const;
1946 
1947   /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1948   /// as defined by the target.
1949   QualType getUIntPtrType() const;
1950 
1951   /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1952   /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1953   QualType getPointerDiffType() const;
1954 
1955   /// Return the unique unsigned counterpart of "ptrdiff_t"
1956   /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1957   /// in the definition of %tu format specifier.
1958   QualType getUnsignedPointerDiffType() const;
1959 
1960   /// Return the unique type for "pid_t" defined in
1961   /// <sys/types.h>. We need this to compute the correct type for vfork().
1962   QualType getProcessIDType() const;
1963 
1964   /// Return the C structure type used to represent constant CFStrings.
1965   QualType getCFConstantStringType() const;
1966 
1967   /// Returns the C struct type for objc_super
1968   QualType getObjCSuperType() const;
1969   void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1970 
1971   /// Get the structure type used to representation CFStrings, or NULL
1972   /// if it hasn't yet been built.
1973   QualType getRawCFConstantStringType() const {
1974     if (CFConstantStringTypeDecl)
1975       return getTypedefType(CFConstantStringTypeDecl);
1976     return QualType();
1977   }
1978   void setCFConstantStringType(QualType T);
1979   TypedefDecl *getCFConstantStringDecl() const;
1980   RecordDecl *getCFConstantStringTagDecl() const;
1981 
1982   // This setter/getter represents the ObjC type for an NSConstantString.
1983   void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1984   QualType getObjCConstantStringInterface() const {
1985     return ObjCConstantStringType;
1986   }
1987 
1988   QualType getObjCNSStringType() const {
1989     return ObjCNSStringType;
1990   }
1991 
1992   void setObjCNSStringType(QualType T) {
1993     ObjCNSStringType = T;
1994   }
1995 
1996   /// Retrieve the type that \c id has been defined to, which may be
1997   /// different from the built-in \c id if \c id has been typedef'd.
1998   QualType getObjCIdRedefinitionType() const {
1999     if (ObjCIdRedefinitionType.isNull())
2000       return getObjCIdType();
2001     return ObjCIdRedefinitionType;
2002   }
2003 
2004   /// Set the user-written type that redefines \c id.
2005   void setObjCIdRedefinitionType(QualType RedefType) {
2006     ObjCIdRedefinitionType = RedefType;
2007   }
2008 
2009   /// Retrieve the type that \c Class has been defined to, which may be
2010   /// different from the built-in \c Class if \c Class has been typedef'd.
2011   QualType getObjCClassRedefinitionType() const {
2012     if (ObjCClassRedefinitionType.isNull())
2013       return getObjCClassType();
2014     return ObjCClassRedefinitionType;
2015   }
2016 
2017   /// Set the user-written type that redefines 'SEL'.
2018   void setObjCClassRedefinitionType(QualType RedefType) {
2019     ObjCClassRedefinitionType = RedefType;
2020   }
2021 
2022   /// Retrieve the type that 'SEL' has been defined to, which may be
2023   /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
2024   QualType getObjCSelRedefinitionType() const {
2025     if (ObjCSelRedefinitionType.isNull())
2026       return getObjCSelType();
2027     return ObjCSelRedefinitionType;
2028   }
2029 
2030   /// Set the user-written type that redefines 'SEL'.
2031   void setObjCSelRedefinitionType(QualType RedefType) {
2032     ObjCSelRedefinitionType = RedefType;
2033   }
2034 
2035   /// Retrieve the identifier 'NSObject'.
2036   IdentifierInfo *getNSObjectName() const {
2037     if (!NSObjectName) {
2038       NSObjectName = &Idents.get("NSObject");
2039     }
2040 
2041     return NSObjectName;
2042   }
2043 
2044   /// Retrieve the identifier 'NSCopying'.
2045   IdentifierInfo *getNSCopyingName() {
2046     if (!NSCopyingName) {
2047       NSCopyingName = &Idents.get("NSCopying");
2048     }
2049 
2050     return NSCopyingName;
2051   }
2052 
2053   CanQualType getNSUIntegerType() const;
2054 
2055   CanQualType getNSIntegerType() const;
2056 
2057   /// Retrieve the identifier 'bool'.
2058   IdentifierInfo *getBoolName() const {
2059     if (!BoolName)
2060       BoolName = &Idents.get("bool");
2061     return BoolName;
2062   }
2063 
2064   IdentifierInfo *getMakeIntegerSeqName() const {
2065     if (!MakeIntegerSeqName)
2066       MakeIntegerSeqName = &Idents.get("__make_integer_seq");
2067     return MakeIntegerSeqName;
2068   }
2069 
2070   IdentifierInfo *getTypePackElementName() const {
2071     if (!TypePackElementName)
2072       TypePackElementName = &Idents.get("__type_pack_element");
2073     return TypePackElementName;
2074   }
2075 
2076   IdentifierInfo *getBuiltinCommonTypeName() const {
2077     if (!BuiltinCommonTypeName)
2078       BuiltinCommonTypeName = &Idents.get("__builtin_common_type");
2079     return BuiltinCommonTypeName;
2080   }
2081 
2082   /// Retrieve the Objective-C "instancetype" type, if already known;
2083   /// otherwise, returns a NULL type;
2084   QualType getObjCInstanceType() {
2085     return getTypeDeclType(getObjCInstanceTypeDecl());
2086   }
2087 
2088   /// Retrieve the typedef declaration corresponding to the Objective-C
2089   /// "instancetype" type.
2090   TypedefDecl *getObjCInstanceTypeDecl();
2091 
2092   /// Set the type for the C FILE type.
2093   void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
2094 
2095   /// Retrieve the C FILE type.
2096   QualType getFILEType() const {
2097     if (FILEDecl)
2098       return getTypeDeclType(FILEDecl);
2099     return QualType();
2100   }
2101 
2102   /// Set the type for the C jmp_buf type.
2103   void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
2104     this->jmp_bufDecl = jmp_bufDecl;
2105   }
2106 
2107   /// Retrieve the C jmp_buf type.
2108   QualType getjmp_bufType() const {
2109     if (jmp_bufDecl)
2110       return getTypeDeclType(jmp_bufDecl);
2111     return QualType();
2112   }
2113 
2114   /// Set the type for the C sigjmp_buf type.
2115   void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
2116     this->sigjmp_bufDecl = sigjmp_bufDecl;
2117   }
2118 
2119   /// Retrieve the C sigjmp_buf type.
2120   QualType getsigjmp_bufType() const {
2121     if (sigjmp_bufDecl)
2122       return getTypeDeclType(sigjmp_bufDecl);
2123     return QualType();
2124   }
2125 
2126   /// Set the type for the C ucontext_t type.
2127   void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
2128     this->ucontext_tDecl = ucontext_tDecl;
2129   }
2130 
2131   /// Retrieve the C ucontext_t type.
2132   QualType getucontext_tType() const {
2133     if (ucontext_tDecl)
2134       return getTypeDeclType(ucontext_tDecl);
2135     return QualType();
2136   }
2137 
2138   /// The result type of logical operations, '<', '>', '!=', etc.
2139   QualType getLogicalOperationType() const {
2140     return getLangOpts().CPlusPlus ? BoolTy : IntTy;
2141   }
2142 
2143   /// Emit the Objective-CC type encoding for the given type \p T into
2144   /// \p S.
2145   ///
2146   /// If \p Field is specified then record field names are also encoded.
2147   void getObjCEncodingForType(QualType T, std::string &S,
2148                               const FieldDecl *Field=nullptr,
2149                               QualType *NotEncodedT=nullptr) const;
2150 
2151   /// Emit the Objective-C property type encoding for the given
2152   /// type \p T into \p S.
2153   void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
2154 
2155   void getLegacyIntegralTypeEncoding(QualType &t) const;
2156 
2157   /// Put the string version of the type qualifiers \p QT into \p S.
2158   void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2159                                        std::string &S) const;
2160 
2161   /// Emit the encoded type for the function \p Decl into \p S.
2162   ///
2163   /// This is in the same format as Objective-C method encodings.
2164   ///
2165   /// \returns true if an error occurred (e.g., because one of the parameter
2166   /// types is incomplete), false otherwise.
2167   std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
2168 
2169   /// Emit the encoded type for the method declaration \p Decl into
2170   /// \p S.
2171   std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2172                                            bool Extended = false) const;
2173 
2174   /// Return the encoded type for this block declaration.
2175   std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
2176 
2177   /// getObjCEncodingForPropertyDecl - Return the encoded type for
2178   /// this method declaration. If non-NULL, Container must be either
2179   /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
2180   /// only be NULL when getting encodings for protocol properties.
2181   std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2182                                              const Decl *Container) const;
2183 
2184   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
2185                                       ObjCProtocolDecl *rProto) const;
2186 
2187   ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
2188                                                   const ObjCPropertyDecl *PD,
2189                                                   const Decl *Container) const;
2190 
2191   /// Return the size of type \p T for Objective-C encoding purpose,
2192   /// in characters.
2193   CharUnits getObjCEncodingTypeSize(QualType T) const;
2194 
2195   /// Retrieve the typedef corresponding to the predefined \c id type
2196   /// in Objective-C.
2197   TypedefDecl *getObjCIdDecl() const;
2198 
2199   /// Represents the Objective-CC \c id type.
2200   ///
2201   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
2202   /// pointer type, a pointer to a struct.
2203   QualType getObjCIdType() const {
2204     return getTypeDeclType(getObjCIdDecl());
2205   }
2206 
2207   /// Retrieve the typedef corresponding to the predefined 'SEL' type
2208   /// in Objective-C.
2209   TypedefDecl *getObjCSelDecl() const;
2210 
2211   /// Retrieve the type that corresponds to the predefined Objective-C
2212   /// 'SEL' type.
2213   QualType getObjCSelType() const {
2214     return getTypeDeclType(getObjCSelDecl());
2215   }
2216 
2217   /// Retrieve the typedef declaration corresponding to the predefined
2218   /// Objective-C 'Class' type.
2219   TypedefDecl *getObjCClassDecl() const;
2220 
2221   /// Represents the Objective-C \c Class type.
2222   ///
2223   /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
2224   /// pointer type, a pointer to a struct.
2225   QualType getObjCClassType() const {
2226     return getTypeDeclType(getObjCClassDecl());
2227   }
2228 
2229   /// Retrieve the Objective-C class declaration corresponding to
2230   /// the predefined \c Protocol class.
2231   ObjCInterfaceDecl *getObjCProtocolDecl() const;
2232 
2233   /// Retrieve declaration of 'BOOL' typedef
2234   TypedefDecl *getBOOLDecl() const {
2235     return BOOLDecl;
2236   }
2237 
2238   /// Save declaration of 'BOOL' typedef
2239   void setBOOLDecl(TypedefDecl *TD) {
2240     BOOLDecl = TD;
2241   }
2242 
2243   /// type of 'BOOL' type.
2244   QualType getBOOLType() const {
2245     return getTypeDeclType(getBOOLDecl());
2246   }
2247 
2248   /// Retrieve the type of the Objective-C \c Protocol class.
2249   QualType getObjCProtoType() const {
2250     return getObjCInterfaceType(getObjCProtocolDecl());
2251   }
2252 
2253   /// Retrieve the C type declaration corresponding to the predefined
2254   /// \c __builtin_va_list type.
2255   TypedefDecl *getBuiltinVaListDecl() const;
2256 
2257   /// Retrieve the type of the \c __builtin_va_list type.
2258   QualType getBuiltinVaListType() const {
2259     return getTypeDeclType(getBuiltinVaListDecl());
2260   }
2261 
2262   /// Retrieve the C type declaration corresponding to the predefined
2263   /// \c __va_list_tag type used to help define the \c __builtin_va_list type
2264   /// for some targets.
2265   Decl *getVaListTagDecl() const;
2266 
2267   /// Retrieve the C type declaration corresponding to the predefined
2268   /// \c __builtin_ms_va_list type.
2269   TypedefDecl *getBuiltinMSVaListDecl() const;
2270 
2271   /// Retrieve the type of the \c __builtin_ms_va_list type.
2272   QualType getBuiltinMSVaListType() const {
2273     return getTypeDeclType(getBuiltinMSVaListDecl());
2274   }
2275 
2276   /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
2277   TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
2278 
2279   /// Retrieve the implicitly-predeclared 'struct _GUID' type.
2280   QualType getMSGuidType() const {
2281     assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
2282     return getTagDeclType(MSGuidTagDecl);
2283   }
2284 
2285   /// Return whether a declaration to a builtin is allowed to be
2286   /// overloaded/redeclared.
2287   bool canBuiltinBeRedeclared(const FunctionDecl *) const;
2288 
2289   /// Return a type with additional \c const, \c volatile, or
2290   /// \c restrict qualifiers.
2291   QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
2292     return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
2293   }
2294 
2295   /// Un-split a SplitQualType.
2296   QualType getQualifiedType(SplitQualType split) const {
2297     return getQualifiedType(split.Ty, split.Quals);
2298   }
2299 
2300   /// Return a type with additional qualifiers.
2301   QualType getQualifiedType(QualType T, Qualifiers Qs) const {
2302     if (!Qs.hasNonFastQualifiers())
2303       return T.withFastQualifiers(Qs.getFastQualifiers());
2304     QualifierCollector Qc(Qs);
2305     const Type *Ptr = Qc.strip(T);
2306     return getExtQualType(Ptr, Qc);
2307   }
2308 
2309   /// Return a type with additional qualifiers.
2310   QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
2311     if (!Qs.hasNonFastQualifiers())
2312       return QualType(T, Qs.getFastQualifiers());
2313     return getExtQualType(T, Qs);
2314   }
2315 
2316   /// Return a type with the given lifetime qualifier.
2317   ///
2318   /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
2319   QualType getLifetimeQualifiedType(QualType type,
2320                                     Qualifiers::ObjCLifetime lifetime) {
2321     assert(type.getObjCLifetime() == Qualifiers::OCL_None);
2322     assert(lifetime != Qualifiers::OCL_None);
2323 
2324     Qualifiers qs;
2325     qs.addObjCLifetime(lifetime);
2326     return getQualifiedType(type, qs);
2327   }
2328 
2329   /// getUnqualifiedObjCPointerType - Returns version of
2330   /// Objective-C pointer type with lifetime qualifier removed.
2331   QualType getUnqualifiedObjCPointerType(QualType type) const {
2332     if (!type.getTypePtr()->isObjCObjectPointerType() ||
2333         !type.getQualifiers().hasObjCLifetime())
2334       return type;
2335     Qualifiers Qs = type.getQualifiers();
2336     Qs.removeObjCLifetime();
2337     return getQualifiedType(type.getUnqualifiedType(), Qs);
2338   }
2339 
2340   /// \brief Return a type with the given __ptrauth qualifier.
2341   QualType getPointerAuthType(QualType Ty, PointerAuthQualifier PointerAuth) {
2342     assert(!Ty.getPointerAuth());
2343     assert(PointerAuth);
2344 
2345     Qualifiers Qs;
2346     Qs.setPointerAuth(PointerAuth);
2347     return getQualifiedType(Ty, Qs);
2348   }
2349 
2350   unsigned char getFixedPointScale(QualType Ty) const;
2351   unsigned char getFixedPointIBits(QualType Ty) const;
2352   llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
2353   llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
2354   llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
2355 
2356   DeclarationNameInfo getNameForTemplate(TemplateName Name,
2357                                          SourceLocation NameLoc) const;
2358 
2359   TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
2360                                          UnresolvedSetIterator End) const;
2361   TemplateName getAssumedTemplateName(DeclarationName Name) const;
2362 
2363   TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
2364                                         bool TemplateKeyword,
2365                                         TemplateName Template) const;
2366 
2367   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2368                                         const IdentifierInfo *Name) const;
2369   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2370                                         OverloadedOperatorKind Operator) const;
2371   TemplateName
2372   getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl,
2373                                unsigned Index,
2374                                std::optional<unsigned> PackIndex) const;
2375   TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
2376                                                 Decl *AssociatedDecl,
2377                                                 unsigned Index,
2378                                                 bool Final) const;
2379 
2380   /// Represents a TemplateName which had some of its default arguments
2381   /// deduced. This both represents this default argument deduction as sugar,
2382   /// and provides the support for it's equivalences through canonicalization.
2383   /// For example DeducedTemplateNames which have the same set of default
2384   /// arguments are equivalent, and are also equivalent to the underlying
2385   /// template when the deduced template arguments are the same.
2386   TemplateName getDeducedTemplateName(TemplateName Underlying,
2387                                       DefaultArguments DefaultArgs) const;
2388 
2389   enum GetBuiltinTypeError {
2390     /// No error
2391     GE_None,
2392 
2393     /// Missing a type
2394     GE_Missing_type,
2395 
2396     /// Missing a type from <stdio.h>
2397     GE_Missing_stdio,
2398 
2399     /// Missing a type from <setjmp.h>
2400     GE_Missing_setjmp,
2401 
2402     /// Missing a type from <ucontext.h>
2403     GE_Missing_ucontext
2404   };
2405 
2406   QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
2407                          ASTContext::GetBuiltinTypeError &Error,
2408                          bool &RequireICE, bool AllowTypeModifiers) const;
2409 
2410   /// Return the type for the specified builtin.
2411   ///
2412   /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2413   /// arguments to the builtin that are required to be integer constant
2414   /// expressions.
2415   QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2416                           unsigned *IntegerConstantArgs = nullptr) const;
2417 
2418   /// Types and expressions required to build C++2a three-way comparisons
2419   /// using operator<=>, including the values return by builtin <=> operators.
2420   ComparisonCategories CompCategories;
2421 
2422 private:
2423   CanQualType getFromTargetType(unsigned Type) const;
2424   TypeInfo getTypeInfoImpl(const Type *T) const;
2425 
2426   //===--------------------------------------------------------------------===//
2427   //                         Type Predicates.
2428   //===--------------------------------------------------------------------===//
2429 
2430 public:
2431   /// Return one of the GCNone, Weak or Strong Objective-C garbage
2432   /// collection attributes.
2433   Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2434 
2435   /// Return true if the given vector types are of the same unqualified
2436   /// type or if they are equivalent to the same GCC vector type.
2437   ///
2438   /// \note This ignores whether they are target-specific (AltiVec or Neon)
2439   /// types.
2440   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2441 
2442   /// Return true if the given types are an SVE builtin and a VectorType that
2443   /// is a fixed-length representation of the SVE builtin for a specific
2444   /// vector-length.
2445   bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
2446 
2447   /// Return true if the given vector types are lax-compatible SVE vector types,
2448   /// false otherwise.
2449   bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
2450 
2451   /// Return true if the given types are an RISC-V vector builtin type and a
2452   /// VectorType that is a fixed-length representation of the RISC-V vector
2453   /// builtin type for a specific vector-length.
2454   bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2455 
2456   /// Return true if the given vector types are lax-compatible RISC-V vector
2457   /// types as defined by -flax-vector-conversions=, which permits implicit
2458   /// conversions between vectors with different number of elements and/or
2459   /// incompatible element types, false otherwise.
2460   bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2461 
2462   /// Return true if the type has been explicitly qualified with ObjC ownership.
2463   /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2464   /// some cases the compiler treats these differently.
2465   bool hasDirectOwnershipQualifier(QualType Ty) const;
2466 
2467   /// Return true if this is an \c NSObject object with its \c NSObject
2468   /// attribute set.
2469   static bool isObjCNSObjectType(QualType Ty) {
2470     return Ty->isObjCNSObjectType();
2471   }
2472 
2473   //===--------------------------------------------------------------------===//
2474   //                         Type Sizing and Analysis
2475   //===--------------------------------------------------------------------===//
2476 
2477   /// Return the APFloat 'semantics' for the specified scalar floating
2478   /// point type.
2479   const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2480 
2481   /// Get the size and alignment of the specified complete type in bits.
2482   TypeInfo getTypeInfo(const Type *T) const;
2483   TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2484 
2485   /// Get default simd alignment of the specified complete type in bits.
2486   unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2487 
2488   /// Return the size of the specified (complete) type \p T, in bits.
2489   uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2490   uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2491 
2492   /// Return the size of the character type, in bits.
2493   uint64_t getCharWidth() const {
2494     return getTypeSize(CharTy);
2495   }
2496 
2497   /// Convert a size in bits to a size in characters.
2498   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2499 
2500   /// Convert a size in characters to a size in bits.
2501   int64_t toBits(CharUnits CharSize) const;
2502 
2503   /// Return the size of the specified (complete) type \p T, in
2504   /// characters.
2505   CharUnits getTypeSizeInChars(QualType T) const;
2506   CharUnits getTypeSizeInChars(const Type *T) const;
2507 
2508   std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2509     if (Ty->isIncompleteType() || Ty->isDependentType())
2510       return std::nullopt;
2511     return getTypeSizeInChars(Ty);
2512   }
2513 
2514   std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2515     return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2516   }
2517 
2518   /// Return the ABI-specified alignment of a (complete) type \p T, in
2519   /// bits.
2520   unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2521   unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2522 
2523   /// Return the ABI-specified natural alignment of a (complete) type \p T,
2524   /// before alignment adjustments, in bits.
2525   ///
2526   /// This alignment is curently used only by ARM and AArch64 when passing
2527   /// arguments of a composite type.
2528   unsigned getTypeUnadjustedAlign(QualType T) const {
2529     return getTypeUnadjustedAlign(T.getTypePtr());
2530   }
2531   unsigned getTypeUnadjustedAlign(const Type *T) const;
2532 
2533   /// Return the alignment of a type, in bits, or 0 if
2534   /// the type is incomplete and we cannot determine the alignment (for
2535   /// example, from alignment attributes). The returned alignment is the
2536   /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
2537   /// ABI alignment.
2538   unsigned getTypeAlignIfKnown(QualType T,
2539                                bool NeedsPreferredAlignment = false) const;
2540 
2541   /// Return the ABI-specified alignment of a (complete) type \p T, in
2542   /// characters.
2543   CharUnits getTypeAlignInChars(QualType T) const;
2544   CharUnits getTypeAlignInChars(const Type *T) const;
2545 
2546   /// Return the PreferredAlignment of a (complete) type \p T, in
2547   /// characters.
2548   CharUnits getPreferredTypeAlignInChars(QualType T) const {
2549     return toCharUnitsFromBits(getPreferredTypeAlign(T));
2550   }
2551 
2552   /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2553   /// in characters, before alignment adjustments. This method does not work on
2554   /// incomplete types.
2555   CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2556   CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2557 
2558   // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2559   // type is a record, its data size is returned.
2560   TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
2561 
2562   TypeInfoChars getTypeInfoInChars(const Type *T) const;
2563   TypeInfoChars getTypeInfoInChars(QualType T) const;
2564 
2565   /// Determine if the alignment the type has was required using an
2566   /// alignment attribute.
2567   bool isAlignmentRequired(const Type *T) const;
2568   bool isAlignmentRequired(QualType T) const;
2569 
2570   /// More type predicates useful for type checking/promotion
2571   bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
2572 
2573   /// Return the "preferred" alignment of the specified type \p T for
2574   /// the current target, in bits.
2575   ///
2576   /// This can be different than the ABI alignment in cases where it is
2577   /// beneficial for performance or backwards compatibility preserving to
2578   /// overalign a data type. (Note: despite the name, the preferred alignment
2579   /// is ABI-impacting, and not an optimization.)
2580   unsigned getPreferredTypeAlign(QualType T) const {
2581     return getPreferredTypeAlign(T.getTypePtr());
2582   }
2583   unsigned getPreferredTypeAlign(const Type *T) const;
2584 
2585   /// Return the default alignment for __attribute__((aligned)) on
2586   /// this target, to be used if no alignment value is specified.
2587   unsigned getTargetDefaultAlignForAttributeAligned() const;
2588 
2589   /// Return the alignment in bits that should be given to a
2590   /// global variable with type \p T. If \p VD is non-null it will be
2591   /// considered specifically for the query.
2592   unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
2593 
2594   /// Return the alignment in characters that should be given to a
2595   /// global variable with type \p T. If \p VD is non-null it will be
2596   /// considered specifically for the query.
2597   CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
2598 
2599   /// Return the minimum alignement as specified by the target. If \p VD is
2600   /// non-null it may be used to identify external or weak variables.
2601   unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const;
2602 
2603   /// Return a conservative estimate of the alignment of the specified
2604   /// decl \p D.
2605   ///
2606   /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2607   /// alignment.
2608   ///
2609   /// If \p ForAlignof, references are treated like their underlying type
2610   /// and  large arrays don't get any special treatment. If not \p ForAlignof
2611   /// it computes the value expected by CodeGen: references are treated like
2612   /// pointers and large arrays get extra alignment.
2613   CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2614 
2615   /// Return the alignment (in bytes) of the thrown exception object. This is
2616   /// only meaningful for targets that allocate C++ exceptions in a system
2617   /// runtime, such as those using the Itanium C++ ABI.
2618   CharUnits getExnObjectAlignment() const;
2619 
2620   /// Get or compute information about the layout of the specified
2621   /// record (struct/union/class) \p D, which indicates its size and field
2622   /// position information.
2623   const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2624 
2625   /// Get or compute information about the layout of the specified
2626   /// Objective-C interface.
2627   const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2628     const;
2629 
2630   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2631                         bool Simple = false) const;
2632 
2633   /// Get or compute information about the layout of the specified
2634   /// Objective-C implementation.
2635   ///
2636   /// This may differ from the interface if synthesized ivars are present.
2637   const ASTRecordLayout &
2638   getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2639 
2640   /// Get our current best idea for the key function of the
2641   /// given record decl, or nullptr if there isn't one.
2642   ///
2643   /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2644   ///   ...the first non-pure virtual function that is not inline at the
2645   ///   point of class definition.
2646   ///
2647   /// Other ABIs use the same idea.  However, the ARM C++ ABI ignores
2648   /// virtual functions that are defined 'inline', which means that
2649   /// the result of this computation can change.
2650   const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2651 
2652   /// Observe that the given method cannot be a key function.
2653   /// Checks the key-function cache for the method's class and clears it
2654   /// if matches the given declaration.
2655   ///
2656   /// This is used in ABIs where out-of-line definitions marked
2657   /// inline are not considered to be key functions.
2658   ///
2659   /// \param method should be the declaration from the class definition
2660   void setNonKeyFunction(const CXXMethodDecl *method);
2661 
2662   /// Loading virtual member pointers using the virtual inheritance model
2663   /// always results in an adjustment using the vbtable even if the index is
2664   /// zero.
2665   ///
2666   /// This is usually OK because the first slot in the vbtable points
2667   /// backwards to the top of the MDC.  However, the MDC might be reusing a
2668   /// vbptr from an nv-base.  In this case, the first slot in the vbtable
2669   /// points to the start of the nv-base which introduced the vbptr and *not*
2670   /// the MDC.  Modify the NonVirtualBaseAdjustment to account for this.
2671   CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2672 
2673   /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2674   uint64_t getFieldOffset(const ValueDecl *FD) const;
2675 
2676   /// Get the offset of an ObjCIvarDecl in bits.
2677   uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2678                                 const ObjCImplementationDecl *ID,
2679                                 const ObjCIvarDecl *Ivar) const;
2680 
2681   /// Find the 'this' offset for the member path in a pointer-to-member
2682   /// APValue.
2683   CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
2684 
2685   bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2686 
2687   VTableContextBase *getVTableContext();
2688 
2689   /// If \p T is null pointer, assume the target in ASTContext.
2690   MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2691 
2692   /// Creates a device mangle context to correctly mangle lambdas in a mixed
2693   /// architecture compile by setting the lambda mangling number source to the
2694   /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo
2695   /// (from the AuxTargetInfo) is a an itanium target.
2696   MangleContext *createDeviceMangleContext(const TargetInfo &T);
2697 
2698   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2699                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2700 
2701   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2702   void CollectInheritedProtocols(const Decl *CDecl,
2703                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2704 
2705   /// Return true if the specified type has unique object representations
2706   /// according to (C++17 [meta.unary.prop]p9)
2707   bool
2708   hasUniqueObjectRepresentations(QualType Ty,
2709                                  bool CheckIfTriviallyCopyable = true) const;
2710 
2711   //===--------------------------------------------------------------------===//
2712   //                            Type Operators
2713   //===--------------------------------------------------------------------===//
2714 
2715   /// Return the canonical (structural) type corresponding to the
2716   /// specified potentially non-canonical type \p T.
2717   ///
2718   /// The non-canonical version of a type may have many "decorated" versions of
2719   /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
2720   /// returned type is guaranteed to be free of any of these, allowing two
2721   /// canonical types to be compared for exact equality with a simple pointer
2722   /// comparison.
2723   CanQualType getCanonicalType(QualType T) const {
2724     return CanQualType::CreateUnsafe(T.getCanonicalType());
2725   }
2726 
2727   const Type *getCanonicalType(const Type *T) const {
2728     return T->getCanonicalTypeInternal().getTypePtr();
2729   }
2730 
2731   /// Return the canonical parameter type corresponding to the specific
2732   /// potentially non-canonical one.
2733   ///
2734   /// Qualifiers are stripped off, functions are turned into function
2735   /// pointers, and arrays decay one level into pointers.
2736   CanQualType getCanonicalParamType(QualType T) const;
2737 
2738   /// Determine whether the given types \p T1 and \p T2 are equivalent.
2739   bool hasSameType(QualType T1, QualType T2) const {
2740     return getCanonicalType(T1) == getCanonicalType(T2);
2741   }
2742   bool hasSameType(const Type *T1, const Type *T2) const {
2743     return getCanonicalType(T1) == getCanonicalType(T2);
2744   }
2745 
2746   /// Determine whether the given expressions \p X and \p Y are equivalent.
2747   bool hasSameExpr(const Expr *X, const Expr *Y) const;
2748 
2749   /// Return this type as a completely-unqualified array type,
2750   /// capturing the qualifiers in \p Quals.
2751   ///
2752   /// This will remove the minimal amount of sugaring from the types, similar
2753   /// to the behavior of QualType::getUnqualifiedType().
2754   ///
2755   /// \param T is the qualified type, which may be an ArrayType
2756   ///
2757   /// \param Quals will receive the full set of qualifiers that were
2758   /// applied to the array.
2759   ///
2760   /// \returns if this is an array type, the completely unqualified array type
2761   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2762   QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const;
2763   QualType getUnqualifiedArrayType(QualType T) const {
2764     Qualifiers Quals;
2765     return getUnqualifiedArrayType(T, Quals);
2766   }
2767 
2768   /// Determine whether the given types are equivalent after
2769   /// cvr-qualifiers have been removed.
2770   bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2771     return getCanonicalType(T1).getTypePtr() ==
2772            getCanonicalType(T2).getTypePtr();
2773   }
2774 
2775   bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2776                                        bool IsParam) const {
2777     auto SubTnullability = SubT->getNullability();
2778     auto SuperTnullability = SuperT->getNullability();
2779     if (SubTnullability.has_value() == SuperTnullability.has_value()) {
2780       // Neither has nullability; return true
2781       if (!SubTnullability)
2782         return true;
2783       // Both have nullability qualifier.
2784       if (*SubTnullability == *SuperTnullability ||
2785           *SubTnullability == NullabilityKind::Unspecified ||
2786           *SuperTnullability == NullabilityKind::Unspecified)
2787         return true;
2788 
2789       if (IsParam) {
2790         // Ok for the superclass method parameter to be "nonnull" and the subclass
2791         // method parameter to be "nullable"
2792         return (*SuperTnullability == NullabilityKind::NonNull &&
2793                 *SubTnullability == NullabilityKind::Nullable);
2794       }
2795       // For the return type, it's okay for the superclass method to specify
2796       // "nullable" and the subclass method specify "nonnull"
2797       return (*SuperTnullability == NullabilityKind::Nullable &&
2798               *SubTnullability == NullabilityKind::NonNull);
2799     }
2800     return true;
2801   }
2802 
2803   bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2804                            const ObjCMethodDecl *MethodImp);
2805 
2806   bool UnwrapSimilarTypes(QualType &T1, QualType &T2,
2807                           bool AllowPiMismatch = true) const;
2808   void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
2809                                bool AllowPiMismatch = true) const;
2810 
2811   /// Determine if two types are similar, according to the C++ rules. That is,
2812   /// determine if they are the same other than qualifiers on the initial
2813   /// sequence of pointer / pointer-to-member / array (and in Clang, object
2814   /// pointer) types and their element types.
2815   ///
2816   /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2817   /// those qualifiers are also ignored in the 'similarity' check.
2818   bool hasSimilarType(QualType T1, QualType T2) const;
2819 
2820   /// Determine if two types are similar, ignoring only CVR qualifiers.
2821   bool hasCvrSimilarType(QualType T1, QualType T2);
2822 
2823   /// Retrieves the "canonical" nested name specifier for a
2824   /// given nested name specifier.
2825   ///
2826   /// The canonical nested name specifier is a nested name specifier
2827   /// that uniquely identifies a type or namespace within the type
2828   /// system. For example, given:
2829   ///
2830   /// \code
2831   /// namespace N {
2832   ///   struct S {
2833   ///     template<typename T> struct X { typename T* type; };
2834   ///   };
2835   /// }
2836   ///
2837   /// template<typename T> struct Y {
2838   ///   typename N::S::X<T>::type member;
2839   /// };
2840   /// \endcode
2841   ///
2842   /// Here, the nested-name-specifier for N::S::X<T>:: will be
2843   /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2844   /// by declarations in the type system and the canonical type for
2845   /// the template type parameter 'T' is template-param-0-0.
2846   NestedNameSpecifier *
2847   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2848 
2849   /// Retrieves the default calling convention for the current target.
2850   CallingConv getDefaultCallingConvention(bool IsVariadic,
2851                                           bool IsCXXMethod,
2852                                           bool IsBuiltin = false) const;
2853 
2854   /// Retrieves the "canonical" template name that refers to a
2855   /// given template.
2856   ///
2857   /// The canonical template name is the simplest expression that can
2858   /// be used to refer to a given template. For most templates, this
2859   /// expression is just the template declaration itself. For example,
2860   /// the template std::vector can be referred to via a variety of
2861   /// names---std::vector, \::std::vector, vector (if vector is in
2862   /// scope), etc.---but all of these names map down to the same
2863   /// TemplateDecl, which is used to form the canonical template name.
2864   ///
2865   /// Dependent template names are more interesting. Here, the
2866   /// template name could be something like T::template apply or
2867   /// std::allocator<T>::template rebind, where the nested name
2868   /// specifier itself is dependent. In this case, the canonical
2869   /// template name uses the shortest form of the dependent
2870   /// nested-name-specifier, which itself contains all canonical
2871   /// types, values, and templates.
2872   TemplateName getCanonicalTemplateName(TemplateName Name,
2873                                         bool IgnoreDeduced = false) const;
2874 
2875   /// Determine whether the given template names refer to the same
2876   /// template.
2877   bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y,
2878                            bool IgnoreDeduced = false) const;
2879 
2880   /// Determine whether the two declarations refer to the same entity.
2881   bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const;
2882 
2883   /// Determine whether two template parameter lists are similar enough
2884   /// that they may be used in declarations of the same template.
2885   bool isSameTemplateParameterList(const TemplateParameterList *X,
2886                                    const TemplateParameterList *Y) const;
2887 
2888   /// Determine whether two template parameters are similar enough
2889   /// that they may be used in declarations of the same template.
2890   bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const;
2891 
2892   /// Determine whether two 'requires' expressions are similar enough that they
2893   /// may be used in re-declarations.
2894   ///
2895   /// Use of 'requires' isn't mandatory, works with constraints expressed in
2896   /// other ways too.
2897   bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const;
2898 
2899   /// Determine whether two type contraint are similar enough that they could
2900   /// used in declarations of the same template.
2901   bool isSameTypeConstraint(const TypeConstraint *XTC,
2902                             const TypeConstraint *YTC) const;
2903 
2904   /// Determine whether two default template arguments are similar enough
2905   /// that they may be used in declarations of the same template.
2906   bool isSameDefaultTemplateArgument(const NamedDecl *X,
2907                                      const NamedDecl *Y) const;
2908 
2909   /// Retrieve the "canonical" template argument.
2910   ///
2911   /// The canonical template argument is the simplest template argument
2912   /// (which may be a type, value, expression, or declaration) that
2913   /// expresses the value of the argument.
2914   TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2915     const;
2916 
2917   /// Type Query functions.  If the type is an instance of the specified class,
2918   /// return the Type pointer for the underlying maximally pretty type.  This
2919   /// is a member of ASTContext because this may need to do some amount of
2920   /// canonicalization, e.g. to move type qualifiers into the element type.
2921   const ArrayType *getAsArrayType(QualType T) const;
2922   const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2923     return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2924   }
2925   const VariableArrayType *getAsVariableArrayType(QualType T) const {
2926     return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2927   }
2928   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2929     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2930   }
2931   const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2932     const {
2933     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2934   }
2935 
2936   /// Return the innermost element type of an array type.
2937   ///
2938   /// For example, will return "int" for int[m][n]
2939   QualType getBaseElementType(const ArrayType *VAT) const;
2940 
2941   /// Return the innermost element type of a type (which needn't
2942   /// actually be an array type).
2943   QualType getBaseElementType(QualType QT) const;
2944 
2945   /// Return number of constant array elements.
2946   uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2947 
2948   /// Return number of elements initialized in an ArrayInitLoopExpr.
2949   uint64_t
2950   getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const;
2951 
2952   /// Perform adjustment on the parameter type of a function.
2953   ///
2954   /// This routine adjusts the given parameter type @p T to the actual
2955   /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2956   /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2957   QualType getAdjustedParameterType(QualType T) const;
2958 
2959   /// Retrieve the parameter type as adjusted for use in the signature
2960   /// of a function, decaying array and function types and removing top-level
2961   /// cv-qualifiers.
2962   QualType getSignatureParameterType(QualType T) const;
2963 
2964   QualType getExceptionObjectType(QualType T) const;
2965 
2966   /// Return the properly qualified result of decaying the specified
2967   /// array type to a pointer.
2968   ///
2969   /// This operation is non-trivial when handling typedefs etc.  The canonical
2970   /// type of \p T must be an array type, this returns a pointer to a properly
2971   /// qualified element of the array.
2972   ///
2973   /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2974   QualType getArrayDecayedType(QualType T) const;
2975 
2976   /// Return the type that \p PromotableType will promote to: C99
2977   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2978   QualType getPromotedIntegerType(QualType PromotableType) const;
2979 
2980   /// Recurses in pointer/array types until it finds an Objective-C
2981   /// retainable type and returns its ownership.
2982   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2983 
2984   /// Whether this is a promotable bitfield reference according
2985   /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2986   ///
2987   /// \returns the type this bit-field will promote to, or NULL if no
2988   /// promotion occurs.
2989   QualType isPromotableBitField(Expr *E) const;
2990 
2991   /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2992   ///
2993   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
2994   /// \p LHS < \p RHS, return -1.
2995   int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2996 
2997   /// Compare the rank of the two specified floating point types,
2998   /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2999   ///
3000   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
3001   /// \p LHS < \p RHS, return -1.
3002   int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
3003 
3004   /// Compare the rank of two floating point types as above, but compare equal
3005   /// if both types have the same floating-point semantics on the target (i.e.
3006   /// long double and double on AArch64 will return 0).
3007   int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
3008 
3009   unsigned getTargetAddressSpace(LangAS AS) const;
3010 
3011   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
3012 
3013   /// Get target-dependent integer value for null pointer which is used for
3014   /// constant folding.
3015   uint64_t getTargetNullPointerValue(QualType QT) const;
3016 
3017   bool addressSpaceMapManglingFor(LangAS AS) const {
3018     return AddrSpaceMapMangling || isTargetAddressSpace(AS);
3019   }
3020 
3021   bool hasAnyFunctionEffects() const { return AnyFunctionEffects; }
3022 
3023   // Merges two exception specifications, such that the resulting
3024   // exception spec is the union of both. For example, if either
3025   // of them can throw something, the result can throw it as well.
3026   FunctionProtoType::ExceptionSpecInfo
3027   mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
3028                       FunctionProtoType::ExceptionSpecInfo ESI2,
3029                       SmallVectorImpl<QualType> &ExceptionTypeStorage,
3030                       bool AcceptDependent);
3031 
3032   // For two "same" types, return a type which has
3033   // the common sugar between them. If Unqualified is true,
3034   // both types need only be the same unqualified type.
3035   // The result will drop the qualifiers which do not occur
3036   // in both types.
3037   QualType getCommonSugaredType(QualType X, QualType Y,
3038                                 bool Unqualified = false);
3039 
3040 private:
3041   // Helper for integer ordering
3042   unsigned getIntegerRank(const Type *T) const;
3043 
3044 public:
3045   //===--------------------------------------------------------------------===//
3046   //                    Type Compatibility Predicates
3047   //===--------------------------------------------------------------------===//
3048 
3049   /// Compatibility predicates used to check assignment expressions.
3050   bool typesAreCompatible(QualType T1, QualType T2,
3051                           bool CompareUnqualified = false); // C99 6.2.7p1
3052 
3053   bool propertyTypesAreCompatible(QualType, QualType);
3054   bool typesAreBlockPointerCompatible(QualType, QualType);
3055 
3056   bool isObjCIdType(QualType T) const {
3057     if (const auto *ET = dyn_cast<ElaboratedType>(T))
3058       T = ET->getNamedType();
3059     return T == getObjCIdType();
3060   }
3061 
3062   bool isObjCClassType(QualType T) const {
3063     if (const auto *ET = dyn_cast<ElaboratedType>(T))
3064       T = ET->getNamedType();
3065     return T == getObjCClassType();
3066   }
3067 
3068   bool isObjCSelType(QualType T) const {
3069     if (const auto *ET = dyn_cast<ElaboratedType>(T))
3070       T = ET->getNamedType();
3071     return T == getObjCSelType();
3072   }
3073 
3074   bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
3075                                          const ObjCObjectPointerType *RHS,
3076                                          bool ForCompare);
3077 
3078   bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
3079                                             const ObjCObjectPointerType *RHS);
3080 
3081   // Check the safety of assignment from LHS to RHS
3082   bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3083                                const ObjCObjectPointerType *RHSOPT);
3084   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
3085                                const ObjCObjectType *RHS);
3086   bool canAssignObjCInterfacesInBlockPointer(
3087                                           const ObjCObjectPointerType *LHSOPT,
3088                                           const ObjCObjectPointerType *RHSOPT,
3089                                           bool BlockReturnType);
3090   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
3091   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
3092                                    const ObjCObjectPointerType *RHSOPT);
3093   bool canBindObjCObjectType(QualType To, QualType From);
3094 
3095   // Functions for calculating composite types
3096   QualType mergeTypes(QualType, QualType, bool OfBlockPointer = false,
3097                       bool Unqualified = false, bool BlockReturnType = false,
3098                       bool IsConditionalOperator = false);
3099   QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer = false,
3100                               bool Unqualified = false, bool AllowCXX = false,
3101                               bool IsConditionalOperator = false);
3102   QualType mergeFunctionParameterTypes(QualType, QualType,
3103                                        bool OfBlockPointer = false,
3104                                        bool Unqualified = false);
3105   QualType mergeTransparentUnionType(QualType, QualType,
3106                                      bool OfBlockPointer=false,
3107                                      bool Unqualified = false);
3108 
3109   QualType mergeObjCGCQualifiers(QualType, QualType);
3110 
3111   /// This function merges the ExtParameterInfo lists of two functions. It
3112   /// returns true if the lists are compatible. The merged list is returned in
3113   /// NewParamInfos.
3114   ///
3115   /// \param FirstFnType The type of the first function.
3116   ///
3117   /// \param SecondFnType The type of the second function.
3118   ///
3119   /// \param CanUseFirst This flag is set to true if the first function's
3120   /// ExtParameterInfo list can be used as the composite list of
3121   /// ExtParameterInfo.
3122   ///
3123   /// \param CanUseSecond This flag is set to true if the second function's
3124   /// ExtParameterInfo list can be used as the composite list of
3125   /// ExtParameterInfo.
3126   ///
3127   /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
3128   /// empty if none of the flags are set.
3129   ///
3130   bool mergeExtParameterInfo(
3131       const FunctionProtoType *FirstFnType,
3132       const FunctionProtoType *SecondFnType,
3133       bool &CanUseFirst, bool &CanUseSecond,
3134       SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
3135 
3136   void ResetObjCLayout(const ObjCContainerDecl *CD);
3137 
3138   //===--------------------------------------------------------------------===//
3139   //                    Integer Predicates
3140   //===--------------------------------------------------------------------===//
3141 
3142   // The width of an integer, as defined in C99 6.2.6.2. This is the number
3143   // of bits in an integer type excluding any padding bits.
3144   unsigned getIntWidth(QualType T) const;
3145 
3146   // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
3147   // unsigned integer type.  This method takes a signed type, and returns the
3148   // corresponding unsigned integer type.
3149   // With the introduction of fixed point types in ISO N1169, this method also
3150   // accepts fixed point types and returns the corresponding unsigned type for
3151   // a given fixed point type.
3152   QualType getCorrespondingUnsignedType(QualType T) const;
3153 
3154   // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
3155   // unsigned integer type.  This method takes an unsigned type, and returns the
3156   // corresponding signed integer type.
3157   // With the introduction of fixed point types in ISO N1169, this method also
3158   // accepts fixed point types and returns the corresponding signed type for
3159   // a given fixed point type.
3160   QualType getCorrespondingSignedType(QualType T) const;
3161 
3162   // Per ISO N1169, this method accepts fixed point types and returns the
3163   // corresponding saturated type for a given fixed point type.
3164   QualType getCorrespondingSaturatedType(QualType Ty) const;
3165 
3166   // Per ISO N1169, this method accepts fixed point types and returns the
3167   // corresponding non-saturated type for a given fixed point type.
3168   QualType getCorrespondingUnsaturatedType(QualType Ty) const;
3169 
3170   // This method accepts fixed point types and returns the corresponding signed
3171   // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
3172   // fixed point types because there are unsigned integer types like bool and
3173   // char8_t that don't have signed equivalents.
3174   QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
3175 
3176   //===--------------------------------------------------------------------===//
3177   //                    Integer Values
3178   //===--------------------------------------------------------------------===//
3179 
3180   /// Make an APSInt of the appropriate width and signedness for the
3181   /// given \p Value and integer \p Type.
3182   llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
3183     // If Type is a signed integer type larger than 64 bits, we need to be sure
3184     // to sign extend Res appropriately.
3185     llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
3186     Res = Value;
3187     unsigned Width = getIntWidth(Type);
3188     if (Width != Res.getBitWidth())
3189       return Res.extOrTrunc(Width);
3190     return Res;
3191   }
3192 
3193   bool isSentinelNullExpr(const Expr *E);
3194 
3195   /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
3196   /// none exists.
3197   ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
3198 
3199   /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
3200   /// none exists.
3201   ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
3202 
3203   /// Return true if there is at least one \@implementation in the TU.
3204   bool AnyObjCImplementation() {
3205     return !ObjCImpls.empty();
3206   }
3207 
3208   /// Set the implementation of ObjCInterfaceDecl.
3209   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3210                              ObjCImplementationDecl *ImplD);
3211 
3212   /// Set the implementation of ObjCCategoryDecl.
3213   void setObjCImplementation(ObjCCategoryDecl *CatD,
3214                              ObjCCategoryImplDecl *ImplD);
3215 
3216   /// Get the duplicate declaration of a ObjCMethod in the same
3217   /// interface, or null if none exists.
3218   const ObjCMethodDecl *
3219   getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
3220 
3221   void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3222                                   const ObjCMethodDecl *Redecl);
3223 
3224   /// Returns the Objective-C interface that \p ND belongs to if it is
3225   /// an Objective-C method/property/ivar etc. that is part of an interface,
3226   /// otherwise returns null.
3227   const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
3228 
3229   /// Set the copy initialization expression of a block var decl. \p CanThrow
3230   /// indicates whether the copy expression can throw or not.
3231   void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
3232 
3233   /// Get the copy initialization expression of the VarDecl \p VD, or
3234   /// nullptr if none exists.
3235   BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
3236 
3237   /// Allocate an uninitialized TypeSourceInfo.
3238   ///
3239   /// The caller should initialize the memory held by TypeSourceInfo using
3240   /// the TypeLoc wrappers.
3241   ///
3242   /// \param T the type that will be the basis for type source info. This type
3243   /// should refer to how the declarator was written in source code, not to
3244   /// what type semantic analysis resolved the declarator to.
3245   ///
3246   /// \param Size the size of the type info to create, or 0 if the size
3247   /// should be calculated based on the type.
3248   TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
3249 
3250   /// Allocate a TypeSourceInfo where all locations have been
3251   /// initialized to a given location, which defaults to the empty
3252   /// location.
3253   TypeSourceInfo *
3254   getTrivialTypeSourceInfo(QualType T,
3255                            SourceLocation Loc = SourceLocation()) const;
3256 
3257   /// Add a deallocation callback that will be invoked when the
3258   /// ASTContext is destroyed.
3259   ///
3260   /// \param Callback A callback function that will be invoked on destruction.
3261   ///
3262   /// \param Data Pointer data that will be provided to the callback function
3263   /// when it is called.
3264   void AddDeallocation(void (*Callback)(void *), void *Data) const;
3265 
3266   /// If T isn't trivially destructible, calls AddDeallocation to register it
3267   /// for destruction.
3268   template <typename T> void addDestruction(T *Ptr) const {
3269     if (!std::is_trivially_destructible<T>::value) {
3270       auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
3271       AddDeallocation(DestroyPtr, Ptr);
3272     }
3273   }
3274 
3275   GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
3276   GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const;
3277 
3278   /// Determines if the decl can be CodeGen'ed or deserialized from PCH
3279   /// lazily, only when used; this is only relevant for function or file scoped
3280   /// var definitions.
3281   ///
3282   /// \returns true if the function/var must be CodeGen'ed/deserialized even if
3283   /// it is not used.
3284   bool DeclMustBeEmitted(const Decl *D);
3285 
3286   /// Visits all versions of a multiversioned function with the passed
3287   /// predicate.
3288   void forEachMultiversionedFunctionVersion(
3289       const FunctionDecl *FD,
3290       llvm::function_ref<void(FunctionDecl *)> Pred) const;
3291 
3292   const CXXConstructorDecl *
3293   getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
3294 
3295   void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
3296                                             CXXConstructorDecl *CD);
3297 
3298   void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
3299 
3300   TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
3301 
3302   void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
3303 
3304   DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
3305 
3306   void setManglingNumber(const NamedDecl *ND, unsigned Number);
3307   unsigned getManglingNumber(const NamedDecl *ND,
3308                              bool ForAuxTarget = false) const;
3309 
3310   void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
3311   unsigned getStaticLocalNumber(const VarDecl *VD) const;
3312 
3313   /// Retrieve the context for computing mangling numbers in the given
3314   /// DeclContext.
3315   MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
3316   enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
3317   MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
3318                                                    const Decl *D);
3319 
3320   std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
3321 
3322   /// Used by ParmVarDecl to store on the side the
3323   /// index of the parameter when it exceeds the size of the normal bitfield.
3324   void setParameterIndex(const ParmVarDecl *D, unsigned index);
3325 
3326   /// Used by ParmVarDecl to retrieve on the side the
3327   /// index of the parameter when it exceeds the size of the normal bitfield.
3328   unsigned getParameterIndex(const ParmVarDecl *D) const;
3329 
3330   /// Return a string representing the human readable name for the specified
3331   /// function declaration or file name. Used by SourceLocExpr and
3332   /// PredefinedExpr to cache evaluated results.
3333   StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
3334 
3335   /// Return the next version number to be used for a string literal evaluated
3336   /// as part of constant evaluation.
3337   unsigned getNextStringLiteralVersion() { return NextStringLiteralVersion++; }
3338 
3339   /// Return a declaration for the global GUID object representing the given
3340   /// GUID value.
3341   MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
3342 
3343   /// Return a declaration for a uniquified anonymous global constant
3344   /// corresponding to a given APValue.
3345   UnnamedGlobalConstantDecl *
3346   getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const;
3347 
3348   /// Return the template parameter object of the given type with the given
3349   /// value.
3350   TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
3351                                                       const APValue &V) const;
3352 
3353   /// Parses the target attributes passed in, and returns only the ones that are
3354   /// valid feature names.
3355   ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
3356 
3357   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3358                              const FunctionDecl *) const;
3359   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3360                              GlobalDecl GD) const;
3361 
3362   /// Generates and stores SYCL kernel metadata for the provided
3363   /// SYCL kernel entry point function. The provided function must have
3364   /// an attached sycl_kernel_entry_point attribute that specifies a unique
3365   /// type for the name of a SYCL kernel. Callers are required to detect
3366   /// conflicting SYCL kernel names and issue a diagnostic prior to calling
3367   /// this function.
3368   void registerSYCLEntryPointFunction(FunctionDecl *FD);
3369 
3370   /// Given a type used as a SYCL kernel name, returns a reference to the
3371   /// metadata generated from the corresponding SYCL kernel entry point.
3372   /// Aborts if the provided type is not a registered SYCL kernel name.
3373   const SYCLKernelInfo &getSYCLKernelInfo(QualType T) const;
3374 
3375   /// Returns a pointer to the metadata generated from the corresponding
3376   /// SYCLkernel entry point if the provided type corresponds to a registered
3377   /// SYCL kernel name. Returns a null pointer otherwise.
3378   const SYCLKernelInfo *findSYCLKernelInfo(QualType T) const;
3379 
3380   //===--------------------------------------------------------------------===//
3381   //                    Statistics
3382   //===--------------------------------------------------------------------===//
3383 
3384   /// The number of implicitly-declared default constructors.
3385   unsigned NumImplicitDefaultConstructors = 0;
3386 
3387   /// The number of implicitly-declared default constructors for
3388   /// which declarations were built.
3389   unsigned NumImplicitDefaultConstructorsDeclared = 0;
3390 
3391   /// The number of implicitly-declared copy constructors.
3392   unsigned NumImplicitCopyConstructors = 0;
3393 
3394   /// The number of implicitly-declared copy constructors for
3395   /// which declarations were built.
3396   unsigned NumImplicitCopyConstructorsDeclared = 0;
3397 
3398   /// The number of implicitly-declared move constructors.
3399   unsigned NumImplicitMoveConstructors = 0;
3400 
3401   /// The number of implicitly-declared move constructors for
3402   /// which declarations were built.
3403   unsigned NumImplicitMoveConstructorsDeclared = 0;
3404 
3405   /// The number of implicitly-declared copy assignment operators.
3406   unsigned NumImplicitCopyAssignmentOperators = 0;
3407 
3408   /// The number of implicitly-declared copy assignment operators for
3409   /// which declarations were built.
3410   unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
3411 
3412   /// The number of implicitly-declared move assignment operators.
3413   unsigned NumImplicitMoveAssignmentOperators = 0;
3414 
3415   /// The number of implicitly-declared move assignment operators for
3416   /// which declarations were built.
3417   unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
3418 
3419   /// The number of implicitly-declared destructors.
3420   unsigned NumImplicitDestructors = 0;
3421 
3422   /// The number of implicitly-declared destructors for which
3423   /// declarations were built.
3424   unsigned NumImplicitDestructorsDeclared = 0;
3425 
3426 public:
3427   /// Initialize built-in types.
3428   ///
3429   /// This routine may only be invoked once for a given ASTContext object.
3430   /// It is normally invoked after ASTContext construction.
3431   ///
3432   /// \param Target The target
3433   void InitBuiltinTypes(const TargetInfo &Target,
3434                         const TargetInfo *AuxTarget = nullptr);
3435 
3436 private:
3437   void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
3438 
3439   class ObjCEncOptions {
3440     unsigned Bits;
3441 
3442     ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
3443 
3444   public:
3445     ObjCEncOptions() : Bits(0) {}
3446 
3447 #define OPT_LIST(V)                                                            \
3448   V(ExpandPointedToStructures, 0)                                              \
3449   V(ExpandStructures, 1)                                                       \
3450   V(IsOutermostType, 2)                                                        \
3451   V(EncodingProperty, 3)                                                       \
3452   V(IsStructField, 4)                                                          \
3453   V(EncodeBlockParameters, 5)                                                  \
3454   V(EncodeClassNames, 6)                                                       \
3455 
3456 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
3457 OPT_LIST(V)
3458 #undef V
3459 
3460 #define V(N,I) bool N() const { return Bits & 1 << I; }
3461 OPT_LIST(V)
3462 #undef V
3463 
3464 #undef OPT_LIST
3465 
3466     [[nodiscard]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
3467       return Bits & Mask.Bits;
3468     }
3469 
3470     [[nodiscard]] ObjCEncOptions forComponentType() const {
3471       ObjCEncOptions Mask = ObjCEncOptions()
3472                                 .setIsOutermostType()
3473                                 .setIsStructField();
3474       return Bits & ~Mask.Bits;
3475     }
3476   };
3477 
3478   // Return the Objective-C type encoding for a given type.
3479   void getObjCEncodingForTypeImpl(QualType t, std::string &S,
3480                                   ObjCEncOptions Options,
3481                                   const FieldDecl *Field,
3482                                   QualType *NotEncodedT = nullptr) const;
3483 
3484   // Adds the encoding of the structure's members.
3485   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
3486                                        const FieldDecl *Field,
3487                                        bool includeVBases = true,
3488                                        QualType *NotEncodedT=nullptr) const;
3489 
3490 public:
3491   // Adds the encoding of a method parameter or return type.
3492   void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
3493                                          QualType T, std::string& S,
3494                                          bool Extended) const;
3495 
3496   /// Returns true if this is an inline-initialized static data member
3497   /// which is treated as a definition for MSVC compatibility.
3498   bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
3499 
3500   enum class InlineVariableDefinitionKind {
3501     /// Not an inline variable.
3502     None,
3503 
3504     /// Weak definition of inline variable.
3505     Weak,
3506 
3507     /// Weak for now, might become strong later in this TU.
3508     WeakUnknown,
3509 
3510     /// Strong definition.
3511     Strong
3512   };
3513 
3514   /// Determine whether a definition of this inline variable should
3515   /// be treated as a weak or strong definition. For compatibility with
3516   /// C++14 and before, for a constexpr static data member, if there is an
3517   /// out-of-line declaration of the member, we may promote it from weak to
3518   /// strong.
3519   InlineVariableDefinitionKind
3520   getInlineVariableDefinitionKind(const VarDecl *VD) const;
3521 
3522 private:
3523   friend class DeclarationNameTable;
3524   friend class DeclContext;
3525 
3526   const ASTRecordLayout &
3527   getObjCLayout(const ObjCInterfaceDecl *D,
3528                 const ObjCImplementationDecl *Impl) const;
3529 
3530   /// A set of deallocations that should be performed when the
3531   /// ASTContext is destroyed.
3532   // FIXME: We really should have a better mechanism in the ASTContext to
3533   // manage running destructors for types which do variable sized allocation
3534   // within the AST. In some places we thread the AST bump pointer allocator
3535   // into the datastructures which avoids this mess during deallocation but is
3536   // wasteful of memory, and here we require a lot of error prone book keeping
3537   // in order to track and run destructors while we're tearing things down.
3538   using DeallocationFunctionsAndArguments =
3539       llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
3540   mutable DeallocationFunctionsAndArguments Deallocations;
3541 
3542   // FIXME: This currently contains the set of StoredDeclMaps used
3543   // by DeclContext objects.  This probably should not be in ASTContext,
3544   // but we include it here so that ASTContext can quickly deallocate them.
3545   llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3546 
3547   std::vector<Decl *> TraversalScope;
3548 
3549   std::unique_ptr<VTableContextBase> VTContext;
3550 
3551   void ReleaseDeclContextMaps();
3552 
3553 public:
3554   enum PragmaSectionFlag : unsigned {
3555     PSF_None = 0,
3556     PSF_Read = 0x1,
3557     PSF_Write = 0x2,
3558     PSF_Execute = 0x4,
3559     PSF_Implicit = 0x8,
3560     PSF_ZeroInit = 0x10,
3561     PSF_Invalid = 0x80000000U,
3562   };
3563 
3564   struct SectionInfo {
3565     NamedDecl *Decl;
3566     SourceLocation PragmaSectionLocation;
3567     int SectionFlags;
3568 
3569     SectionInfo() = default;
3570     SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
3571                 int SectionFlags)
3572         : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3573           SectionFlags(SectionFlags) {}
3574   };
3575 
3576   llvm::StringMap<SectionInfo> SectionInfos;
3577 
3578   /// Return a new OMPTraitInfo object owned by this context.
3579   OMPTraitInfo &getNewOMPTraitInfo();
3580 
3581   /// Whether a C++ static variable or CUDA/HIP kernel may be externalized.
3582   bool mayExternalize(const Decl *D) const;
3583 
3584   /// Whether a C++ static variable or CUDA/HIP kernel should be externalized.
3585   bool shouldExternalize(const Decl *D) const;
3586 
3587   /// Resolve the root record to be used to derive the vtable pointer
3588   /// authentication policy for the specified record.
3589   const CXXRecordDecl *
3590   baseForVTableAuthentication(const CXXRecordDecl *ThisClass);
3591   bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
3592                                StringRef MangledName);
3593 
3594   StringRef getCUIDHash() const;
3595 
3596 private:
3597   /// All OMPTraitInfo objects live in this collection, one per
3598   /// `pragma omp [begin] declare variant` directive.
3599   SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3600 
3601   llvm::DenseMap<GlobalDecl, llvm::StringSet<>> ThunksToBeAbbreviated;
3602 };
3603 
3604 /// Insertion operator for diagnostics.
3605 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
3606                                       const ASTContext::SectionInfo &Section);
3607 
3608 /// Utility function for constructing a nullary selector.
3609 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3610   const IdentifierInfo *II = &Ctx.Idents.get(name);
3611   return Ctx.Selectors.getSelector(0, &II);
3612 }
3613 
3614 /// Utility function for constructing an unary selector.
3615 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3616   const IdentifierInfo *II = &Ctx.Idents.get(name);
3617   return Ctx.Selectors.getSelector(1, &II);
3618 }
3619 
3620 } // namespace clang
3621 
3622 // operator new and delete aren't allowed inside namespaces.
3623 
3624 /// Placement new for using the ASTContext's allocator.
3625 ///
3626 /// This placement form of operator new uses the ASTContext's allocator for
3627 /// obtaining memory.
3628 ///
3629 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3630 /// Any changes here need to also be made there.
3631 ///
3632 /// We intentionally avoid using a nothrow specification here so that the calls
3633 /// to this operator will not perform a null check on the result -- the
3634 /// underlying allocator never returns null pointers.
3635 ///
3636 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3637 /// @code
3638 /// // Default alignment (8)
3639 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3640 /// // Specific alignment
3641 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3642 /// @endcode
3643 /// Memory allocated through this placement new operator does not need to be
3644 /// explicitly freed, as ASTContext will free all of this memory when it gets
3645 /// destroyed. Please note that you cannot use delete on the pointer.
3646 ///
3647 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3648 /// @param C The ASTContext that provides the allocator.
3649 /// @param Alignment The alignment of the allocated memory (if the underlying
3650 ///                  allocator supports it).
3651 /// @return The allocated memory. Could be nullptr.
3652 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3653                           size_t Alignment /* = 8 */) {
3654   return C.Allocate(Bytes, Alignment);
3655 }
3656 
3657 /// Placement delete companion to the new above.
3658 ///
3659 /// This operator is just a companion to the new above. There is no way of
3660 /// invoking it directly; see the new operator for more details. This operator
3661 /// is called implicitly by the compiler if a placement new expression using
3662 /// the ASTContext throws in the object constructor.
3663 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3664   C.Deallocate(Ptr);
3665 }
3666 
3667 /// This placement form of operator new[] uses the ASTContext's allocator for
3668 /// obtaining memory.
3669 ///
3670 /// We intentionally avoid using a nothrow specification here so that the calls
3671 /// to this operator will not perform a null check on the result -- the
3672 /// underlying allocator never returns null pointers.
3673 ///
3674 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3675 /// @code
3676 /// // Default alignment (8)
3677 /// char *data = new (Context) char[10];
3678 /// // Specific alignment
3679 /// char *data = new (Context, 4) char[10];
3680 /// @endcode
3681 /// Memory allocated through this placement new[] operator does not need to be
3682 /// explicitly freed, as ASTContext will free all of this memory when it gets
3683 /// destroyed. Please note that you cannot use delete on the pointer.
3684 ///
3685 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3686 /// @param C The ASTContext that provides the allocator.
3687 /// @param Alignment The alignment of the allocated memory (if the underlying
3688 ///                  allocator supports it).
3689 /// @return The allocated memory. Could be nullptr.
3690 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3691                             size_t Alignment /* = 8 */) {
3692   return C.Allocate(Bytes, Alignment);
3693 }
3694 
3695 /// Placement delete[] companion to the new[] above.
3696 ///
3697 /// This operator is just a companion to the new[] above. There is no way of
3698 /// invoking it directly; see the new[] operator for more details. This operator
3699 /// is called implicitly by the compiler if a placement new[] expression using
3700 /// the ASTContext throws in the object constructor.
3701 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3702   C.Deallocate(Ptr);
3703 }
3704 
3705 /// Create the representation of a LazyGenerationalUpdatePtr.
3706 template <typename Owner, typename T,
3707           void (clang::ExternalASTSource::*Update)(Owner)>
3708 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3709     clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3710         const clang::ASTContext &Ctx, T Value) {
3711   // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3712   // include ASTContext.h. We explicitly instantiate it for all relevant types
3713   // in ASTContext.cpp.
3714   if (auto *Source = Ctx.getExternalSource())
3715     return new (Ctx) LazyData(Source, Value);
3716   return Value;
3717 }
3718 
3719 #endif // LLVM_CLANG_AST_ASTCONTEXT_H