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