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