1 //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Defines the clang::ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15 #define LLVM_CLANG_AST_ASTCONTEXT_H
16 
17 #include "clang/AST/ASTContextAllocate.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/RawCommentList.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/AttrKinds.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/Linkage.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/SanitizerBlacklist.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/Basic/XRayLists.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/IntrusiveRefCntPtr.h"
48 #include "llvm/ADT/MapVector.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/PointerIntPair.h"
52 #include "llvm/ADT/PointerUnion.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringMap.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Support/AlignOf.h"
60 #include "llvm/Support/Allocator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/TypeSize.h"
64 #include <cassert>
65 #include <cstddef>
66 #include <cstdint>
67 #include <iterator>
68 #include <memory>
69 #include <string>
70 #include <type_traits>
71 #include <utility>
72 #include <vector>
73 
74 namespace llvm {
75 
76 struct fltSemantics;
77 template <typename T, unsigned N> class SmallPtrSet;
78 
79 } // namespace llvm
80 
81 namespace clang {
82 
83 class APFixedPoint;
84 class APValue;
85 class ASTMutationListener;
86 class ASTRecordLayout;
87 class AtomicExpr;
88 class BlockExpr;
89 class BuiltinTemplateDecl;
90 class CharUnits;
91 class ConceptDecl;
92 class CXXABI;
93 class CXXConstructorDecl;
94 class CXXMethodDecl;
95 class CXXRecordDecl;
96 class DiagnosticsEngine;
97 class ParentMapContext;
98 class DynTypedNode;
99 class DynTypedNodeList;
100 class Expr;
101 class FixedPointSemantics;
102 class GlobalDecl;
103 class MangleContext;
104 class MangleNumberingContext;
105 class MaterializeTemporaryExpr;
106 class MemberSpecializationInfo;
107 class Module;
108 struct MSGuidDeclParts;
109 class ObjCCategoryDecl;
110 class ObjCCategoryImplDecl;
111 class ObjCContainerDecl;
112 class ObjCImplDecl;
113 class ObjCImplementationDecl;
114 class ObjCInterfaceDecl;
115 class ObjCIvarDecl;
116 class ObjCMethodDecl;
117 class ObjCPropertyDecl;
118 class ObjCPropertyImplDecl;
119 class ObjCProtocolDecl;
120 class ObjCTypeParamDecl;
121 class OMPTraitInfo;
122 struct ParsedTargetAttr;
123 class Preprocessor;
124 class Stmt;
125 class StoredDeclsMap;
126 class TargetAttr;
127 class TargetInfo;
128 class TemplateDecl;
129 class TemplateParameterList;
130 class TemplateTemplateParmDecl;
131 class TemplateTypeParmDecl;
132 class UnresolvedSetIterator;
133 class UsingShadowDecl;
134 class VarTemplateDecl;
135 class VTableContextBase;
136 struct BlockVarCopyInit;
137 
138 namespace Builtin {
139 
140 class Context;
141 
142 } // namespace Builtin
143 
144 enum BuiltinTemplateKind : int;
145 enum OpenCLTypeKind : uint8_t;
146 
147 namespace comments {
148 
149 class FullComment;
150 
151 } // namespace comments
152 
153 namespace interp {
154 
155 class Context;
156 
157 } // namespace interp
158 
159 namespace serialization {
160 template <class> class AbstractTypeReader;
161 } // namespace serialization
162 
163 struct TypeInfo {
164   uint64_t Width = 0;
165   unsigned Align = 0;
166   bool AlignIsRequired : 1;
167 
168   TypeInfo() : AlignIsRequired(false) {}
169   TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
170       : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
171 };
172 
173 /// Holds long-lived AST nodes (such as types and decls) that can be
174 /// referred to throughout the semantic analysis of a file.
175 class ASTContext : public RefCountedBase<ASTContext> {
176   friend class NestedNameSpecifier;
177 
178   mutable SmallVector<Type *, 0> Types;
179   mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
180   mutable llvm::FoldingSet<ComplexType> ComplexTypes;
181   mutable llvm::FoldingSet<PointerType> PointerTypes;
182   mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
183   mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
184   mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
185   mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
186   mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
187   mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
188       ConstantArrayTypes;
189   mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
190   mutable std::vector<VariableArrayType*> VariableArrayTypes;
191   mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
192   mutable llvm::FoldingSet<DependentSizedExtVectorType>
193     DependentSizedExtVectorTypes;
194   mutable llvm::FoldingSet<DependentAddressSpaceType>
195       DependentAddressSpaceTypes;
196   mutable llvm::FoldingSet<VectorType> VectorTypes;
197   mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
198   mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
199   mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
200   mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
201   mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
202     FunctionProtoTypes;
203   mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
204   mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
205   mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
206   mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
207   mutable llvm::FoldingSet<SubstTemplateTypeParmType>
208     SubstTemplateTypeParmTypes;
209   mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
210     SubstTemplateTypeParmPackTypes;
211   mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
212     TemplateSpecializationTypes;
213   mutable llvm::FoldingSet<ParenType> ParenTypes;
214   mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
215   mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
216   mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
217                                      ASTContext&>
218     DependentTemplateSpecializationTypes;
219   llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
220   mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
221   mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
222   mutable llvm::FoldingSet<DependentUnaryTransformType>
223     DependentUnaryTransformTypes;
224   mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
225   mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
226     DeducedTemplateSpecializationTypes;
227   mutable llvm::FoldingSet<AtomicType> AtomicTypes;
228   llvm::FoldingSet<AttributedType> AttributedTypes;
229   mutable llvm::FoldingSet<PipeType> PipeTypes;
230   mutable llvm::FoldingSet<ExtIntType> ExtIntTypes;
231   mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes;
232 
233   mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
234   mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
235   mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
236     SubstTemplateTemplateParms;
237   mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
238                                      ASTContext&>
239     SubstTemplateTemplateParmPacks;
240 
241   /// The set of nested name specifiers.
242   ///
243   /// This set is managed by the NestedNameSpecifier class.
244   mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
245   mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
246 
247   /// A cache mapping from RecordDecls to ASTRecordLayouts.
248   ///
249   /// This is lazily created.  This is intentionally not serialized.
250   mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
251     ASTRecordLayouts;
252   mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
253     ObjCLayouts;
254 
255   /// A cache from types to size and alignment information.
256   using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
257   mutable TypeInfoMap MemoizedTypeInfo;
258 
259   /// A cache from types to unadjusted alignment information. Only ARM and
260   /// AArch64 targets need this information, keeping it separate prevents
261   /// imposing overhead on TypeInfo size.
262   using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
263   mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
264 
265   /// A cache mapping from CXXRecordDecls to key functions.
266   llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
267 
268   /// Mapping from ObjCContainers to their ObjCImplementations.
269   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
270 
271   /// Mapping from ObjCMethod to its duplicate declaration in the same
272   /// interface.
273   llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
274 
275   /// Mapping from __block VarDecls to BlockVarCopyInit.
276   llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
277 
278   /// Mapping from GUIDs to the corresponding MSGuidDecl.
279   mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
280 
281   /// Used to cleanups APValues stored in the AST.
282   mutable llvm::SmallVector<APValue *, 0> APValueCleanups;
283 
284   /// A cache mapping a string value to a StringLiteral object with the same
285   /// value.
286   ///
287   /// This is lazily created.  This is intentionally not serialized.
288   mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
289 
290   /// Representation of a "canonical" template template parameter that
291   /// is used in canonical template names.
292   class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
293     TemplateTemplateParmDecl *Parm;
294 
295   public:
296     CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
297         : Parm(Parm) {}
298 
299     TemplateTemplateParmDecl *getParam() const { return Parm; }
300 
301     void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
302       Profile(ID, C, Parm);
303     }
304 
305     static void Profile(llvm::FoldingSetNodeID &ID,
306                         const ASTContext &C,
307                         TemplateTemplateParmDecl *Parm);
308   };
309   mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
310                                      const ASTContext&>
311     CanonTemplateTemplateParms;
312 
313   TemplateTemplateParmDecl *
314     getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
315 
316   /// The typedef for the __int128_t type.
317   mutable TypedefDecl *Int128Decl = nullptr;
318 
319   /// The typedef for the __uint128_t type.
320   mutable TypedefDecl *UInt128Decl = nullptr;
321 
322   /// The typedef for the target specific predefined
323   /// __builtin_va_list type.
324   mutable TypedefDecl *BuiltinVaListDecl = nullptr;
325 
326   /// The typedef for the predefined \c __builtin_ms_va_list type.
327   mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
328 
329   /// The typedef for the predefined \c id type.
330   mutable TypedefDecl *ObjCIdDecl = nullptr;
331 
332   /// The typedef for the predefined \c SEL type.
333   mutable TypedefDecl *ObjCSelDecl = nullptr;
334 
335   /// The typedef for the predefined \c Class type.
336   mutable TypedefDecl *ObjCClassDecl = nullptr;
337 
338   /// The typedef for the predefined \c Protocol class in Objective-C.
339   mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
340 
341   /// The typedef for the predefined 'BOOL' type.
342   mutable TypedefDecl *BOOLDecl = nullptr;
343 
344   // Typedefs which may be provided defining the structure of Objective-C
345   // pseudo-builtins
346   QualType ObjCIdRedefinitionType;
347   QualType ObjCClassRedefinitionType;
348   QualType ObjCSelRedefinitionType;
349 
350   /// The identifier 'bool'.
351   mutable IdentifierInfo *BoolName = nullptr;
352 
353   /// The identifier 'NSObject'.
354   mutable IdentifierInfo *NSObjectName = nullptr;
355 
356   /// The identifier 'NSCopying'.
357   IdentifierInfo *NSCopyingName = nullptr;
358 
359   /// The identifier '__make_integer_seq'.
360   mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
361 
362   /// The identifier '__type_pack_element'.
363   mutable IdentifierInfo *TypePackElementName = nullptr;
364 
365   QualType ObjCConstantStringType;
366   mutable RecordDecl *CFConstantStringTagDecl = nullptr;
367   mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
368 
369   mutable QualType ObjCSuperType;
370 
371   QualType ObjCNSStringType;
372 
373   /// The typedef declaration for the Objective-C "instancetype" type.
374   TypedefDecl *ObjCInstanceTypeDecl = nullptr;
375 
376   /// The type for the C FILE type.
377   TypeDecl *FILEDecl = nullptr;
378 
379   /// The type for the C jmp_buf type.
380   TypeDecl *jmp_bufDecl = nullptr;
381 
382   /// The type for the C sigjmp_buf type.
383   TypeDecl *sigjmp_bufDecl = nullptr;
384 
385   /// The type for the C ucontext_t type.
386   TypeDecl *ucontext_tDecl = nullptr;
387 
388   /// Type for the Block descriptor for Blocks CodeGen.
389   ///
390   /// Since this is only used for generation of debug info, it is not
391   /// serialized.
392   mutable RecordDecl *BlockDescriptorType = nullptr;
393 
394   /// Type for the Block descriptor for Blocks CodeGen.
395   ///
396   /// Since this is only used for generation of debug info, it is not
397   /// serialized.
398   mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
399 
400   /// Declaration for the CUDA cudaConfigureCall function.
401   FunctionDecl *cudaConfigureCallDecl = nullptr;
402 
403   /// Keeps track of all declaration attributes.
404   ///
405   /// Since so few decls have attrs, we keep them in a hash map instead of
406   /// wasting space in the Decl class.
407   llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
408 
409   /// A mapping from non-redeclarable declarations in modules that were
410   /// merged with other declarations to the canonical declaration that they were
411   /// merged into.
412   llvm::DenseMap<Decl*, Decl*> MergedDecls;
413 
414   /// A mapping from a defining declaration to a list of modules (other
415   /// than the owning module of the declaration) that contain merged
416   /// definitions of that entity.
417   llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
418 
419   /// Initializers for a module, in order. Each Decl will be either
420   /// something that has a semantic effect on startup (such as a variable with
421   /// a non-constant initializer), or an ImportDecl (which recursively triggers
422   /// initialization of another module).
423   struct PerModuleInitializers {
424     llvm::SmallVector<Decl*, 4> Initializers;
425     llvm::SmallVector<uint32_t, 4> LazyInitializers;
426 
427     void resolve(ASTContext &Ctx);
428   };
429   llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
430 
431   ASTContext &this_() { return *this; }
432 
433 public:
434   /// A type synonym for the TemplateOrInstantiation mapping.
435   using TemplateOrSpecializationInfo =
436       llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
437 
438 private:
439   friend class ASTDeclReader;
440   friend class ASTReader;
441   friend class ASTWriter;
442   template <class> friend class serialization::AbstractTypeReader;
443   friend class CXXRecordDecl;
444 
445   /// A mapping to contain the template or declaration that
446   /// a variable declaration describes or was instantiated from,
447   /// respectively.
448   ///
449   /// For non-templates, this value will be NULL. For variable
450   /// declarations that describe a variable template, this will be a
451   /// pointer to a VarTemplateDecl. For static data members
452   /// of class template specializations, this will be the
453   /// MemberSpecializationInfo referring to the member variable that was
454   /// instantiated or specialized. Thus, the mapping will keep track of
455   /// the static data member templates from which static data members of
456   /// class template specializations were instantiated.
457   ///
458   /// Given the following example:
459   ///
460   /// \code
461   /// template<typename T>
462   /// struct X {
463   ///   static T value;
464   /// };
465   ///
466   /// template<typename T>
467   ///   T X<T>::value = T(17);
468   ///
469   /// int *x = &X<int>::value;
470   /// \endcode
471   ///
472   /// This mapping will contain an entry that maps from the VarDecl for
473   /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
474   /// class template X) and will be marked TSK_ImplicitInstantiation.
475   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
476   TemplateOrInstantiation;
477 
478   /// Keeps track of the declaration from which a using declaration was
479   /// created during instantiation.
480   ///
481   /// The source and target declarations are always a UsingDecl, an
482   /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
483   ///
484   /// For example:
485   /// \code
486   /// template<typename T>
487   /// struct A {
488   ///   void f();
489   /// };
490   ///
491   /// template<typename T>
492   /// struct B : A<T> {
493   ///   using A<T>::f;
494   /// };
495   ///
496   /// template struct B<int>;
497   /// \endcode
498   ///
499   /// This mapping will contain an entry that maps from the UsingDecl in
500   /// B<int> to the UnresolvedUsingDecl in B<T>.
501   llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
502 
503   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
504     InstantiatedFromUsingShadowDecl;
505 
506   llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
507 
508   /// Mapping that stores the methods overridden by a given C++
509   /// member function.
510   ///
511   /// Since most C++ member functions aren't virtual and therefore
512   /// don't override anything, we store the overridden functions in
513   /// this map on the side rather than within the CXXMethodDecl structure.
514   using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
515   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
516 
517   /// Mapping from each declaration context to its corresponding
518   /// mangling numbering context (used for constructs like lambdas which
519   /// need to be consistently numbered for the mangler).
520   llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
521       MangleNumberingContexts;
522   llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
523       ExtraMangleNumberingContexts;
524 
525   /// Side-table of mangling numbers for declarations which rarely
526   /// need them (like static local vars).
527   llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
528   llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
529 
530   /// Mapping that stores parameterIndex values for ParmVarDecls when
531   /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
532   using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
533   ParameterIndexTable ParamIndices;
534 
535   ImportDecl *FirstLocalImport = nullptr;
536   ImportDecl *LastLocalImport = nullptr;
537 
538   TranslationUnitDecl *TUDecl;
539   mutable ExternCContextDecl *ExternCContext = nullptr;
540   mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
541   mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
542 
543   /// The associated SourceManager object.
544   SourceManager &SourceMgr;
545 
546   /// The language options used to create the AST associated with
547   ///  this ASTContext object.
548   LangOptions &LangOpts;
549 
550   /// Blacklist object that is used by sanitizers to decide which
551   /// entities should not be instrumented.
552   std::unique_ptr<SanitizerBlacklist> SanitizerBL;
553 
554   /// Function filtering mechanism to determine whether a given function
555   /// should be imbued with the XRay "always" or "never" attributes.
556   std::unique_ptr<XRayFunctionFilter> XRayFilter;
557 
558   /// The allocator used to create AST objects.
559   ///
560   /// AST objects are never destructed; rather, all memory associated with the
561   /// AST objects will be released when the ASTContext itself is destroyed.
562   mutable llvm::BumpPtrAllocator BumpAlloc;
563 
564   /// Allocator for partial diagnostics.
565   PartialDiagnostic::StorageAllocator DiagAllocator;
566 
567   /// The current C++ ABI.
568   std::unique_ptr<CXXABI> ABI;
569   CXXABI *createCXXABI(const TargetInfo &T);
570 
571   /// The logical -> physical address space map.
572   const LangASMap *AddrSpaceMap = nullptr;
573 
574   /// Address space map mangling must be used with language specific
575   /// address spaces (e.g. OpenCL/CUDA)
576   bool AddrSpaceMapMangling;
577 
578   const TargetInfo *Target = nullptr;
579   const TargetInfo *AuxTarget = nullptr;
580   clang::PrintingPolicy PrintingPolicy;
581   std::unique_ptr<interp::Context> InterpContext;
582   std::unique_ptr<ParentMapContext> ParentMapCtx;
583 
584 public:
585   IdentifierTable &Idents;
586   SelectorTable &Selectors;
587   Builtin::Context &BuiltinInfo;
588   mutable DeclarationNameTable DeclarationNames;
589   IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
590   ASTMutationListener *Listener = nullptr;
591 
592   /// Returns the clang bytecode interpreter context.
593   interp::Context &getInterpContext();
594 
595   /// Returns the dynamic AST node parent map context.
596   ParentMapContext &getParentMapContext();
597 
598   // A traversal scope limits the parts of the AST visible to certain analyses.
599   // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and
600   // getParents() will only observe reachable parent edges.
601   //
602   // The scope is defined by a set of "top-level" declarations.
603   // Initially, it is the entire TU: {getTranslationUnitDecl()}.
604   // Changing the scope clears the parent cache, which is expensive to rebuild.
605   std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
606   void setTraversalScope(const std::vector<Decl *> &);
607 
608   /// Forwards to get node parents from the ParentMapContext. New callers should
609   /// use ParentMapContext::getParents() directly.
610   template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
611 
612   const clang::PrintingPolicy &getPrintingPolicy() const {
613     return PrintingPolicy;
614   }
615 
616   void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
617     PrintingPolicy = Policy;
618   }
619 
620   SourceManager& getSourceManager() { return SourceMgr; }
621   const SourceManager& getSourceManager() const { return SourceMgr; }
622 
623   llvm::BumpPtrAllocator &getAllocator() const {
624     return BumpAlloc;
625   }
626 
627   void *Allocate(size_t Size, unsigned Align = 8) const {
628     return BumpAlloc.Allocate(Size, Align);
629   }
630   template <typename T> T *Allocate(size_t Num = 1) const {
631     return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
632   }
633   void Deallocate(void *Ptr) const {}
634 
635   /// Return the total amount of physical memory allocated for representing
636   /// AST nodes and type information.
637   size_t getASTAllocatedMemory() const {
638     return BumpAlloc.getTotalMemory();
639   }
640 
641   /// Return the total memory used for various side tables.
642   size_t getSideTableAllocatedMemory() const;
643 
644   PartialDiagnostic::StorageAllocator &getDiagAllocator() {
645     return DiagAllocator;
646   }
647 
648   const TargetInfo &getTargetInfo() const { return *Target; }
649   const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
650 
651   /// getIntTypeForBitwidth -
652   /// sets integer QualTy according to specified details:
653   /// bitwidth, signed/unsigned.
654   /// Returns empty type if there is no appropriate target types.
655   QualType getIntTypeForBitwidth(unsigned DestWidth,
656                                  unsigned Signed) const;
657 
658   /// getRealTypeForBitwidth -
659   /// sets floating point QualTy according to specified bitwidth.
660   /// Returns empty type if there is no appropriate target types.
661   QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const;
662 
663   bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
664 
665   const LangOptions& getLangOpts() const { return LangOpts; }
666 
667   const SanitizerBlacklist &getSanitizerBlacklist() const {
668     return *SanitizerBL;
669   }
670 
671   const XRayFunctionFilter &getXRayFilter() const {
672     return *XRayFilter;
673   }
674 
675   DiagnosticsEngine &getDiagnostics() const;
676 
677   FullSourceLoc getFullLoc(SourceLocation Loc) const {
678     return FullSourceLoc(Loc,SourceMgr);
679   }
680 
681   /// All comments in this translation unit.
682   RawCommentList Comments;
683 
684   /// True if comments are already loaded from ExternalASTSource.
685   mutable bool CommentsLoaded = false;
686 
687   /// Mapping from declaration to directly attached comment.
688   ///
689   /// Raw comments are owned by Comments list.  This mapping is populated
690   /// lazily.
691   mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
692 
693   /// Mapping from canonical declaration to the first redeclaration in chain
694   /// that has a comment attached.
695   ///
696   /// Raw comments are owned by Comments list.  This mapping is populated
697   /// lazily.
698   mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
699 
700   /// Keeps track of redeclaration chains that don't have any comment attached.
701   /// Mapping from canonical declaration to redeclaration chain that has no
702   /// comments attached to any redeclaration. Specifically it's mapping to
703   /// the last redeclaration we've checked.
704   ///
705   /// Shall not contain declarations that have comments attached to any
706   /// redeclaration in their chain.
707   mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
708 
709   /// Mapping from declarations to parsed comments attached to any
710   /// redeclaration.
711   mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
712 
713   /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
714   /// and removes the redeclaration chain from the set of commentless chains.
715   ///
716   /// Don't do anything if a comment has already been attached to \p OriginalD
717   /// or its redeclaration chain.
718   void cacheRawCommentForDecl(const Decl &OriginalD,
719                               const RawComment &Comment) const;
720 
721   /// \returns searches \p CommentsInFile for doc comment for \p D.
722   ///
723   /// \p RepresentativeLocForDecl is used as a location for searching doc
724   /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
725   /// same file where \p RepresentativeLocForDecl is.
726   RawComment *getRawCommentForDeclNoCacheImpl(
727       const Decl *D, const SourceLocation RepresentativeLocForDecl,
728       const std::map<unsigned, RawComment *> &CommentsInFile) const;
729 
730   /// Return the documentation comment attached to a given declaration,
731   /// without looking into cache.
732   RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
733 
734 public:
735   void addComment(const RawComment &RC);
736 
737   /// Return the documentation comment attached to a given declaration.
738   /// Returns nullptr if no comment is attached.
739   ///
740   /// \param OriginalDecl if not nullptr, is set to declaration AST node that
741   /// had the comment, if the comment we found comes from a redeclaration.
742   const RawComment *
743   getRawCommentForAnyRedecl(const Decl *D,
744                             const Decl **OriginalDecl = nullptr) const;
745 
746   /// Searches existing comments for doc comments that should be attached to \p
747   /// Decls. If any doc comment is found, it is parsed.
748   ///
749   /// Requirement: All \p Decls are in the same file.
750   ///
751   /// If the last comment in the file is already attached we assume
752   /// there are not comments left to be attached to \p Decls.
753   void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
754                                        const Preprocessor *PP);
755 
756   /// Return parsed documentation comment attached to a given declaration.
757   /// Returns nullptr if no comment is attached.
758   ///
759   /// \param PP the Preprocessor used with this TU.  Could be nullptr if
760   /// preprocessor is not available.
761   comments::FullComment *getCommentForDecl(const Decl *D,
762                                            const Preprocessor *PP) const;
763 
764   /// Return parsed documentation comment attached to a given declaration.
765   /// Returns nullptr if no comment is attached. Does not look at any
766   /// redeclarations of the declaration.
767   comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
768 
769   comments::FullComment *cloneFullComment(comments::FullComment *FC,
770                                          const Decl *D) const;
771 
772 private:
773   mutable comments::CommandTraits CommentCommandTraits;
774 
775   /// Iterator that visits import declarations.
776   class import_iterator {
777     ImportDecl *Import = nullptr;
778 
779   public:
780     using value_type = ImportDecl *;
781     using reference = ImportDecl *;
782     using pointer = ImportDecl *;
783     using difference_type = int;
784     using iterator_category = std::forward_iterator_tag;
785 
786     import_iterator() = default;
787     explicit import_iterator(ImportDecl *Import) : Import(Import) {}
788 
789     reference operator*() const { return Import; }
790     pointer operator->() const { return Import; }
791 
792     import_iterator &operator++() {
793       Import = ASTContext::getNextLocalImport(Import);
794       return *this;
795     }
796 
797     import_iterator operator++(int) {
798       import_iterator Other(*this);
799       ++(*this);
800       return Other;
801     }
802 
803     friend bool operator==(import_iterator X, import_iterator Y) {
804       return X.Import == Y.Import;
805     }
806 
807     friend bool operator!=(import_iterator X, import_iterator Y) {
808       return X.Import != Y.Import;
809     }
810   };
811 
812 public:
813   comments::CommandTraits &getCommentCommandTraits() const {
814     return CommentCommandTraits;
815   }
816 
817   /// Retrieve the attributes for the given declaration.
818   AttrVec& getDeclAttrs(const Decl *D);
819 
820   /// Erase the attributes corresponding to the given declaration.
821   void eraseDeclAttrs(const Decl *D);
822 
823   /// If this variable is an instantiated static data member of a
824   /// class template specialization, returns the templated static data member
825   /// from which it was instantiated.
826   // FIXME: Remove ?
827   MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
828                                                            const VarDecl *Var);
829 
830   TemplateOrSpecializationInfo
831   getTemplateOrSpecializationInfo(const VarDecl *Var);
832 
833   /// Note that the static data member \p Inst is an instantiation of
834   /// the static data member template \p Tmpl of a class template.
835   void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
836                                            TemplateSpecializationKind TSK,
837                         SourceLocation PointOfInstantiation = SourceLocation());
838 
839   void setTemplateOrSpecializationInfo(VarDecl *Inst,
840                                        TemplateOrSpecializationInfo TSI);
841 
842   /// If the given using decl \p Inst is an instantiation of a
843   /// (possibly unresolved) using decl from a template instantiation,
844   /// return it.
845   NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
846 
847   /// Remember that the using decl \p Inst is an instantiation
848   /// of the using decl \p Pattern of a class template.
849   void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
850 
851   void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
852                                           UsingShadowDecl *Pattern);
853   UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
854 
855   FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
856 
857   void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
858 
859   // Access to the set of methods overridden by the given C++ method.
860   using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
861   overridden_cxx_method_iterator
862   overridden_methods_begin(const CXXMethodDecl *Method) const;
863 
864   overridden_cxx_method_iterator
865   overridden_methods_end(const CXXMethodDecl *Method) const;
866 
867   unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
868 
869   using overridden_method_range =
870       llvm::iterator_range<overridden_cxx_method_iterator>;
871 
872   overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
873 
874   /// Note that the given C++ \p Method overrides the given \p
875   /// Overridden method.
876   void addOverriddenMethod(const CXXMethodDecl *Method,
877                            const CXXMethodDecl *Overridden);
878 
879   /// Return C++ or ObjC overridden methods for the given \p Method.
880   ///
881   /// An ObjC method is considered to override any method in the class's
882   /// base classes, its protocols, or its categories' protocols, that has
883   /// the same selector and is of the same kind (class or instance).
884   /// A method in an implementation is not considered as overriding the same
885   /// method in the interface or its categories.
886   void getOverriddenMethods(
887                         const NamedDecl *Method,
888                         SmallVectorImpl<const NamedDecl *> &Overridden) const;
889 
890   /// Notify the AST context that a new import declaration has been
891   /// parsed or implicitly created within this translation unit.
892   void addedLocalImportDecl(ImportDecl *Import);
893 
894   static ImportDecl *getNextLocalImport(ImportDecl *Import) {
895     return Import->getNextLocalImport();
896   }
897 
898   using import_range = llvm::iterator_range<import_iterator>;
899 
900   import_range local_imports() const {
901     return import_range(import_iterator(FirstLocalImport), import_iterator());
902   }
903 
904   Decl *getPrimaryMergedDecl(Decl *D) {
905     Decl *Result = MergedDecls.lookup(D);
906     return Result ? Result : D;
907   }
908   void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
909     MergedDecls[D] = Primary;
910   }
911 
912   /// Note that the definition \p ND has been merged into module \p M,
913   /// and should be visible whenever \p M is visible.
914   void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
915                                  bool NotifyListeners = true);
916 
917   /// Clean up the merged definition list. Call this if you might have
918   /// added duplicates into the list.
919   void deduplicateMergedDefinitonsFor(NamedDecl *ND);
920 
921   /// Get the additional modules in which the definition \p Def has
922   /// been merged.
923   ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
924 
925   /// Add a declaration to the list of declarations that are initialized
926   /// for a module. This will typically be a global variable (with internal
927   /// linkage) that runs module initializers, such as the iostream initializer,
928   /// or an ImportDecl nominating another module that has initializers.
929   void addModuleInitializer(Module *M, Decl *Init);
930 
931   void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
932 
933   /// Get the initializations to perform when importing a module, if any.
934   ArrayRef<Decl*> getModuleInitializers(Module *M);
935 
936   TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
937 
938   ExternCContextDecl *getExternCContextDecl() const;
939   BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
940   BuiltinTemplateDecl *getTypePackElementDecl() const;
941 
942   // Builtin Types.
943   CanQualType VoidTy;
944   CanQualType BoolTy;
945   CanQualType CharTy;
946   CanQualType WCharTy;  // [C++ 3.9.1p5].
947   CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
948   CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
949   CanQualType Char8Ty;  // [C++20 proposal]
950   CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
951   CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
952   CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
953   CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
954   CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
955   CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
956   CanQualType ShortAccumTy, AccumTy,
957       LongAccumTy;  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
958   CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
959   CanQualType ShortFractTy, FractTy, LongFractTy;
960   CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
961   CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
962   CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
963       SatUnsignedLongAccumTy;
964   CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
965   CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
966       SatUnsignedLongFractTy;
967   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
968   CanQualType BFloat16Ty;
969   CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
970   CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
971   CanQualType Float128ComplexTy;
972   CanQualType VoidPtrTy, NullPtrTy;
973   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
974   CanQualType BuiltinFnTy;
975   CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
976   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
977   CanQualType ObjCBuiltinBoolTy;
978 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
979   CanQualType SingletonId;
980 #include "clang/Basic/OpenCLImageTypes.def"
981   CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
982   CanQualType OCLQueueTy, OCLReserveIDTy;
983   CanQualType IncompleteMatrixIdxTy;
984   CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
985 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
986   CanQualType Id##Ty;
987 #include "clang/Basic/OpenCLExtensionTypes.def"
988 #define SVE_TYPE(Name, Id, SingletonId) \
989   CanQualType SingletonId;
990 #include "clang/Basic/AArch64SVEACLETypes.def"
991 
992   // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
993   mutable QualType AutoDeductTy;     // Deduction against 'auto'.
994   mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
995 
996   // Decl used to help define __builtin_va_list for some targets.
997   // The decl is built when constructing 'BuiltinVaListDecl'.
998   mutable Decl *VaListTagDecl = nullptr;
999 
1000   // Implicitly-declared type 'struct _GUID'.
1001   mutable TagDecl *MSGuidTagDecl = nullptr;
1002 
1003   ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1004              SelectorTable &sels, Builtin::Context &builtins);
1005   ASTContext(const ASTContext &) = delete;
1006   ASTContext &operator=(const ASTContext &) = delete;
1007   ~ASTContext();
1008 
1009   /// Attach an external AST source to the AST context.
1010   ///
1011   /// The external AST source provides the ability to load parts of
1012   /// the abstract syntax tree as needed from some external storage,
1013   /// e.g., a precompiled header.
1014   void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1015 
1016   /// Retrieve a pointer to the external AST source associated
1017   /// with this AST context, if any.
1018   ExternalASTSource *getExternalSource() const {
1019     return ExternalSource.get();
1020   }
1021 
1022   /// Attach an AST mutation listener to the AST context.
1023   ///
1024   /// The AST mutation listener provides the ability to track modifications to
1025   /// the abstract syntax tree entities committed after they were initially
1026   /// created.
1027   void setASTMutationListener(ASTMutationListener *Listener) {
1028     this->Listener = Listener;
1029   }
1030 
1031   /// Retrieve a pointer to the AST mutation listener associated
1032   /// with this AST context, if any.
1033   ASTMutationListener *getASTMutationListener() const { return Listener; }
1034 
1035   void PrintStats() const;
1036   const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1037 
1038   BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1039                                                 const IdentifierInfo *II) const;
1040 
1041   /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1042   /// declaration.
1043   RecordDecl *buildImplicitRecord(StringRef Name,
1044                                   RecordDecl::TagKind TK = TTK_Struct) const;
1045 
1046   /// Create a new implicit TU-level typedef declaration.
1047   TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1048 
1049   /// Retrieve the declaration for the 128-bit signed integer type.
1050   TypedefDecl *getInt128Decl() const;
1051 
1052   /// Retrieve the declaration for the 128-bit unsigned integer type.
1053   TypedefDecl *getUInt128Decl() const;
1054 
1055   //===--------------------------------------------------------------------===//
1056   //                           Type Constructors
1057   //===--------------------------------------------------------------------===//
1058 
1059 private:
1060   /// Return a type with extended qualifiers.
1061   QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1062 
1063   QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1064 
1065   QualType getPipeType(QualType T, bool ReadOnly) const;
1066 
1067 public:
1068   /// Return the uniqued reference to the type for an address space
1069   /// qualified type with the specified type and address space.
1070   ///
1071   /// The resulting type has a union of the qualifiers from T and the address
1072   /// space. If T already has an address space specifier, it is silently
1073   /// replaced.
1074   QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1075 
1076   /// Remove any existing address space on the type and returns the type
1077   /// with qualifiers intact (or that's the idea anyway)
1078   ///
1079   /// The return type should be T with all prior qualifiers minus the address
1080   /// space.
1081   QualType removeAddrSpaceQualType(QualType T) const;
1082 
1083   /// Apply Objective-C protocol qualifiers to the given type.
1084   /// \param allowOnPointerType specifies if we can apply protocol
1085   /// qualifiers on ObjCObjectPointerType. It can be set to true when
1086   /// constructing the canonical type of a Objective-C type parameter.
1087   QualType applyObjCProtocolQualifiers(QualType type,
1088       ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1089       bool allowOnPointerType = false) const;
1090 
1091   /// Return the uniqued reference to the type for an Objective-C
1092   /// gc-qualified type.
1093   ///
1094   /// The resulting type has a union of the qualifiers from T and the gc
1095   /// attribute.
1096   QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1097 
1098   /// Remove the existing address space on the type if it is a pointer size
1099   /// address space and return the type with qualifiers intact.
1100   QualType removePtrSizeAddrSpace(QualType T) const;
1101 
1102   /// Return the uniqued reference to the type for a \c restrict
1103   /// qualified type.
1104   ///
1105   /// The resulting type has a union of the qualifiers from \p T and
1106   /// \c restrict.
1107   QualType getRestrictType(QualType T) const {
1108     return T.withFastQualifiers(Qualifiers::Restrict);
1109   }
1110 
1111   /// Return the uniqued reference to the type for a \c volatile
1112   /// qualified type.
1113   ///
1114   /// The resulting type has a union of the qualifiers from \p T and
1115   /// \c volatile.
1116   QualType getVolatileType(QualType T) const {
1117     return T.withFastQualifiers(Qualifiers::Volatile);
1118   }
1119 
1120   /// Return the uniqued reference to the type for a \c const
1121   /// qualified type.
1122   ///
1123   /// The resulting type has a union of the qualifiers from \p T and \c const.
1124   ///
1125   /// It can be reasonably expected that this will always be equivalent to
1126   /// calling T.withConst().
1127   QualType getConstType(QualType T) const { return T.withConst(); }
1128 
1129   /// Change the ExtInfo on a function type.
1130   const FunctionType *adjustFunctionType(const FunctionType *Fn,
1131                                          FunctionType::ExtInfo EInfo);
1132 
1133   /// Adjust the given function result type.
1134   CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1135 
1136   /// Change the result type of a function type once it is deduced.
1137   void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1138 
1139   /// Get a function type and produce the equivalent function type with the
1140   /// specified exception specification. Type sugar that can be present on a
1141   /// declaration of a function with an exception specification is permitted
1142   /// and preserved. Other type sugar (for instance, typedefs) is not.
1143   QualType getFunctionTypeWithExceptionSpec(
1144       QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1145 
1146   /// Determine whether two function types are the same, ignoring
1147   /// exception specifications in cases where they're part of the type.
1148   bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1149 
1150   /// Change the exception specification on a function once it is
1151   /// delay-parsed, instantiated, or computed.
1152   void adjustExceptionSpec(FunctionDecl *FD,
1153                            const FunctionProtoType::ExceptionSpecInfo &ESI,
1154                            bool AsWritten = false);
1155 
1156   /// Get a function type and produce the equivalent function type where
1157   /// pointer size address spaces in the return type and parameter tyeps are
1158   /// replaced with the default address space.
1159   QualType getFunctionTypeWithoutPtrSizes(QualType T);
1160 
1161   /// Determine whether two function types are the same, ignoring pointer sizes
1162   /// in the return type and parameter types.
1163   bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1164 
1165   /// Return the uniqued reference to the type for a complex
1166   /// number with the specified element type.
1167   QualType getComplexType(QualType T) const;
1168   CanQualType getComplexType(CanQualType T) const {
1169     return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1170   }
1171 
1172   /// Return the uniqued reference to the type for a pointer to
1173   /// the specified type.
1174   QualType getPointerType(QualType T) const;
1175   CanQualType getPointerType(CanQualType T) const {
1176     return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1177   }
1178 
1179   /// Return the uniqued reference to a type adjusted from the original
1180   /// type to a new type.
1181   QualType getAdjustedType(QualType Orig, QualType New) const;
1182   CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1183     return CanQualType::CreateUnsafe(
1184         getAdjustedType((QualType)Orig, (QualType)New));
1185   }
1186 
1187   /// Return the uniqued reference to the decayed version of the given
1188   /// type.  Can only be called on array and function types which decay to
1189   /// pointer types.
1190   QualType getDecayedType(QualType T) const;
1191   CanQualType getDecayedType(CanQualType T) const {
1192     return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1193   }
1194 
1195   /// Return the uniqued reference to the atomic type for the specified
1196   /// type.
1197   QualType getAtomicType(QualType T) const;
1198 
1199   /// Return the uniqued reference to the type for a block of the
1200   /// specified type.
1201   QualType getBlockPointerType(QualType T) const;
1202 
1203   /// Gets the struct used to keep track of the descriptor for pointer to
1204   /// blocks.
1205   QualType getBlockDescriptorType() const;
1206 
1207   /// Return a read_only pipe type for the specified type.
1208   QualType getReadPipeType(QualType T) const;
1209 
1210   /// Return a write_only pipe type for the specified type.
1211   QualType getWritePipeType(QualType T) const;
1212 
1213   /// Return an extended integer type with the specified signedness and bit
1214   /// count.
1215   QualType getExtIntType(bool Unsigned, unsigned NumBits) const;
1216 
1217   /// Return a dependent extended integer type with the specified signedness and
1218   /// bit count.
1219   QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const;
1220 
1221   /// Gets the struct used to keep track of the extended descriptor for
1222   /// pointer to blocks.
1223   QualType getBlockDescriptorExtendedType() const;
1224 
1225   /// Map an AST Type to an OpenCLTypeKind enum value.
1226   OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1227 
1228   /// Get address space for OpenCL type.
1229   LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1230 
1231   void setcudaConfigureCallDecl(FunctionDecl *FD) {
1232     cudaConfigureCallDecl = FD;
1233   }
1234 
1235   FunctionDecl *getcudaConfigureCallDecl() {
1236     return cudaConfigureCallDecl;
1237   }
1238 
1239   /// Returns true iff we need copy/dispose helpers for the given type.
1240   bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1241 
1242   /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1243   /// is set to false in this case. If HasByrefExtendedLayout returns true,
1244   /// byref variable has extended lifetime.
1245   bool getByrefLifetime(QualType Ty,
1246                         Qualifiers::ObjCLifetime &Lifetime,
1247                         bool &HasByrefExtendedLayout) const;
1248 
1249   /// Return the uniqued reference to the type for an lvalue reference
1250   /// to the specified type.
1251   QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1252     const;
1253 
1254   /// Return the uniqued reference to the type for an rvalue reference
1255   /// to the specified type.
1256   QualType getRValueReferenceType(QualType T) const;
1257 
1258   /// Return the uniqued reference to the type for a member pointer to
1259   /// the specified type in the specified class.
1260   ///
1261   /// The class \p Cls is a \c Type because it could be a dependent name.
1262   QualType getMemberPointerType(QualType T, const Type *Cls) const;
1263 
1264   /// Return a non-unique reference to the type for a variable array of
1265   /// the specified element type.
1266   QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1267                                 ArrayType::ArraySizeModifier ASM,
1268                                 unsigned IndexTypeQuals,
1269                                 SourceRange Brackets) const;
1270 
1271   /// Return a non-unique reference to the type for a dependently-sized
1272   /// array of the specified element type.
1273   ///
1274   /// FIXME: We will need these to be uniqued, or at least comparable, at some
1275   /// point.
1276   QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1277                                       ArrayType::ArraySizeModifier ASM,
1278                                       unsigned IndexTypeQuals,
1279                                       SourceRange Brackets) const;
1280 
1281   /// Return a unique reference to the type for an incomplete array of
1282   /// the specified element type.
1283   QualType getIncompleteArrayType(QualType EltTy,
1284                                   ArrayType::ArraySizeModifier ASM,
1285                                   unsigned IndexTypeQuals) const;
1286 
1287   /// Return the unique reference to the type for a constant array of
1288   /// the specified element type.
1289   QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1290                                 const Expr *SizeExpr,
1291                                 ArrayType::ArraySizeModifier ASM,
1292                                 unsigned IndexTypeQuals) const;
1293 
1294   /// Return a type for a constant array for a string literal of the
1295   /// specified element type and length.
1296   QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1297 
1298   /// Returns a vla type where known sizes are replaced with [*].
1299   QualType getVariableArrayDecayedType(QualType Ty) const;
1300 
1301   // Convenience struct to return information about a builtin vector type.
1302   struct BuiltinVectorTypeInfo {
1303     QualType ElementType;
1304     llvm::ElementCount EC;
1305     unsigned NumVectors;
1306     BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1307                           unsigned NumVectors)
1308         : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1309   };
1310 
1311   /// Returns the element type, element count and number of vectors
1312   /// (in case of tuple) for a builtin vector type.
1313   BuiltinVectorTypeInfo
1314   getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1315 
1316   /// Return the unique reference to a scalable vector type of the specified
1317   /// element type and scalable number of elements.
1318   ///
1319   /// \pre \p EltTy must be a built-in type.
1320   QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const;
1321 
1322   /// Return the unique reference to a vector type of the specified
1323   /// element type and size.
1324   ///
1325   /// \pre \p VectorType must be a built-in type.
1326   QualType getVectorType(QualType VectorType, unsigned NumElts,
1327                          VectorType::VectorKind VecKind) const;
1328   /// Return the unique reference to the type for a dependently sized vector of
1329   /// the specified element type.
1330   QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1331                                   SourceLocation AttrLoc,
1332                                   VectorType::VectorKind VecKind) const;
1333 
1334   /// Return the unique reference to an extended vector type
1335   /// of the specified element type and size.
1336   ///
1337   /// \pre \p VectorType must be a built-in type.
1338   QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1339 
1340   /// \pre Return a non-unique reference to the type for a dependently-sized
1341   /// vector of the specified element type.
1342   ///
1343   /// FIXME: We will need these to be uniqued, or at least comparable, at some
1344   /// point.
1345   QualType getDependentSizedExtVectorType(QualType VectorType,
1346                                           Expr *SizeExpr,
1347                                           SourceLocation AttrLoc) const;
1348 
1349   /// Return the unique reference to the matrix type of the specified element
1350   /// type and size
1351   ///
1352   /// \pre \p ElementType must be a valid matrix element type (see
1353   /// MatrixType::isValidElementType).
1354   QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1355                                  unsigned NumColumns) const;
1356 
1357   /// Return the unique reference to the matrix type of the specified element
1358   /// type and size
1359   QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1360                                        Expr *ColumnExpr,
1361                                        SourceLocation AttrLoc) const;
1362 
1363   QualType getDependentAddressSpaceType(QualType PointeeType,
1364                                         Expr *AddrSpaceExpr,
1365                                         SourceLocation AttrLoc) const;
1366 
1367   /// Return a K&R style C function type like 'int()'.
1368   QualType getFunctionNoProtoType(QualType ResultTy,
1369                                   const FunctionType::ExtInfo &Info) const;
1370 
1371   QualType getFunctionNoProtoType(QualType ResultTy) const {
1372     return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1373   }
1374 
1375   /// Return a normal function type with a typed argument list.
1376   QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1377                            const FunctionProtoType::ExtProtoInfo &EPI) const {
1378     return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1379   }
1380 
1381   QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1382 
1383 private:
1384   /// Return a normal function type with a typed argument list.
1385   QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1386                                    const FunctionProtoType::ExtProtoInfo &EPI,
1387                                    bool OnlyWantCanonical) const;
1388 
1389 public:
1390   /// Return the unique reference to the type for the specified type
1391   /// declaration.
1392   QualType getTypeDeclType(const TypeDecl *Decl,
1393                            const TypeDecl *PrevDecl = nullptr) const {
1394     assert(Decl && "Passed null for Decl param");
1395     if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1396 
1397     if (PrevDecl) {
1398       assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1399       Decl->TypeForDecl = PrevDecl->TypeForDecl;
1400       return QualType(PrevDecl->TypeForDecl, 0);
1401     }
1402 
1403     return getTypeDeclTypeSlow(Decl);
1404   }
1405 
1406   /// Return the unique reference to the type for the specified
1407   /// typedef-name decl.
1408   QualType getTypedefType(const TypedefNameDecl *Decl,
1409                           QualType Canon = QualType()) const;
1410 
1411   QualType getRecordType(const RecordDecl *Decl) const;
1412 
1413   QualType getEnumType(const EnumDecl *Decl) const;
1414 
1415   QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1416 
1417   QualType getAttributedType(attr::Kind attrKind,
1418                              QualType modifiedType,
1419                              QualType equivalentType);
1420 
1421   QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1422                                         QualType Replacement) const;
1423   QualType getSubstTemplateTypeParmPackType(
1424                                           const TemplateTypeParmType *Replaced,
1425                                             const TemplateArgument &ArgPack);
1426 
1427   QualType
1428   getTemplateTypeParmType(unsigned Depth, unsigned Index,
1429                           bool ParameterPack,
1430                           TemplateTypeParmDecl *ParmDecl = nullptr) const;
1431 
1432   QualType getTemplateSpecializationType(TemplateName T,
1433                                          ArrayRef<TemplateArgument> Args,
1434                                          QualType Canon = QualType()) const;
1435 
1436   QualType
1437   getCanonicalTemplateSpecializationType(TemplateName T,
1438                                          ArrayRef<TemplateArgument> Args) const;
1439 
1440   QualType getTemplateSpecializationType(TemplateName T,
1441                                          const TemplateArgumentListInfo &Args,
1442                                          QualType Canon = QualType()) const;
1443 
1444   TypeSourceInfo *
1445   getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1446                                     const TemplateArgumentListInfo &Args,
1447                                     QualType Canon = QualType()) const;
1448 
1449   QualType getParenType(QualType NamedType) const;
1450 
1451   QualType getMacroQualifiedType(QualType UnderlyingTy,
1452                                  const IdentifierInfo *MacroII) const;
1453 
1454   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1455                              NestedNameSpecifier *NNS, QualType NamedType,
1456                              TagDecl *OwnedTagDecl = nullptr) const;
1457   QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1458                                 NestedNameSpecifier *NNS,
1459                                 const IdentifierInfo *Name,
1460                                 QualType Canon = QualType()) const;
1461 
1462   QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1463                                                   NestedNameSpecifier *NNS,
1464                                                   const IdentifierInfo *Name,
1465                                     const TemplateArgumentListInfo &Args) const;
1466   QualType getDependentTemplateSpecializationType(
1467       ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1468       const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1469 
1470   TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1471 
1472   /// Get a template argument list with one argument per template parameter
1473   /// in a template parameter list, such as for the injected class name of
1474   /// a class template.
1475   void getInjectedTemplateArgs(const TemplateParameterList *Params,
1476                                SmallVectorImpl<TemplateArgument> &Args);
1477 
1478   QualType getPackExpansionType(QualType Pattern,
1479                                 Optional<unsigned> NumExpansions);
1480 
1481   QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1482                                 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1483 
1484   /// Legacy interface: cannot provide type arguments or __kindof.
1485   QualType getObjCObjectType(QualType Base,
1486                              ObjCProtocolDecl * const *Protocols,
1487                              unsigned NumProtocols) const;
1488 
1489   QualType getObjCObjectType(QualType Base,
1490                              ArrayRef<QualType> typeArgs,
1491                              ArrayRef<ObjCProtocolDecl *> protocols,
1492                              bool isKindOf) const;
1493 
1494   QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1495                                 ArrayRef<ObjCProtocolDecl *> protocols) const;
1496   void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1497                                     ObjCTypeParamDecl *New) const;
1498 
1499   bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1500 
1501   /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1502   /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1503   /// of protocols.
1504   bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1505                                             ObjCInterfaceDecl *IDecl);
1506 
1507   /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1508   QualType getObjCObjectPointerType(QualType OIT) const;
1509 
1510   /// GCC extension.
1511   QualType getTypeOfExprType(Expr *e) const;
1512   QualType getTypeOfType(QualType t) const;
1513 
1514   /// C++11 decltype.
1515   QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1516 
1517   /// Unary type transforms
1518   QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1519                                  UnaryTransformType::UTTKind UKind) const;
1520 
1521   /// C++11 deduced auto type.
1522   QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1523                        bool IsDependent, bool IsPack = false,
1524                        ConceptDecl *TypeConstraintConcept = nullptr,
1525                        ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1526 
1527   /// C++11 deduction pattern for 'auto' type.
1528   QualType getAutoDeductType() const;
1529 
1530   /// C++11 deduction pattern for 'auto &&' type.
1531   QualType getAutoRRefDeductType() const;
1532 
1533   /// C++17 deduced class template specialization type.
1534   QualType getDeducedTemplateSpecializationType(TemplateName Template,
1535                                                 QualType DeducedType,
1536                                                 bool IsDependent) const;
1537 
1538   /// Return the unique reference to the type for the specified TagDecl
1539   /// (struct/union/class/enum) decl.
1540   QualType getTagDeclType(const TagDecl *Decl) const;
1541 
1542   /// Return the unique type for "size_t" (C99 7.17), defined in
1543   /// <stddef.h>.
1544   ///
1545   /// The sizeof operator requires this (C99 6.5.3.4p4).
1546   CanQualType getSizeType() const;
1547 
1548   /// Return the unique signed counterpart of
1549   /// the integer type corresponding to size_t.
1550   CanQualType getSignedSizeType() const;
1551 
1552   /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1553   /// <stdint.h>.
1554   CanQualType getIntMaxType() const;
1555 
1556   /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1557   /// <stdint.h>.
1558   CanQualType getUIntMaxType() const;
1559 
1560   /// Return the unique wchar_t type available in C++ (and available as
1561   /// __wchar_t as a Microsoft extension).
1562   QualType getWCharType() const { return WCharTy; }
1563 
1564   /// Return the type of wide characters. In C++, this returns the
1565   /// unique wchar_t type. In C99, this returns a type compatible with the type
1566   /// defined in <stddef.h> as defined by the target.
1567   QualType getWideCharType() const { return WideCharTy; }
1568 
1569   /// Return the type of "signed wchar_t".
1570   ///
1571   /// Used when in C++, as a GCC extension.
1572   QualType getSignedWCharType() const;
1573 
1574   /// Return the type of "unsigned wchar_t".
1575   ///
1576   /// Used when in C++, as a GCC extension.
1577   QualType getUnsignedWCharType() const;
1578 
1579   /// In C99, this returns a type compatible with the type
1580   /// defined in <stddef.h> as defined by the target.
1581   QualType getWIntType() const { return WIntTy; }
1582 
1583   /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1584   /// as defined by the target.
1585   QualType getIntPtrType() const;
1586 
1587   /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1588   /// as defined by the target.
1589   QualType getUIntPtrType() const;
1590 
1591   /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1592   /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1593   QualType getPointerDiffType() const;
1594 
1595   /// Return the unique unsigned counterpart of "ptrdiff_t"
1596   /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1597   /// in the definition of %tu format specifier.
1598   QualType getUnsignedPointerDiffType() const;
1599 
1600   /// Return the unique type for "pid_t" defined in
1601   /// <sys/types.h>. We need this to compute the correct type for vfork().
1602   QualType getProcessIDType() const;
1603 
1604   /// Return the C structure type used to represent constant CFStrings.
1605   QualType getCFConstantStringType() const;
1606 
1607   /// Returns the C struct type for objc_super
1608   QualType getObjCSuperType() const;
1609   void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1610 
1611   /// Get the structure type used to representation CFStrings, or NULL
1612   /// if it hasn't yet been built.
1613   QualType getRawCFConstantStringType() const {
1614     if (CFConstantStringTypeDecl)
1615       return getTypedefType(CFConstantStringTypeDecl);
1616     return QualType();
1617   }
1618   void setCFConstantStringType(QualType T);
1619   TypedefDecl *getCFConstantStringDecl() const;
1620   RecordDecl *getCFConstantStringTagDecl() const;
1621 
1622   // This setter/getter represents the ObjC type for an NSConstantString.
1623   void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1624   QualType getObjCConstantStringInterface() const {
1625     return ObjCConstantStringType;
1626   }
1627 
1628   QualType getObjCNSStringType() const {
1629     return ObjCNSStringType;
1630   }
1631 
1632   void setObjCNSStringType(QualType T) {
1633     ObjCNSStringType = T;
1634   }
1635 
1636   /// Retrieve the type that \c id has been defined to, which may be
1637   /// different from the built-in \c id if \c id has been typedef'd.
1638   QualType getObjCIdRedefinitionType() const {
1639     if (ObjCIdRedefinitionType.isNull())
1640       return getObjCIdType();
1641     return ObjCIdRedefinitionType;
1642   }
1643 
1644   /// Set the user-written type that redefines \c id.
1645   void setObjCIdRedefinitionType(QualType RedefType) {
1646     ObjCIdRedefinitionType = RedefType;
1647   }
1648 
1649   /// Retrieve the type that \c Class has been defined to, which may be
1650   /// different from the built-in \c Class if \c Class has been typedef'd.
1651   QualType getObjCClassRedefinitionType() const {
1652     if (ObjCClassRedefinitionType.isNull())
1653       return getObjCClassType();
1654     return ObjCClassRedefinitionType;
1655   }
1656 
1657   /// Set the user-written type that redefines 'SEL'.
1658   void setObjCClassRedefinitionType(QualType RedefType) {
1659     ObjCClassRedefinitionType = RedefType;
1660   }
1661 
1662   /// Retrieve the type that 'SEL' has been defined to, which may be
1663   /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1664   QualType getObjCSelRedefinitionType() const {
1665     if (ObjCSelRedefinitionType.isNull())
1666       return getObjCSelType();
1667     return ObjCSelRedefinitionType;
1668   }
1669 
1670   /// Set the user-written type that redefines 'SEL'.
1671   void setObjCSelRedefinitionType(QualType RedefType) {
1672     ObjCSelRedefinitionType = RedefType;
1673   }
1674 
1675   /// Retrieve the identifier 'NSObject'.
1676   IdentifierInfo *getNSObjectName() const {
1677     if (!NSObjectName) {
1678       NSObjectName = &Idents.get("NSObject");
1679     }
1680 
1681     return NSObjectName;
1682   }
1683 
1684   /// Retrieve the identifier 'NSCopying'.
1685   IdentifierInfo *getNSCopyingName() {
1686     if (!NSCopyingName) {
1687       NSCopyingName = &Idents.get("NSCopying");
1688     }
1689 
1690     return NSCopyingName;
1691   }
1692 
1693   CanQualType getNSUIntegerType() const;
1694 
1695   CanQualType getNSIntegerType() const;
1696 
1697   /// Retrieve the identifier 'bool'.
1698   IdentifierInfo *getBoolName() const {
1699     if (!BoolName)
1700       BoolName = &Idents.get("bool");
1701     return BoolName;
1702   }
1703 
1704   IdentifierInfo *getMakeIntegerSeqName() const {
1705     if (!MakeIntegerSeqName)
1706       MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1707     return MakeIntegerSeqName;
1708   }
1709 
1710   IdentifierInfo *getTypePackElementName() const {
1711     if (!TypePackElementName)
1712       TypePackElementName = &Idents.get("__type_pack_element");
1713     return TypePackElementName;
1714   }
1715 
1716   /// Retrieve the Objective-C "instancetype" type, if already known;
1717   /// otherwise, returns a NULL type;
1718   QualType getObjCInstanceType() {
1719     return getTypeDeclType(getObjCInstanceTypeDecl());
1720   }
1721 
1722   /// Retrieve the typedef declaration corresponding to the Objective-C
1723   /// "instancetype" type.
1724   TypedefDecl *getObjCInstanceTypeDecl();
1725 
1726   /// Set the type for the C FILE type.
1727   void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1728 
1729   /// Retrieve the C FILE type.
1730   QualType getFILEType() const {
1731     if (FILEDecl)
1732       return getTypeDeclType(FILEDecl);
1733     return QualType();
1734   }
1735 
1736   /// Set the type for the C jmp_buf type.
1737   void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1738     this->jmp_bufDecl = jmp_bufDecl;
1739   }
1740 
1741   /// Retrieve the C jmp_buf type.
1742   QualType getjmp_bufType() const {
1743     if (jmp_bufDecl)
1744       return getTypeDeclType(jmp_bufDecl);
1745     return QualType();
1746   }
1747 
1748   /// Set the type for the C sigjmp_buf type.
1749   void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1750     this->sigjmp_bufDecl = sigjmp_bufDecl;
1751   }
1752 
1753   /// Retrieve the C sigjmp_buf type.
1754   QualType getsigjmp_bufType() const {
1755     if (sigjmp_bufDecl)
1756       return getTypeDeclType(sigjmp_bufDecl);
1757     return QualType();
1758   }
1759 
1760   /// Set the type for the C ucontext_t type.
1761   void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1762     this->ucontext_tDecl = ucontext_tDecl;
1763   }
1764 
1765   /// Retrieve the C ucontext_t type.
1766   QualType getucontext_tType() const {
1767     if (ucontext_tDecl)
1768       return getTypeDeclType(ucontext_tDecl);
1769     return QualType();
1770   }
1771 
1772   /// The result type of logical operations, '<', '>', '!=', etc.
1773   QualType getLogicalOperationType() const {
1774     return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1775   }
1776 
1777   /// Emit the Objective-CC type encoding for the given type \p T into
1778   /// \p S.
1779   ///
1780   /// If \p Field is specified then record field names are also encoded.
1781   void getObjCEncodingForType(QualType T, std::string &S,
1782                               const FieldDecl *Field=nullptr,
1783                               QualType *NotEncodedT=nullptr) const;
1784 
1785   /// Emit the Objective-C property type encoding for the given
1786   /// type \p T into \p S.
1787   void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1788 
1789   void getLegacyIntegralTypeEncoding(QualType &t) const;
1790 
1791   /// Put the string version of the type qualifiers \p QT into \p S.
1792   void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1793                                        std::string &S) const;
1794 
1795   /// Emit the encoded type for the function \p Decl into \p S.
1796   ///
1797   /// This is in the same format as Objective-C method encodings.
1798   ///
1799   /// \returns true if an error occurred (e.g., because one of the parameter
1800   /// types is incomplete), false otherwise.
1801   std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1802 
1803   /// Emit the encoded type for the method declaration \p Decl into
1804   /// \p S.
1805   std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1806                                            bool Extended = false) const;
1807 
1808   /// Return the encoded type for this block declaration.
1809   std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1810 
1811   /// getObjCEncodingForPropertyDecl - Return the encoded type for
1812   /// this method declaration. If non-NULL, Container must be either
1813   /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1814   /// only be NULL when getting encodings for protocol properties.
1815   std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1816                                              const Decl *Container) const;
1817 
1818   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1819                                       ObjCProtocolDecl *rProto) const;
1820 
1821   ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1822                                                   const ObjCPropertyDecl *PD,
1823                                                   const Decl *Container) const;
1824 
1825   /// Return the size of type \p T for Objective-C encoding purpose,
1826   /// in characters.
1827   CharUnits getObjCEncodingTypeSize(QualType T) const;
1828 
1829   /// Retrieve the typedef corresponding to the predefined \c id type
1830   /// in Objective-C.
1831   TypedefDecl *getObjCIdDecl() const;
1832 
1833   /// Represents the Objective-CC \c id type.
1834   ///
1835   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1836   /// pointer type, a pointer to a struct.
1837   QualType getObjCIdType() const {
1838     return getTypeDeclType(getObjCIdDecl());
1839   }
1840 
1841   /// Retrieve the typedef corresponding to the predefined 'SEL' type
1842   /// in Objective-C.
1843   TypedefDecl *getObjCSelDecl() const;
1844 
1845   /// Retrieve the type that corresponds to the predefined Objective-C
1846   /// 'SEL' type.
1847   QualType getObjCSelType() const {
1848     return getTypeDeclType(getObjCSelDecl());
1849   }
1850 
1851   /// Retrieve the typedef declaration corresponding to the predefined
1852   /// Objective-C 'Class' type.
1853   TypedefDecl *getObjCClassDecl() const;
1854 
1855   /// Represents the Objective-C \c Class type.
1856   ///
1857   /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1858   /// pointer type, a pointer to a struct.
1859   QualType getObjCClassType() const {
1860     return getTypeDeclType(getObjCClassDecl());
1861   }
1862 
1863   /// Retrieve the Objective-C class declaration corresponding to
1864   /// the predefined \c Protocol class.
1865   ObjCInterfaceDecl *getObjCProtocolDecl() const;
1866 
1867   /// Retrieve declaration of 'BOOL' typedef
1868   TypedefDecl *getBOOLDecl() const {
1869     return BOOLDecl;
1870   }
1871 
1872   /// Save declaration of 'BOOL' typedef
1873   void setBOOLDecl(TypedefDecl *TD) {
1874     BOOLDecl = TD;
1875   }
1876 
1877   /// type of 'BOOL' type.
1878   QualType getBOOLType() const {
1879     return getTypeDeclType(getBOOLDecl());
1880   }
1881 
1882   /// Retrieve the type of the Objective-C \c Protocol class.
1883   QualType getObjCProtoType() const {
1884     return getObjCInterfaceType(getObjCProtocolDecl());
1885   }
1886 
1887   /// Retrieve the C type declaration corresponding to the predefined
1888   /// \c __builtin_va_list type.
1889   TypedefDecl *getBuiltinVaListDecl() const;
1890 
1891   /// Retrieve the type of the \c __builtin_va_list type.
1892   QualType getBuiltinVaListType() const {
1893     return getTypeDeclType(getBuiltinVaListDecl());
1894   }
1895 
1896   /// Retrieve the C type declaration corresponding to the predefined
1897   /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1898   /// for some targets.
1899   Decl *getVaListTagDecl() const;
1900 
1901   /// Retrieve the C type declaration corresponding to the predefined
1902   /// \c __builtin_ms_va_list type.
1903   TypedefDecl *getBuiltinMSVaListDecl() const;
1904 
1905   /// Retrieve the type of the \c __builtin_ms_va_list type.
1906   QualType getBuiltinMSVaListType() const {
1907     return getTypeDeclType(getBuiltinMSVaListDecl());
1908   }
1909 
1910   /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
1911   TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
1912 
1913   /// Retrieve the implicitly-predeclared 'struct _GUID' type.
1914   QualType getMSGuidType() const {
1915     assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
1916     return getTagDeclType(MSGuidTagDecl);
1917   }
1918 
1919   /// Return whether a declaration to a builtin is allowed to be
1920   /// overloaded/redeclared.
1921   bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1922 
1923   /// Return a type with additional \c const, \c volatile, or
1924   /// \c restrict qualifiers.
1925   QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1926     return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1927   }
1928 
1929   /// Un-split a SplitQualType.
1930   QualType getQualifiedType(SplitQualType split) const {
1931     return getQualifiedType(split.Ty, split.Quals);
1932   }
1933 
1934   /// Return a type with additional qualifiers.
1935   QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1936     if (!Qs.hasNonFastQualifiers())
1937       return T.withFastQualifiers(Qs.getFastQualifiers());
1938     QualifierCollector Qc(Qs);
1939     const Type *Ptr = Qc.strip(T);
1940     return getExtQualType(Ptr, Qc);
1941   }
1942 
1943   /// Return a type with additional qualifiers.
1944   QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1945     if (!Qs.hasNonFastQualifiers())
1946       return QualType(T, Qs.getFastQualifiers());
1947     return getExtQualType(T, Qs);
1948   }
1949 
1950   /// Return a type with the given lifetime qualifier.
1951   ///
1952   /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1953   QualType getLifetimeQualifiedType(QualType type,
1954                                     Qualifiers::ObjCLifetime lifetime) {
1955     assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1956     assert(lifetime != Qualifiers::OCL_None);
1957 
1958     Qualifiers qs;
1959     qs.addObjCLifetime(lifetime);
1960     return getQualifiedType(type, qs);
1961   }
1962 
1963   /// getUnqualifiedObjCPointerType - Returns version of
1964   /// Objective-C pointer type with lifetime qualifier removed.
1965   QualType getUnqualifiedObjCPointerType(QualType type) const {
1966     if (!type.getTypePtr()->isObjCObjectPointerType() ||
1967         !type.getQualifiers().hasObjCLifetime())
1968       return type;
1969     Qualifiers Qs = type.getQualifiers();
1970     Qs.removeObjCLifetime();
1971     return getQualifiedType(type.getUnqualifiedType(), Qs);
1972   }
1973 
1974   unsigned char getFixedPointScale(QualType Ty) const;
1975   unsigned char getFixedPointIBits(QualType Ty) const;
1976   FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
1977   APFixedPoint getFixedPointMax(QualType Ty) const;
1978   APFixedPoint getFixedPointMin(QualType Ty) const;
1979 
1980   DeclarationNameInfo getNameForTemplate(TemplateName Name,
1981                                          SourceLocation NameLoc) const;
1982 
1983   TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1984                                          UnresolvedSetIterator End) const;
1985   TemplateName getAssumedTemplateName(DeclarationName Name) const;
1986 
1987   TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1988                                         bool TemplateKeyword,
1989                                         TemplateDecl *Template) const;
1990 
1991   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1992                                         const IdentifierInfo *Name) const;
1993   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1994                                         OverloadedOperatorKind Operator) const;
1995   TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1996                                             TemplateName replacement) const;
1997   TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1998                                         const TemplateArgument &ArgPack) const;
1999 
2000   enum GetBuiltinTypeError {
2001     /// No error
2002     GE_None,
2003 
2004     /// Missing a type
2005     GE_Missing_type,
2006 
2007     /// Missing a type from <stdio.h>
2008     GE_Missing_stdio,
2009 
2010     /// Missing a type from <setjmp.h>
2011     GE_Missing_setjmp,
2012 
2013     /// Missing a type from <ucontext.h>
2014     GE_Missing_ucontext
2015   };
2016 
2017   /// Return the type for the specified builtin.
2018   ///
2019   /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2020   /// arguments to the builtin that are required to be integer constant
2021   /// expressions.
2022   QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2023                           unsigned *IntegerConstantArgs = nullptr) const;
2024 
2025   /// Types and expressions required to build C++2a three-way comparisons
2026   /// using operator<=>, including the values return by builtin <=> operators.
2027   ComparisonCategories CompCategories;
2028 
2029 private:
2030   CanQualType getFromTargetType(unsigned Type) const;
2031   TypeInfo getTypeInfoImpl(const Type *T) const;
2032 
2033   //===--------------------------------------------------------------------===//
2034   //                         Type Predicates.
2035   //===--------------------------------------------------------------------===//
2036 
2037 public:
2038   /// Return one of the GCNone, Weak or Strong Objective-C garbage
2039   /// collection attributes.
2040   Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2041 
2042   /// Return true if the given vector types are of the same unqualified
2043   /// type or if they are equivalent to the same GCC vector type.
2044   ///
2045   /// \note This ignores whether they are target-specific (AltiVec or Neon)
2046   /// types.
2047   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2048 
2049   /// Return true if the type has been explicitly qualified with ObjC ownership.
2050   /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2051   /// some cases the compiler treats these differently.
2052   bool hasDirectOwnershipQualifier(QualType Ty) const;
2053 
2054   /// Return true if this is an \c NSObject object with its \c NSObject
2055   /// attribute set.
2056   static bool isObjCNSObjectType(QualType Ty) {
2057     return Ty->isObjCNSObjectType();
2058   }
2059 
2060   //===--------------------------------------------------------------------===//
2061   //                         Type Sizing and Analysis
2062   //===--------------------------------------------------------------------===//
2063 
2064   /// Return the APFloat 'semantics' for the specified scalar floating
2065   /// point type.
2066   const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2067 
2068   /// Get the size and alignment of the specified complete type in bits.
2069   TypeInfo getTypeInfo(const Type *T) const;
2070   TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2071 
2072   /// Get default simd alignment of the specified complete type in bits.
2073   unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2074 
2075   /// Return the size of the specified (complete) type \p T, in bits.
2076   uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2077   uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2078 
2079   /// Return the size of the character type, in bits.
2080   uint64_t getCharWidth() const {
2081     return getTypeSize(CharTy);
2082   }
2083 
2084   /// Convert a size in bits to a size in characters.
2085   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2086 
2087   /// Convert a size in characters to a size in bits.
2088   int64_t toBits(CharUnits CharSize) const;
2089 
2090   /// Return the size of the specified (complete) type \p T, in
2091   /// characters.
2092   CharUnits getTypeSizeInChars(QualType T) const;
2093   CharUnits getTypeSizeInChars(const Type *T) const;
2094 
2095   Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2096     if (Ty->isIncompleteType() || Ty->isDependentType())
2097       return None;
2098     return getTypeSizeInChars(Ty);
2099   }
2100 
2101   Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2102     return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2103   }
2104 
2105   /// Return the ABI-specified alignment of a (complete) type \p T, in
2106   /// bits.
2107   unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2108   unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2109 
2110   /// Return the ABI-specified natural alignment of a (complete) type \p T,
2111   /// before alignment adjustments, in bits.
2112   ///
2113   /// This alignment is curently used only by ARM and AArch64 when passing
2114   /// arguments of a composite type.
2115   unsigned getTypeUnadjustedAlign(QualType T) const {
2116     return getTypeUnadjustedAlign(T.getTypePtr());
2117   }
2118   unsigned getTypeUnadjustedAlign(const Type *T) const;
2119 
2120   /// Return the ABI-specified alignment of a type, in bits, or 0 if
2121   /// the type is incomplete and we cannot determine the alignment (for
2122   /// example, from alignment attributes).
2123   unsigned getTypeAlignIfKnown(QualType T) const;
2124 
2125   /// Return the ABI-specified alignment of a (complete) type \p T, in
2126   /// characters.
2127   CharUnits getTypeAlignInChars(QualType T) const;
2128   CharUnits getTypeAlignInChars(const Type *T) const;
2129 
2130   /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2131   /// in characters, before alignment adjustments. This method does not work on
2132   /// incomplete types.
2133   CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2134   CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2135 
2136   // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2137   // type is a record, its data size is returned.
2138   std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2139 
2140   std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2141   std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2142 
2143   /// Determine if the alignment the type has was required using an
2144   /// alignment attribute.
2145   bool isAlignmentRequired(const Type *T) const;
2146   bool isAlignmentRequired(QualType T) const;
2147 
2148   /// Return the "preferred" alignment of the specified type \p T for
2149   /// the current target, in bits.
2150   ///
2151   /// This can be different than the ABI alignment in cases where it is
2152   /// beneficial for performance to overalign a data type.
2153   unsigned getPreferredTypeAlign(const Type *T) const;
2154 
2155   /// Return the default alignment for __attribute__((aligned)) on
2156   /// this target, to be used if no alignment value is specified.
2157   unsigned getTargetDefaultAlignForAttributeAligned() const;
2158 
2159   /// Return the alignment in bits that should be given to a
2160   /// global variable with type \p T.
2161   unsigned getAlignOfGlobalVar(QualType T) const;
2162 
2163   /// Return the alignment in characters that should be given to a
2164   /// global variable with type \p T.
2165   CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2166 
2167   /// Return a conservative estimate of the alignment of the specified
2168   /// decl \p D.
2169   ///
2170   /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2171   /// alignment.
2172   ///
2173   /// If \p ForAlignof, references are treated like their underlying type
2174   /// and  large arrays don't get any special treatment. If not \p ForAlignof
2175   /// it computes the value expected by CodeGen: references are treated like
2176   /// pointers and large arrays get extra alignment.
2177   CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2178 
2179   /// Return the alignment (in bytes) of the thrown exception object. This is
2180   /// only meaningful for targets that allocate C++ exceptions in a system
2181   /// runtime, such as those using the Itanium C++ ABI.
2182   CharUnits getExnObjectAlignment() const;
2183 
2184   /// Get or compute information about the layout of the specified
2185   /// record (struct/union/class) \p D, which indicates its size and field
2186   /// position information.
2187   const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2188 
2189   /// Get or compute information about the layout of the specified
2190   /// Objective-C interface.
2191   const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2192     const;
2193 
2194   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2195                         bool Simple = false) const;
2196 
2197   /// Get or compute information about the layout of the specified
2198   /// Objective-C implementation.
2199   ///
2200   /// This may differ from the interface if synthesized ivars are present.
2201   const ASTRecordLayout &
2202   getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2203 
2204   /// Get our current best idea for the key function of the
2205   /// given record decl, or nullptr if there isn't one.
2206   ///
2207   /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2208   ///   ...the first non-pure virtual function that is not inline at the
2209   ///   point of class definition.
2210   ///
2211   /// Other ABIs use the same idea.  However, the ARM C++ ABI ignores
2212   /// virtual functions that are defined 'inline', which means that
2213   /// the result of this computation can change.
2214   const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2215 
2216   /// Observe that the given method cannot be a key function.
2217   /// Checks the key-function cache for the method's class and clears it
2218   /// if matches the given declaration.
2219   ///
2220   /// This is used in ABIs where out-of-line definitions marked
2221   /// inline are not considered to be key functions.
2222   ///
2223   /// \param method should be the declaration from the class definition
2224   void setNonKeyFunction(const CXXMethodDecl *method);
2225 
2226   /// Loading virtual member pointers using the virtual inheritance model
2227   /// always results in an adjustment using the vbtable even if the index is
2228   /// zero.
2229   ///
2230   /// This is usually OK because the first slot in the vbtable points
2231   /// backwards to the top of the MDC.  However, the MDC might be reusing a
2232   /// vbptr from an nv-base.  In this case, the first slot in the vbtable
2233   /// points to the start of the nv-base which introduced the vbptr and *not*
2234   /// the MDC.  Modify the NonVirtualBaseAdjustment to account for this.
2235   CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2236 
2237   /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2238   uint64_t getFieldOffset(const ValueDecl *FD) const;
2239 
2240   /// Get the offset of an ObjCIvarDecl in bits.
2241   uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2242                                 const ObjCImplementationDecl *ID,
2243                                 const ObjCIvarDecl *Ivar) const;
2244 
2245   bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2246 
2247   VTableContextBase *getVTableContext();
2248 
2249   /// If \p T is null pointer, assume the target in ASTContext.
2250   MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2251 
2252   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2253                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2254 
2255   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2256   void CollectInheritedProtocols(const Decl *CDecl,
2257                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2258 
2259   /// Return true if the specified type has unique object representations
2260   /// according to (C++17 [meta.unary.prop]p9)
2261   bool hasUniqueObjectRepresentations(QualType Ty) const;
2262 
2263   //===--------------------------------------------------------------------===//
2264   //                            Type Operators
2265   //===--------------------------------------------------------------------===//
2266 
2267   /// Return the canonical (structural) type corresponding to the
2268   /// specified potentially non-canonical type \p T.
2269   ///
2270   /// The non-canonical version of a type may have many "decorated" versions of
2271   /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
2272   /// returned type is guaranteed to be free of any of these, allowing two
2273   /// canonical types to be compared for exact equality with a simple pointer
2274   /// comparison.
2275   CanQualType getCanonicalType(QualType T) const {
2276     return CanQualType::CreateUnsafe(T.getCanonicalType());
2277   }
2278 
2279   const Type *getCanonicalType(const Type *T) const {
2280     return T->getCanonicalTypeInternal().getTypePtr();
2281   }
2282 
2283   /// Return the canonical parameter type corresponding to the specific
2284   /// potentially non-canonical one.
2285   ///
2286   /// Qualifiers are stripped off, functions are turned into function
2287   /// pointers, and arrays decay one level into pointers.
2288   CanQualType getCanonicalParamType(QualType T) const;
2289 
2290   /// Determine whether the given types \p T1 and \p T2 are equivalent.
2291   bool hasSameType(QualType T1, QualType T2) const {
2292     return getCanonicalType(T1) == getCanonicalType(T2);
2293   }
2294   bool hasSameType(const Type *T1, const Type *T2) const {
2295     return getCanonicalType(T1) == getCanonicalType(T2);
2296   }
2297 
2298   /// Return this type as a completely-unqualified array type,
2299   /// capturing the qualifiers in \p Quals.
2300   ///
2301   /// This will remove the minimal amount of sugaring from the types, similar
2302   /// to the behavior of QualType::getUnqualifiedType().
2303   ///
2304   /// \param T is the qualified type, which may be an ArrayType
2305   ///
2306   /// \param Quals will receive the full set of qualifiers that were
2307   /// applied to the array.
2308   ///
2309   /// \returns if this is an array type, the completely unqualified array type
2310   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2311   QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2312 
2313   /// Determine whether the given types are equivalent after
2314   /// cvr-qualifiers have been removed.
2315   bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2316     return getCanonicalType(T1).getTypePtr() ==
2317            getCanonicalType(T2).getTypePtr();
2318   }
2319 
2320   bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2321                                        bool IsParam) const {
2322     auto SubTnullability = SubT->getNullability(*this);
2323     auto SuperTnullability = SuperT->getNullability(*this);
2324     if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2325       // Neither has nullability; return true
2326       if (!SubTnullability)
2327         return true;
2328       // Both have nullability qualifier.
2329       if (*SubTnullability == *SuperTnullability ||
2330           *SubTnullability == NullabilityKind::Unspecified ||
2331           *SuperTnullability == NullabilityKind::Unspecified)
2332         return true;
2333 
2334       if (IsParam) {
2335         // Ok for the superclass method parameter to be "nonnull" and the subclass
2336         // method parameter to be "nullable"
2337         return (*SuperTnullability == NullabilityKind::NonNull &&
2338                 *SubTnullability == NullabilityKind::Nullable);
2339       }
2340       else {
2341         // For the return type, it's okay for the superclass method to specify
2342         // "nullable" and the subclass method specify "nonnull"
2343         return (*SuperTnullability == NullabilityKind::Nullable &&
2344                 *SubTnullability == NullabilityKind::NonNull);
2345       }
2346     }
2347     return true;
2348   }
2349 
2350   bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2351                            const ObjCMethodDecl *MethodImp);
2352 
2353   bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2354   bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2355 
2356   /// Determine if two types are similar, according to the C++ rules. That is,
2357   /// determine if they are the same other than qualifiers on the initial
2358   /// sequence of pointer / pointer-to-member / array (and in Clang, object
2359   /// pointer) types and their element types.
2360   ///
2361   /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2362   /// those qualifiers are also ignored in the 'similarity' check.
2363   bool hasSimilarType(QualType T1, QualType T2);
2364 
2365   /// Determine if two types are similar, ignoring only CVR qualifiers.
2366   bool hasCvrSimilarType(QualType T1, QualType T2);
2367 
2368   /// Retrieves the "canonical" nested name specifier for a
2369   /// given nested name specifier.
2370   ///
2371   /// The canonical nested name specifier is a nested name specifier
2372   /// that uniquely identifies a type or namespace within the type
2373   /// system. For example, given:
2374   ///
2375   /// \code
2376   /// namespace N {
2377   ///   struct S {
2378   ///     template<typename T> struct X { typename T* type; };
2379   ///   };
2380   /// }
2381   ///
2382   /// template<typename T> struct Y {
2383   ///   typename N::S::X<T>::type member;
2384   /// };
2385   /// \endcode
2386   ///
2387   /// Here, the nested-name-specifier for N::S::X<T>:: will be
2388   /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2389   /// by declarations in the type system and the canonical type for
2390   /// the template type parameter 'T' is template-param-0-0.
2391   NestedNameSpecifier *
2392   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2393 
2394   /// Retrieves the default calling convention for the current target.
2395   CallingConv getDefaultCallingConvention(bool IsVariadic,
2396                                           bool IsCXXMethod,
2397                                           bool IsBuiltin = false) const;
2398 
2399   /// Retrieves the "canonical" template name that refers to a
2400   /// given template.
2401   ///
2402   /// The canonical template name is the simplest expression that can
2403   /// be used to refer to a given template. For most templates, this
2404   /// expression is just the template declaration itself. For example,
2405   /// the template std::vector can be referred to via a variety of
2406   /// names---std::vector, \::std::vector, vector (if vector is in
2407   /// scope), etc.---but all of these names map down to the same
2408   /// TemplateDecl, which is used to form the canonical template name.
2409   ///
2410   /// Dependent template names are more interesting. Here, the
2411   /// template name could be something like T::template apply or
2412   /// std::allocator<T>::template rebind, where the nested name
2413   /// specifier itself is dependent. In this case, the canonical
2414   /// template name uses the shortest form of the dependent
2415   /// nested-name-specifier, which itself contains all canonical
2416   /// types, values, and templates.
2417   TemplateName getCanonicalTemplateName(TemplateName Name) const;
2418 
2419   /// Determine whether the given template names refer to the same
2420   /// template.
2421   bool hasSameTemplateName(TemplateName X, TemplateName Y);
2422 
2423   /// Retrieve the "canonical" template argument.
2424   ///
2425   /// The canonical template argument is the simplest template argument
2426   /// (which may be a type, value, expression, or declaration) that
2427   /// expresses the value of the argument.
2428   TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2429     const;
2430 
2431   /// Type Query functions.  If the type is an instance of the specified class,
2432   /// return the Type pointer for the underlying maximally pretty type.  This
2433   /// is a member of ASTContext because this may need to do some amount of
2434   /// canonicalization, e.g. to move type qualifiers into the element type.
2435   const ArrayType *getAsArrayType(QualType T) const;
2436   const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2437     return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2438   }
2439   const VariableArrayType *getAsVariableArrayType(QualType T) const {
2440     return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2441   }
2442   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2443     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2444   }
2445   const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2446     const {
2447     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2448   }
2449 
2450   /// Return the innermost element type of an array type.
2451   ///
2452   /// For example, will return "int" for int[m][n]
2453   QualType getBaseElementType(const ArrayType *VAT) const;
2454 
2455   /// Return the innermost element type of a type (which needn't
2456   /// actually be an array type).
2457   QualType getBaseElementType(QualType QT) const;
2458 
2459   /// Return number of constant array elements.
2460   uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2461 
2462   /// Perform adjustment on the parameter type of a function.
2463   ///
2464   /// This routine adjusts the given parameter type @p T to the actual
2465   /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2466   /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2467   QualType getAdjustedParameterType(QualType T) const;
2468 
2469   /// Retrieve the parameter type as adjusted for use in the signature
2470   /// of a function, decaying array and function types and removing top-level
2471   /// cv-qualifiers.
2472   QualType getSignatureParameterType(QualType T) const;
2473 
2474   QualType getExceptionObjectType(QualType T) const;
2475 
2476   /// Return the properly qualified result of decaying the specified
2477   /// array type to a pointer.
2478   ///
2479   /// This operation is non-trivial when handling typedefs etc.  The canonical
2480   /// type of \p T must be an array type, this returns a pointer to a properly
2481   /// qualified element of the array.
2482   ///
2483   /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2484   QualType getArrayDecayedType(QualType T) const;
2485 
2486   /// Return the type that \p PromotableType will promote to: C99
2487   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2488   QualType getPromotedIntegerType(QualType PromotableType) const;
2489 
2490   /// Recurses in pointer/array types until it finds an Objective-C
2491   /// retainable type and returns its ownership.
2492   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2493 
2494   /// Whether this is a promotable bitfield reference according
2495   /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2496   ///
2497   /// \returns the type this bit-field will promote to, or NULL if no
2498   /// promotion occurs.
2499   QualType isPromotableBitField(Expr *E) const;
2500 
2501   /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2502   ///
2503   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
2504   /// \p LHS < \p RHS, return -1.
2505   int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2506 
2507   /// Compare the rank of the two specified floating point types,
2508   /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2509   ///
2510   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
2511   /// \p LHS < \p RHS, return -1.
2512   int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2513 
2514   /// Compare the rank of two floating point types as above, but compare equal
2515   /// if both types have the same floating-point semantics on the target (i.e.
2516   /// long double and double on AArch64 will return 0).
2517   int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2518 
2519   /// Return a real floating point or a complex type (based on
2520   /// \p typeDomain/\p typeSize).
2521   ///
2522   /// \param typeDomain a real floating point or complex type.
2523   /// \param typeSize a real floating point or complex type.
2524   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2525                                              QualType typeDomain) const;
2526 
2527   unsigned getTargetAddressSpace(QualType T) const {
2528     return getTargetAddressSpace(T.getQualifiers());
2529   }
2530 
2531   unsigned getTargetAddressSpace(Qualifiers Q) const {
2532     return getTargetAddressSpace(Q.getAddressSpace());
2533   }
2534 
2535   unsigned getTargetAddressSpace(LangAS AS) const;
2536 
2537   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2538 
2539   /// Get target-dependent integer value for null pointer which is used for
2540   /// constant folding.
2541   uint64_t getTargetNullPointerValue(QualType QT) const;
2542 
2543   bool addressSpaceMapManglingFor(LangAS AS) const {
2544     return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2545   }
2546 
2547 private:
2548   // Helper for integer ordering
2549   unsigned getIntegerRank(const Type *T) const;
2550 
2551 public:
2552   //===--------------------------------------------------------------------===//
2553   //                    Type Compatibility Predicates
2554   //===--------------------------------------------------------------------===//
2555 
2556   /// Compatibility predicates used to check assignment expressions.
2557   bool typesAreCompatible(QualType T1, QualType T2,
2558                           bool CompareUnqualified = false); // C99 6.2.7p1
2559 
2560   bool propertyTypesAreCompatible(QualType, QualType);
2561   bool typesAreBlockPointerCompatible(QualType, QualType);
2562 
2563   bool isObjCIdType(QualType T) const {
2564     return T == getObjCIdType();
2565   }
2566 
2567   bool isObjCClassType(QualType T) const {
2568     return T == getObjCClassType();
2569   }
2570 
2571   bool isObjCSelType(QualType T) const {
2572     return T == getObjCSelType();
2573   }
2574 
2575   bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2576                                          const ObjCObjectPointerType *RHS,
2577                                          bool ForCompare);
2578 
2579   bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2580                                             const ObjCObjectPointerType *RHS);
2581 
2582   // Check the safety of assignment from LHS to RHS
2583   bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2584                                const ObjCObjectPointerType *RHSOPT);
2585   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2586                                const ObjCObjectType *RHS);
2587   bool canAssignObjCInterfacesInBlockPointer(
2588                                           const ObjCObjectPointerType *LHSOPT,
2589                                           const ObjCObjectPointerType *RHSOPT,
2590                                           bool BlockReturnType);
2591   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2592   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2593                                    const ObjCObjectPointerType *RHSOPT);
2594   bool canBindObjCObjectType(QualType To, QualType From);
2595 
2596   // Functions for calculating composite types
2597   QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2598                       bool Unqualified = false, bool BlockReturnType = false);
2599   QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2600                               bool Unqualified = false, bool AllowCXX = false);
2601   QualType mergeFunctionParameterTypes(QualType, QualType,
2602                                        bool OfBlockPointer = false,
2603                                        bool Unqualified = false);
2604   QualType mergeTransparentUnionType(QualType, QualType,
2605                                      bool OfBlockPointer=false,
2606                                      bool Unqualified = false);
2607 
2608   QualType mergeObjCGCQualifiers(QualType, QualType);
2609 
2610   /// This function merges the ExtParameterInfo lists of two functions. It
2611   /// returns true if the lists are compatible. The merged list is returned in
2612   /// NewParamInfos.
2613   ///
2614   /// \param FirstFnType The type of the first function.
2615   ///
2616   /// \param SecondFnType The type of the second function.
2617   ///
2618   /// \param CanUseFirst This flag is set to true if the first function's
2619   /// ExtParameterInfo list can be used as the composite list of
2620   /// ExtParameterInfo.
2621   ///
2622   /// \param CanUseSecond This flag is set to true if the second function's
2623   /// ExtParameterInfo list can be used as the composite list of
2624   /// ExtParameterInfo.
2625   ///
2626   /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2627   /// empty if none of the flags are set.
2628   ///
2629   bool mergeExtParameterInfo(
2630       const FunctionProtoType *FirstFnType,
2631       const FunctionProtoType *SecondFnType,
2632       bool &CanUseFirst, bool &CanUseSecond,
2633       SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2634 
2635   void ResetObjCLayout(const ObjCContainerDecl *CD);
2636 
2637   //===--------------------------------------------------------------------===//
2638   //                    Integer Predicates
2639   //===--------------------------------------------------------------------===//
2640 
2641   // The width of an integer, as defined in C99 6.2.6.2. This is the number
2642   // of bits in an integer type excluding any padding bits.
2643   unsigned getIntWidth(QualType T) const;
2644 
2645   // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2646   // unsigned integer type.  This method takes a signed type, and returns the
2647   // corresponding unsigned integer type.
2648   // With the introduction of fixed point types in ISO N1169, this method also
2649   // accepts fixed point types and returns the corresponding unsigned type for
2650   // a given fixed point type.
2651   QualType getCorrespondingUnsignedType(QualType T) const;
2652 
2653   // Per ISO N1169, this method accepts fixed point types and returns the
2654   // corresponding saturated type for a given fixed point type.
2655   QualType getCorrespondingSaturatedType(QualType Ty) const;
2656 
2657   // This method accepts fixed point types and returns the corresponding signed
2658   // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
2659   // fixed point types because there are unsigned integer types like bool and
2660   // char8_t that don't have signed equivalents.
2661   QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
2662 
2663   //===--------------------------------------------------------------------===//
2664   //                    Integer Values
2665   //===--------------------------------------------------------------------===//
2666 
2667   /// Make an APSInt of the appropriate width and signedness for the
2668   /// given \p Value and integer \p Type.
2669   llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2670     // If Type is a signed integer type larger than 64 bits, we need to be sure
2671     // to sign extend Res appropriately.
2672     llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2673     Res = Value;
2674     unsigned Width = getIntWidth(Type);
2675     if (Width != Res.getBitWidth())
2676       return Res.extOrTrunc(Width);
2677     return Res;
2678   }
2679 
2680   bool isSentinelNullExpr(const Expr *E);
2681 
2682   /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2683   /// none exists.
2684   ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2685 
2686   /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2687   /// none exists.
2688   ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2689 
2690   /// Return true if there is at least one \@implementation in the TU.
2691   bool AnyObjCImplementation() {
2692     return !ObjCImpls.empty();
2693   }
2694 
2695   /// Set the implementation of ObjCInterfaceDecl.
2696   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2697                              ObjCImplementationDecl *ImplD);
2698 
2699   /// Set the implementation of ObjCCategoryDecl.
2700   void setObjCImplementation(ObjCCategoryDecl *CatD,
2701                              ObjCCategoryImplDecl *ImplD);
2702 
2703   /// Get the duplicate declaration of a ObjCMethod in the same
2704   /// interface, or null if none exists.
2705   const ObjCMethodDecl *
2706   getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2707 
2708   void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2709                                   const ObjCMethodDecl *Redecl);
2710 
2711   /// Returns the Objective-C interface that \p ND belongs to if it is
2712   /// an Objective-C method/property/ivar etc. that is part of an interface,
2713   /// otherwise returns null.
2714   const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2715 
2716   /// Set the copy initialization expression of a block var decl. \p CanThrow
2717   /// indicates whether the copy expression can throw or not.
2718   void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2719 
2720   /// Get the copy initialization expression of the VarDecl \p VD, or
2721   /// nullptr if none exists.
2722   BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2723 
2724   /// Allocate an uninitialized TypeSourceInfo.
2725   ///
2726   /// The caller should initialize the memory held by TypeSourceInfo using
2727   /// the TypeLoc wrappers.
2728   ///
2729   /// \param T the type that will be the basis for type source info. This type
2730   /// should refer to how the declarator was written in source code, not to
2731   /// what type semantic analysis resolved the declarator to.
2732   ///
2733   /// \param Size the size of the type info to create, or 0 if the size
2734   /// should be calculated based on the type.
2735   TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2736 
2737   /// Allocate a TypeSourceInfo where all locations have been
2738   /// initialized to a given location, which defaults to the empty
2739   /// location.
2740   TypeSourceInfo *
2741   getTrivialTypeSourceInfo(QualType T,
2742                            SourceLocation Loc = SourceLocation()) const;
2743 
2744   /// Add a deallocation callback that will be invoked when the
2745   /// ASTContext is destroyed.
2746   ///
2747   /// \param Callback A callback function that will be invoked on destruction.
2748   ///
2749   /// \param Data Pointer data that will be provided to the callback function
2750   /// when it is called.
2751   void AddDeallocation(void (*Callback)(void *), void *Data) const;
2752 
2753   /// If T isn't trivially destructible, calls AddDeallocation to register it
2754   /// for destruction.
2755   template <typename T> void addDestruction(T *Ptr) const {
2756     if (!std::is_trivially_destructible<T>::value) {
2757       auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2758       AddDeallocation(DestroyPtr, Ptr);
2759     }
2760   }
2761 
2762   GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2763   GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2764 
2765   /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2766   /// lazily, only when used; this is only relevant for function or file scoped
2767   /// var definitions.
2768   ///
2769   /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2770   /// it is not used.
2771   bool DeclMustBeEmitted(const Decl *D);
2772 
2773   /// Visits all versions of a multiversioned function with the passed
2774   /// predicate.
2775   void forEachMultiversionedFunctionVersion(
2776       const FunctionDecl *FD,
2777       llvm::function_ref<void(FunctionDecl *)> Pred) const;
2778 
2779   const CXXConstructorDecl *
2780   getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2781 
2782   void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2783                                             CXXConstructorDecl *CD);
2784 
2785   void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2786 
2787   TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2788 
2789   void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2790 
2791   DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2792 
2793   void setManglingNumber(const NamedDecl *ND, unsigned Number);
2794   unsigned getManglingNumber(const NamedDecl *ND) const;
2795 
2796   void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2797   unsigned getStaticLocalNumber(const VarDecl *VD) const;
2798 
2799   /// Retrieve the context for computing mangling numbers in the given
2800   /// DeclContext.
2801   MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2802   enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
2803   MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
2804                                                    const Decl *D);
2805 
2806   std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2807 
2808   /// Used by ParmVarDecl to store on the side the
2809   /// index of the parameter when it exceeds the size of the normal bitfield.
2810   void setParameterIndex(const ParmVarDecl *D, unsigned index);
2811 
2812   /// Used by ParmVarDecl to retrieve on the side the
2813   /// index of the parameter when it exceeds the size of the normal bitfield.
2814   unsigned getParameterIndex(const ParmVarDecl *D) const;
2815 
2816   /// Return a string representing the human readable name for the specified
2817   /// function declaration or file name. Used by SourceLocExpr and
2818   /// PredefinedExpr to cache evaluated results.
2819   StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
2820 
2821   /// Return a declaration for the global GUID object representing the given
2822   /// GUID value.
2823   MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
2824 
2825   /// Parses the target attributes passed in, and returns only the ones that are
2826   /// valid feature names.
2827   ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
2828 
2829   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2830                              const FunctionDecl *) const;
2831   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2832                              GlobalDecl GD) const;
2833 
2834   //===--------------------------------------------------------------------===//
2835   //                    Statistics
2836   //===--------------------------------------------------------------------===//
2837 
2838   /// The number of implicitly-declared default constructors.
2839   unsigned NumImplicitDefaultConstructors = 0;
2840 
2841   /// The number of implicitly-declared default constructors for
2842   /// which declarations were built.
2843   unsigned NumImplicitDefaultConstructorsDeclared = 0;
2844 
2845   /// The number of implicitly-declared copy constructors.
2846   unsigned NumImplicitCopyConstructors = 0;
2847 
2848   /// The number of implicitly-declared copy constructors for
2849   /// which declarations were built.
2850   unsigned NumImplicitCopyConstructorsDeclared = 0;
2851 
2852   /// The number of implicitly-declared move constructors.
2853   unsigned NumImplicitMoveConstructors = 0;
2854 
2855   /// The number of implicitly-declared move constructors for
2856   /// which declarations were built.
2857   unsigned NumImplicitMoveConstructorsDeclared = 0;
2858 
2859   /// The number of implicitly-declared copy assignment operators.
2860   unsigned NumImplicitCopyAssignmentOperators = 0;
2861 
2862   /// The number of implicitly-declared copy assignment operators for
2863   /// which declarations were built.
2864   unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
2865 
2866   /// The number of implicitly-declared move assignment operators.
2867   unsigned NumImplicitMoveAssignmentOperators = 0;
2868 
2869   /// The number of implicitly-declared move assignment operators for
2870   /// which declarations were built.
2871   unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
2872 
2873   /// The number of implicitly-declared destructors.
2874   unsigned NumImplicitDestructors = 0;
2875 
2876   /// The number of implicitly-declared destructors for which
2877   /// declarations were built.
2878   unsigned NumImplicitDestructorsDeclared = 0;
2879 
2880 public:
2881   /// Initialize built-in types.
2882   ///
2883   /// This routine may only be invoked once for a given ASTContext object.
2884   /// It is normally invoked after ASTContext construction.
2885   ///
2886   /// \param Target The target
2887   void InitBuiltinTypes(const TargetInfo &Target,
2888                         const TargetInfo *AuxTarget = nullptr);
2889 
2890 private:
2891   void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2892 
2893   class ObjCEncOptions {
2894     unsigned Bits;
2895 
2896     ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
2897 
2898   public:
2899     ObjCEncOptions() : Bits(0) {}
2900     ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
2901 
2902 #define OPT_LIST(V)                                                            \
2903   V(ExpandPointedToStructures, 0)                                              \
2904   V(ExpandStructures, 1)                                                       \
2905   V(IsOutermostType, 2)                                                        \
2906   V(EncodingProperty, 3)                                                       \
2907   V(IsStructField, 4)                                                          \
2908   V(EncodeBlockParameters, 5)                                                  \
2909   V(EncodeClassNames, 6)                                                       \
2910 
2911 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
2912 OPT_LIST(V)
2913 #undef V
2914 
2915 #define V(N,I) bool N() const { return Bits & 1 << I; }
2916 OPT_LIST(V)
2917 #undef V
2918 
2919 #undef OPT_LIST
2920 
2921     LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
2922       return Bits & Mask.Bits;
2923     }
2924 
2925     LLVM_NODISCARD ObjCEncOptions forComponentType() const {
2926       ObjCEncOptions Mask = ObjCEncOptions()
2927                                 .setIsOutermostType()
2928                                 .setIsStructField();
2929       return Bits & ~Mask.Bits;
2930     }
2931   };
2932 
2933   // Return the Objective-C type encoding for a given type.
2934   void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2935                                   ObjCEncOptions Options,
2936                                   const FieldDecl *Field,
2937                                   QualType *NotEncodedT = nullptr) const;
2938 
2939   // Adds the encoding of the structure's members.
2940   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2941                                        const FieldDecl *Field,
2942                                        bool includeVBases = true,
2943                                        QualType *NotEncodedT=nullptr) const;
2944 
2945 public:
2946   // Adds the encoding of a method parameter or return type.
2947   void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2948                                          QualType T, std::string& S,
2949                                          bool Extended) const;
2950 
2951   /// Returns true if this is an inline-initialized static data member
2952   /// which is treated as a definition for MSVC compatibility.
2953   bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2954 
2955   enum class InlineVariableDefinitionKind {
2956     /// Not an inline variable.
2957     None,
2958 
2959     /// Weak definition of inline variable.
2960     Weak,
2961 
2962     /// Weak for now, might become strong later in this TU.
2963     WeakUnknown,
2964 
2965     /// Strong definition.
2966     Strong
2967   };
2968 
2969   /// Determine whether a definition of this inline variable should
2970   /// be treated as a weak or strong definition. For compatibility with
2971   /// C++14 and before, for a constexpr static data member, if there is an
2972   /// out-of-line declaration of the member, we may promote it from weak to
2973   /// strong.
2974   InlineVariableDefinitionKind
2975   getInlineVariableDefinitionKind(const VarDecl *VD) const;
2976 
2977 private:
2978   friend class DeclarationNameTable;
2979   friend class DeclContext;
2980 
2981   const ASTRecordLayout &
2982   getObjCLayout(const ObjCInterfaceDecl *D,
2983                 const ObjCImplementationDecl *Impl) const;
2984 
2985   /// A set of deallocations that should be performed when the
2986   /// ASTContext is destroyed.
2987   // FIXME: We really should have a better mechanism in the ASTContext to
2988   // manage running destructors for types which do variable sized allocation
2989   // within the AST. In some places we thread the AST bump pointer allocator
2990   // into the datastructures which avoids this mess during deallocation but is
2991   // wasteful of memory, and here we require a lot of error prone book keeping
2992   // in order to track and run destructors while we're tearing things down.
2993   using DeallocationFunctionsAndArguments =
2994       llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2995   mutable DeallocationFunctionsAndArguments Deallocations;
2996 
2997   // FIXME: This currently contains the set of StoredDeclMaps used
2998   // by DeclContext objects.  This probably should not be in ASTContext,
2999   // but we include it here so that ASTContext can quickly deallocate them.
3000   llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3001 
3002   std::vector<Decl *> TraversalScope;
3003 
3004   std::unique_ptr<VTableContextBase> VTContext;
3005 
3006   void ReleaseDeclContextMaps();
3007 
3008 public:
3009   enum PragmaSectionFlag : unsigned {
3010     PSF_None = 0,
3011     PSF_Read = 0x1,
3012     PSF_Write = 0x2,
3013     PSF_Execute = 0x4,
3014     PSF_Implicit = 0x8,
3015     PSF_ZeroInit = 0x10,
3016     PSF_Invalid = 0x80000000U,
3017   };
3018 
3019   struct SectionInfo {
3020     DeclaratorDecl *Decl;
3021     SourceLocation PragmaSectionLocation;
3022     int SectionFlags;
3023 
3024     SectionInfo() = default;
3025     SectionInfo(DeclaratorDecl *Decl,
3026                 SourceLocation PragmaSectionLocation,
3027                 int SectionFlags)
3028         : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3029           SectionFlags(SectionFlags) {}
3030   };
3031 
3032   llvm::StringMap<SectionInfo> SectionInfos;
3033 
3034   /// Return a new OMPTraitInfo object owned by this context.
3035   OMPTraitInfo &getNewOMPTraitInfo();
3036 
3037 private:
3038   /// All OMPTraitInfo objects live in this collection, one per
3039   /// `pragma omp [begin] declare variant` directive.
3040   SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3041 };
3042 
3043 /// Insertion operator for diagnostics.
3044 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3045                                     const ASTContext::SectionInfo &Section);
3046 
3047 /// Utility function for constructing a nullary selector.
3048 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3049   IdentifierInfo* II = &Ctx.Idents.get(name);
3050   return Ctx.Selectors.getSelector(0, &II);
3051 }
3052 
3053 /// Utility function for constructing an unary selector.
3054 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3055   IdentifierInfo* II = &Ctx.Idents.get(name);
3056   return Ctx.Selectors.getSelector(1, &II);
3057 }
3058 
3059 } // namespace clang
3060 
3061 // operator new and delete aren't allowed inside namespaces.
3062 
3063 /// Placement new for using the ASTContext's allocator.
3064 ///
3065 /// This placement form of operator new uses the ASTContext's allocator for
3066 /// obtaining memory.
3067 ///
3068 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3069 /// Any changes here need to also be made there.
3070 ///
3071 /// We intentionally avoid using a nothrow specification here so that the calls
3072 /// to this operator will not perform a null check on the result -- the
3073 /// underlying allocator never returns null pointers.
3074 ///
3075 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3076 /// @code
3077 /// // Default alignment (8)
3078 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3079 /// // Specific alignment
3080 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3081 /// @endcode
3082 /// Memory allocated through this placement new operator does not need to be
3083 /// explicitly freed, as ASTContext will free all of this memory when it gets
3084 /// destroyed. Please note that you cannot use delete on the pointer.
3085 ///
3086 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3087 /// @param C The ASTContext that provides the allocator.
3088 /// @param Alignment The alignment of the allocated memory (if the underlying
3089 ///                  allocator supports it).
3090 /// @return The allocated memory. Could be nullptr.
3091 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3092                           size_t Alignment /* = 8 */) {
3093   return C.Allocate(Bytes, Alignment);
3094 }
3095 
3096 /// Placement delete companion to the new above.
3097 ///
3098 /// This operator is just a companion to the new above. There is no way of
3099 /// invoking it directly; see the new operator for more details. This operator
3100 /// is called implicitly by the compiler if a placement new expression using
3101 /// the ASTContext throws in the object constructor.
3102 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3103   C.Deallocate(Ptr);
3104 }
3105 
3106 /// This placement form of operator new[] uses the ASTContext's allocator for
3107 /// obtaining memory.
3108 ///
3109 /// We intentionally avoid using a nothrow specification here so that the calls
3110 /// to this operator will not perform a null check on the result -- the
3111 /// underlying allocator never returns null pointers.
3112 ///
3113 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3114 /// @code
3115 /// // Default alignment (8)
3116 /// char *data = new (Context) char[10];
3117 /// // Specific alignment
3118 /// char *data = new (Context, 4) char[10];
3119 /// @endcode
3120 /// Memory allocated through this placement new[] operator does not need to be
3121 /// explicitly freed, as ASTContext will free all of this memory when it gets
3122 /// destroyed. Please note that you cannot use delete on the pointer.
3123 ///
3124 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3125 /// @param C The ASTContext that provides the allocator.
3126 /// @param Alignment The alignment of the allocated memory (if the underlying
3127 ///                  allocator supports it).
3128 /// @return The allocated memory. Could be nullptr.
3129 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3130                             size_t Alignment /* = 8 */) {
3131   return C.Allocate(Bytes, Alignment);
3132 }
3133 
3134 /// Placement delete[] companion to the new[] above.
3135 ///
3136 /// This operator is just a companion to the new[] above. There is no way of
3137 /// invoking it directly; see the new[] operator for more details. This operator
3138 /// is called implicitly by the compiler if a placement new[] expression using
3139 /// the ASTContext throws in the object constructor.
3140 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3141   C.Deallocate(Ptr);
3142 }
3143 
3144 /// Create the representation of a LazyGenerationalUpdatePtr.
3145 template <typename Owner, typename T,
3146           void (clang::ExternalASTSource::*Update)(Owner)>
3147 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3148     clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3149         const clang::ASTContext &Ctx, T Value) {
3150   // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3151   // include ASTContext.h. We explicitly instantiate it for all relevant types
3152   // in ASTContext.cpp.
3153   if (auto *Source = Ctx.getExternalSource())
3154     return new (Ctx) LazyData(Source, Value);
3155   return Value;
3156 }
3157 
3158 #endif // LLVM_CLANG_AST_ASTCONTEXT_H
3159