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