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