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