ASTContext.h revision da8962a6198bc4bf09a38209db99551b2b0a41a0
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//  This file defines the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/Basic/AddressSpaces.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/OperatorKinds.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/VersionTuple.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/PrettyPrinter.h"
26#include "clang/AST/TemplateName.h"
27#include "clang/AST/Type.h"
28#include "clang/AST/CanonicalType.h"
29#include "clang/AST/UsuallyTinyPtrVector.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/IntrusiveRefCntPtr.h"
33#include "llvm/ADT/OwningPtr.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/Support/Allocator.h"
36#include <vector>
37
38namespace llvm {
39  struct fltSemantics;
40}
41
42namespace clang {
43  class FileManager;
44  class ASTRecordLayout;
45  class BlockExpr;
46  class CharUnits;
47  class DiagnosticsEngine;
48  class Expr;
49  class ExternalASTSource;
50  class ASTMutationListener;
51  class IdentifierTable;
52  class SelectorTable;
53  class SourceManager;
54  class TargetInfo;
55  class CXXABI;
56  // Decls
57  class DeclContext;
58  class CXXMethodDecl;
59  class CXXRecordDecl;
60  class Decl;
61  class FieldDecl;
62  class MangleContext;
63  class ObjCIvarDecl;
64  class ObjCIvarRefExpr;
65  class ObjCPropertyDecl;
66  class ParmVarDecl;
67  class RecordDecl;
68  class StoredDeclsMap;
69  class TagDecl;
70  class TemplateTemplateParmDecl;
71  class TemplateTypeParmDecl;
72  class TranslationUnitDecl;
73  class TypeDecl;
74  class TypedefNameDecl;
75  class UsingDecl;
76  class UsingShadowDecl;
77  class UnresolvedSetIterator;
78
79  namespace Builtin { class Context; }
80
81/// ASTContext - This class holds long-lived AST nodes (such as types and
82/// decls) that can be referred to throughout the semantic analysis of a file.
83class ASTContext : public llvm::RefCountedBase<ASTContext> {
84  ASTContext &this_() { return *this; }
85
86  mutable std::vector<Type*> Types;
87  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
88  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
89  mutable llvm::FoldingSet<PointerType> PointerTypes;
90  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
91  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
92  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
93  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
94  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
95  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
96  mutable std::vector<VariableArrayType*> VariableArrayTypes;
97  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
98  mutable llvm::FoldingSet<DependentSizedExtVectorType>
99    DependentSizedExtVectorTypes;
100  mutable llvm::FoldingSet<VectorType> VectorTypes;
101  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
102  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
103    FunctionProtoTypes;
104  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
105  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
106  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
107  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
108    SubstTemplateTypeParmTypes;
109  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
110    SubstTemplateTypeParmPackTypes;
111  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
112    TemplateSpecializationTypes;
113  mutable llvm::FoldingSet<ParenType> ParenTypes;
114  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
115  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
116  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
117                                     ASTContext&>
118    DependentTemplateSpecializationTypes;
119  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
120  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
121  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
122  mutable llvm::FoldingSet<AutoType> AutoTypes;
123  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
124  llvm::FoldingSet<AttributedType> AttributedTypes;
125
126  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
127  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
128  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
129    SubstTemplateTemplateParms;
130  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
131                                     ASTContext&>
132    SubstTemplateTemplateParmPacks;
133
134  /// \brief The set of nested name specifiers.
135  ///
136  /// This set is managed by the NestedNameSpecifier class.
137  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
138  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
139  friend class NestedNameSpecifier;
140
141  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
142  ///  This is lazily created.  This is intentionally not serialized.
143  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
144    ASTRecordLayouts;
145  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
146    ObjCLayouts;
147
148  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
149  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
150
151  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
152  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
153
154  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
155  /// interface.
156  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
157
158  /// \brief Mapping from __block VarDecls to their copy initialization expr.
159  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
160
161  /// \brief Mapping from class scope functions specialization to their
162  ///  template patterns.
163  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
164    ClassScopeSpecializationPattern;
165
166  /// \brief Representation of a "canonical" template template parameter that
167  /// is used in canonical template names.
168  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
169    TemplateTemplateParmDecl *Parm;
170
171  public:
172    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
173      : Parm(Parm) { }
174
175    TemplateTemplateParmDecl *getParam() const { return Parm; }
176
177    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
178
179    static void Profile(llvm::FoldingSetNodeID &ID,
180                        TemplateTemplateParmDecl *Parm);
181  };
182  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
183    CanonTemplateTemplateParms;
184
185  TemplateTemplateParmDecl *
186    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
187
188  /// \brief The typedef for the __int128_t type.
189  mutable TypedefDecl *Int128Decl;
190
191  /// \brief The typedef for the __uint128_t type.
192  mutable TypedefDecl *UInt128Decl;
193
194  /// BuiltinVaListType - built-in va list type.
195  /// This is initially null and set by Sema::LazilyCreateBuiltin when
196  /// a builtin that takes a valist is encountered.
197  QualType BuiltinVaListType;
198
199  /// \brief The typedef for the predefined 'id' type.
200  mutable TypedefDecl *ObjCIdDecl;
201
202  /// \brief The typedef for the predefined 'SEL' type.
203  mutable TypedefDecl *ObjCSelDecl;
204
205  /// \brief The typedef for the predefined 'Class' type.
206  mutable TypedefDecl *ObjCClassDecl;
207
208  /// \brief The typedef for the predefined 'Protocol' class in Objective-C.
209  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
210
211  // Typedefs which may be provided defining the structure of Objective-C
212  // pseudo-builtins
213  QualType ObjCIdRedefinitionType;
214  QualType ObjCClassRedefinitionType;
215  QualType ObjCSelRedefinitionType;
216
217  QualType ObjCConstantStringType;
218  mutable RecordDecl *CFConstantStringTypeDecl;
219
220  /// \brief The typedef declaration for the Objective-C "instancetype" type.
221  TypedefDecl *ObjCInstanceTypeDecl;
222
223  /// \brief The type for the C FILE type.
224  TypeDecl *FILEDecl;
225
226  /// \brief The type for the C jmp_buf type.
227  TypeDecl *jmp_bufDecl;
228
229  /// \brief The type for the C sigjmp_buf type.
230  TypeDecl *sigjmp_bufDecl;
231
232  /// \brief The type for the C ucontext_t type.
233  TypeDecl *ucontext_tDecl;
234
235  /// \brief Type for the Block descriptor for Blocks CodeGen.
236  ///
237  /// Since this is only used for generation of debug info, it is not
238  /// serialized.
239  mutable RecordDecl *BlockDescriptorType;
240
241  /// \brief Type for the Block descriptor for Blocks CodeGen.
242  ///
243  /// Since this is only used for generation of debug info, it is not
244  /// serialized.
245  mutable RecordDecl *BlockDescriptorExtendedType;
246
247  /// \brief Declaration for the CUDA cudaConfigureCall function.
248  FunctionDecl *cudaConfigureCallDecl;
249
250  TypeSourceInfo NullTypeSourceInfo;
251
252  /// \brief Keeps track of all declaration attributes.
253  ///
254  /// Since so few decls have attrs, we keep them in a hash map instead of
255  /// wasting space in the Decl class.
256  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
257
258  /// \brief Keeps track of the static data member templates from which
259  /// static data members of class template specializations were instantiated.
260  ///
261  /// This data structure stores the mapping from instantiations of static
262  /// data members to the static data member representations within the
263  /// class template from which they were instantiated along with the kind
264  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
265  ///
266  /// Given the following example:
267  ///
268  /// \code
269  /// template<typename T>
270  /// struct X {
271  ///   static T value;
272  /// };
273  ///
274  /// template<typename T>
275  ///   T X<T>::value = T(17);
276  ///
277  /// int *x = &X<int>::value;
278  /// \endcode
279  ///
280  /// This mapping will contain an entry that maps from the VarDecl for
281  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
282  /// class template X) and will be marked TSK_ImplicitInstantiation.
283  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
284    InstantiatedFromStaticDataMember;
285
286  /// \brief Keeps track of the declaration from which a UsingDecl was
287  /// created during instantiation.  The source declaration is always
288  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
289  /// UnresolvedUsingTypenameDecl.
290  ///
291  /// For example:
292  /// \code
293  /// template<typename T>
294  /// struct A {
295  ///   void f();
296  /// };
297  ///
298  /// template<typename T>
299  /// struct B : A<T> {
300  ///   using A<T>::f;
301  /// };
302  ///
303  /// template struct B<int>;
304  /// \endcode
305  ///
306  /// This mapping will contain an entry that maps from the UsingDecl in
307  /// B<int> to the UnresolvedUsingDecl in B<T>.
308  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
309
310  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
311    InstantiatedFromUsingShadowDecl;
312
313  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
314
315  /// \brief Mapping that stores the methods overridden by a given C++
316  /// member function.
317  ///
318  /// Since most C++ member functions aren't virtual and therefore
319  /// don't override anything, we store the overridden functions in
320  /// this map on the side rather than within the CXXMethodDecl structure.
321  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
322  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
323
324  /// \brief Mapping that stores parameterIndex values for ParmVarDecls
325  /// when that value exceeds the bitfield size of
326  /// ParmVarDeclBits.ParameterIndex.
327  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
328  ParameterIndexTable ParamIndices;
329
330  ImportDecl *FirstLocalImport;
331  ImportDecl *LastLocalImport;
332
333  TranslationUnitDecl *TUDecl;
334
335  /// SourceMgr - The associated SourceManager object.
336  SourceManager &SourceMgr;
337
338  /// LangOpts - The language options used to create the AST associated with
339  ///  this ASTContext object.
340  LangOptions &LangOpts;
341
342  /// \brief The allocator used to create AST objects.
343  ///
344  /// AST objects are never destructed; rather, all memory associated with the
345  /// AST objects will be released when the ASTContext itself is destroyed.
346  mutable llvm::BumpPtrAllocator BumpAlloc;
347
348  /// \brief Allocator for partial diagnostics.
349  PartialDiagnostic::StorageAllocator DiagAllocator;
350
351  /// \brief The current C++ ABI.
352  OwningPtr<CXXABI> ABI;
353  CXXABI *createCXXABI(const TargetInfo &T);
354
355  /// \brief The logical -> physical address space map.
356  const LangAS::Map *AddrSpaceMap;
357
358  friend class ASTDeclReader;
359  friend class ASTReader;
360  friend class ASTWriter;
361  friend class CXXRecordDecl;
362
363  const TargetInfo *Target;
364  clang::PrintingPolicy PrintingPolicy;
365
366public:
367  IdentifierTable &Idents;
368  SelectorTable &Selectors;
369  Builtin::Context &BuiltinInfo;
370  mutable DeclarationNameTable DeclarationNames;
371  OwningPtr<ExternalASTSource> ExternalSource;
372  ASTMutationListener *Listener;
373
374  clang::PrintingPolicy getPrintingPolicy() const { return PrintingPolicy; }
375
376  void setPrintingPolicy(clang::PrintingPolicy Policy) {
377    PrintingPolicy = Policy;
378  }
379
380  SourceManager& getSourceManager() { return SourceMgr; }
381  const SourceManager& getSourceManager() const { return SourceMgr; }
382  void *Allocate(unsigned Size, unsigned Align = 8) const {
383    return BumpAlloc.Allocate(Size, Align);
384  }
385  void Deallocate(void *Ptr) const { }
386
387  /// Return the total amount of physical memory allocated for representing
388  /// AST nodes and type information.
389  size_t getASTAllocatedMemory() const {
390    return BumpAlloc.getTotalMemory();
391  }
392  /// Return the total memory used for various side tables.
393  size_t getSideTableAllocatedMemory() const;
394
395  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
396    return DiagAllocator;
397  }
398
399  const TargetInfo &getTargetInfo() const { return *Target; }
400
401  const LangOptions& getLangOptions() const { return LangOpts; }
402
403  DiagnosticsEngine &getDiagnostics() const;
404
405  FullSourceLoc getFullLoc(SourceLocation Loc) const {
406    return FullSourceLoc(Loc,SourceMgr);
407  }
408
409  /// \brief Retrieve the attributes for the given declaration.
410  AttrVec& getDeclAttrs(const Decl *D);
411
412  /// \brief Erase the attributes corresponding to the given declaration.
413  void eraseDeclAttrs(const Decl *D);
414
415  /// \brief If this variable is an instantiated static data member of a
416  /// class template specialization, returns the templated static data member
417  /// from which it was instantiated.
418  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
419                                                           const VarDecl *Var);
420
421  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
422
423  void setClassScopeSpecializationPattern(FunctionDecl *FD,
424                                          FunctionDecl *Pattern);
425
426  /// \brief Note that the static data member \p Inst is an instantiation of
427  /// the static data member template \p Tmpl of a class template.
428  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
429                                           TemplateSpecializationKind TSK,
430                        SourceLocation PointOfInstantiation = SourceLocation());
431
432  /// \brief If the given using decl is an instantiation of a
433  /// (possibly unresolved) using decl from a template instantiation,
434  /// return it.
435  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
436
437  /// \brief Remember that the using decl \p Inst is an instantiation
438  /// of the using decl \p Pattern of a class template.
439  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
440
441  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
442                                          UsingShadowDecl *Pattern);
443  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
444
445  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
446
447  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
448
449  /// ZeroBitfieldFollowsNonBitfield - return 'true" if 'FD' is a zero-length
450  /// bitfield which follows the non-bitfield 'LastFD'.
451  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
452                                      const FieldDecl *LastFD) const;
453
454  /// ZeroBitfieldFollowsBitfield - return 'true" if 'FD' is a zero-length
455  /// bitfield which follows the bitfield 'LastFD'.
456  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
457                                   const FieldDecl *LastFD) const;
458
459  /// BitfieldFollowsBitfield - return 'true" if 'FD' is a
460  /// bitfield which follows the bitfield 'LastFD'.
461  bool BitfieldFollowsBitfield(const FieldDecl *FD,
462                               const FieldDecl *LastFD) const;
463
464  /// NonBitfieldFollowsBitfield - return 'true" if 'FD' is not a
465  /// bitfield which follows the bitfield 'LastFD'.
466  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
467                                  const FieldDecl *LastFD) const;
468
469  /// BitfieldFollowsNonBitfield - return 'true" if 'FD' is a
470  /// bitfield which follows the none bitfield 'LastFD'.
471  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
472                                  const FieldDecl *LastFD) const;
473
474  // Access to the set of methods overridden by the given C++ method.
475  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
476  overridden_cxx_method_iterator
477  overridden_methods_begin(const CXXMethodDecl *Method) const;
478
479  overridden_cxx_method_iterator
480  overridden_methods_end(const CXXMethodDecl *Method) const;
481
482  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
483
484  /// \brief Note that the given C++ \p Method overrides the given \p
485  /// Overridden method.
486  void addOverriddenMethod(const CXXMethodDecl *Method,
487                           const CXXMethodDecl *Overridden);
488
489  /// \brief Notify the AST context that a new import declaration has been
490  /// parsed or implicitly created within this translation unit.
491  void addedLocalImportDecl(ImportDecl *Import);
492
493  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
494    return Import->NextLocalImport;
495  }
496
497  /// \brief Iterator that visits import declarations.
498  class import_iterator {
499    ImportDecl *Import;
500
501  public:
502    typedef ImportDecl               *value_type;
503    typedef ImportDecl               *reference;
504    typedef ImportDecl               *pointer;
505    typedef int                       difference_type;
506    typedef std::forward_iterator_tag iterator_category;
507
508    import_iterator() : Import() { }
509    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
510
511    reference operator*() const { return Import; }
512    pointer operator->() const { return Import; }
513
514    import_iterator &operator++() {
515      Import = ASTContext::getNextLocalImport(Import);
516      return *this;
517    }
518
519    import_iterator operator++(int) {
520      import_iterator Other(*this);
521      ++(*this);
522      return Other;
523    }
524
525    friend bool operator==(import_iterator X, import_iterator Y) {
526      return X.Import == Y.Import;
527    }
528
529    friend bool operator!=(import_iterator X, import_iterator Y) {
530      return X.Import != Y.Import;
531    }
532  };
533
534  import_iterator local_import_begin() const {
535    return import_iterator(FirstLocalImport);
536  }
537  import_iterator local_import_end() const { return import_iterator(); }
538
539  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
540
541
542  // Builtin Types.
543  CanQualType VoidTy;
544  CanQualType BoolTy;
545  CanQualType CharTy;
546  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
547  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
548  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
549  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
550  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
551  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
552  CanQualType FloatTy, DoubleTy, LongDoubleTy;
553  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
554  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
555  CanQualType VoidPtrTy, NullPtrTy;
556  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
557  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
558  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
559
560  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
561  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
562  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
563
564  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
565             IdentifierTable &idents, SelectorTable &sels,
566             Builtin::Context &builtins,
567             unsigned size_reserve,
568             bool DelayInitialization = false);
569
570  ~ASTContext();
571
572  /// \brief Attach an external AST source to the AST context.
573  ///
574  /// The external AST source provides the ability to load parts of
575  /// the abstract syntax tree as needed from some external storage,
576  /// e.g., a precompiled header.
577  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
578
579  /// \brief Retrieve a pointer to the external AST source associated
580  /// with this AST context, if any.
581  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
582
583  /// \brief Attach an AST mutation listener to the AST context.
584  ///
585  /// The AST mutation listener provides the ability to track modifications to
586  /// the abstract syntax tree entities committed after they were initially
587  /// created.
588  void setASTMutationListener(ASTMutationListener *Listener) {
589    this->Listener = Listener;
590  }
591
592  /// \brief Retrieve a pointer to the AST mutation listener associated
593  /// with this AST context, if any.
594  ASTMutationListener *getASTMutationListener() const { return Listener; }
595
596  void PrintStats() const;
597  const std::vector<Type*>& getTypes() const { return Types; }
598
599  /// \brief Retrieve the declaration for the 128-bit signed integer type.
600  TypedefDecl *getInt128Decl() const;
601
602  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
603  TypedefDecl *getUInt128Decl() const;
604
605  //===--------------------------------------------------------------------===//
606  //                           Type Constructors
607  //===--------------------------------------------------------------------===//
608
609private:
610  /// getExtQualType - Return a type with extended qualifiers.
611  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
612
613  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
614
615public:
616  /// getAddSpaceQualType - Return the uniqued reference to the type for an
617  /// address space qualified type with the specified type and address space.
618  /// The resulting type has a union of the qualifiers from T and the address
619  /// space. If T already has an address space specifier, it is silently
620  /// replaced.
621  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
622
623  /// getObjCGCQualType - Returns the uniqued reference to the type for an
624  /// objc gc qualified type. The retulting type has a union of the qualifiers
625  /// from T and the gc attribute.
626  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
627
628  /// getRestrictType - Returns the uniqued reference to the type for a
629  /// 'restrict' qualified type.  The resulting type has a union of the
630  /// qualifiers from T and 'restrict'.
631  QualType getRestrictType(QualType T) const {
632    return T.withFastQualifiers(Qualifiers::Restrict);
633  }
634
635  /// getVolatileType - Returns the uniqued reference to the type for a
636  /// 'volatile' qualified type.  The resulting type has a union of the
637  /// qualifiers from T and 'volatile'.
638  QualType getVolatileType(QualType T) const {
639    return T.withFastQualifiers(Qualifiers::Volatile);
640  }
641
642  /// getConstType - Returns the uniqued reference to the type for a
643  /// 'const' qualified type.  The resulting type has a union of the
644  /// qualifiers from T and 'const'.
645  ///
646  /// It can be reasonably expected that this will always be
647  /// equivalent to calling T.withConst().
648  QualType getConstType(QualType T) const { return T.withConst(); }
649
650  /// adjustFunctionType - Change the ExtInfo on a function type.
651  const FunctionType *adjustFunctionType(const FunctionType *Fn,
652                                         FunctionType::ExtInfo EInfo);
653
654  /// getComplexType - Return the uniqued reference to the type for a complex
655  /// number with the specified element type.
656  QualType getComplexType(QualType T) const;
657  CanQualType getComplexType(CanQualType T) const {
658    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
659  }
660
661  /// getPointerType - Return the uniqued reference to the type for a pointer to
662  /// the specified type.
663  QualType getPointerType(QualType T) const;
664  CanQualType getPointerType(CanQualType T) const {
665    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
666  }
667
668  /// getAtomicType - Return the uniqued reference to the atomic type for
669  /// the specified type.
670  QualType getAtomicType(QualType T) const;
671
672  /// getBlockPointerType - Return the uniqued reference to the type for a block
673  /// of the specified type.
674  QualType getBlockPointerType(QualType T) const;
675
676  /// This gets the struct used to keep track of the descriptor for pointer to
677  /// blocks.
678  QualType getBlockDescriptorType() const;
679
680  /// This gets the struct used to keep track of the extended descriptor for
681  /// pointer to blocks.
682  QualType getBlockDescriptorExtendedType() const;
683
684  void setcudaConfigureCallDecl(FunctionDecl *FD) {
685    cudaConfigureCallDecl = FD;
686  }
687  FunctionDecl *getcudaConfigureCallDecl() {
688    return cudaConfigureCallDecl;
689  }
690
691  /// This builds the struct used for __block variables.
692  QualType BuildByRefType(StringRef DeclName, QualType Ty) const;
693
694  /// Returns true iff we need copy/dispose helpers for the given type.
695  bool BlockRequiresCopying(QualType Ty) const;
696
697  /// getLValueReferenceType - Return the uniqued reference to the type for an
698  /// lvalue reference to the specified type.
699  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
700    const;
701
702  /// getRValueReferenceType - Return the uniqued reference to the type for an
703  /// rvalue reference to the specified type.
704  QualType getRValueReferenceType(QualType T) const;
705
706  /// getMemberPointerType - Return the uniqued reference to the type for a
707  /// member pointer to the specified type in the specified class. The class
708  /// is a Type because it could be a dependent name.
709  QualType getMemberPointerType(QualType T, const Type *Cls) const;
710
711  /// getVariableArrayType - Returns a non-unique reference to the type for a
712  /// variable array of the specified element type.
713  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
714                                ArrayType::ArraySizeModifier ASM,
715                                unsigned IndexTypeQuals,
716                                SourceRange Brackets) const;
717
718  /// getDependentSizedArrayType - Returns a non-unique reference to
719  /// the type for a dependently-sized array of the specified element
720  /// type. FIXME: We will need these to be uniqued, or at least
721  /// comparable, at some point.
722  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
723                                      ArrayType::ArraySizeModifier ASM,
724                                      unsigned IndexTypeQuals,
725                                      SourceRange Brackets) const;
726
727  /// getIncompleteArrayType - Returns a unique reference to the type for a
728  /// incomplete array of the specified element type.
729  QualType getIncompleteArrayType(QualType EltTy,
730                                  ArrayType::ArraySizeModifier ASM,
731                                  unsigned IndexTypeQuals) const;
732
733  /// getConstantArrayType - Return the unique reference to the type for a
734  /// constant array of the specified element type.
735  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
736                                ArrayType::ArraySizeModifier ASM,
737                                unsigned IndexTypeQuals) const;
738
739  /// getVariableArrayDecayedType - Returns a vla type where known sizes
740  /// are replaced with [*].
741  QualType getVariableArrayDecayedType(QualType Ty) const;
742
743  /// getVectorType - Return the unique reference to a vector type of
744  /// the specified element type and size. VectorType must be a built-in type.
745  QualType getVectorType(QualType VectorType, unsigned NumElts,
746                         VectorType::VectorKind VecKind) const;
747
748  /// getExtVectorType - Return the unique reference to an extended vector type
749  /// of the specified element type and size.  VectorType must be a built-in
750  /// type.
751  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
752
753  /// getDependentSizedExtVectorType - Returns a non-unique reference to
754  /// the type for a dependently-sized vector of the specified element
755  /// type. FIXME: We will need these to be uniqued, or at least
756  /// comparable, at some point.
757  QualType getDependentSizedExtVectorType(QualType VectorType,
758                                          Expr *SizeExpr,
759                                          SourceLocation AttrLoc) const;
760
761  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
762  ///
763  QualType getFunctionNoProtoType(QualType ResultTy,
764                                  const FunctionType::ExtInfo &Info) const;
765
766  QualType getFunctionNoProtoType(QualType ResultTy) const {
767    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
768  }
769
770  /// getFunctionType - Return a normal function type with a typed
771  /// argument list.
772  QualType getFunctionType(QualType ResultTy,
773                           const QualType *Args, unsigned NumArgs,
774                           const FunctionProtoType::ExtProtoInfo &EPI) const;
775
776  /// getTypeDeclType - Return the unique reference to the type for
777  /// the specified type declaration.
778  QualType getTypeDeclType(const TypeDecl *Decl,
779                           const TypeDecl *PrevDecl = 0) const {
780    assert(Decl && "Passed null for Decl param");
781    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
782
783    if (PrevDecl) {
784      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
785      Decl->TypeForDecl = PrevDecl->TypeForDecl;
786      return QualType(PrevDecl->TypeForDecl, 0);
787    }
788
789    return getTypeDeclTypeSlow(Decl);
790  }
791
792  /// getTypedefType - Return the unique reference to the type for the
793  /// specified typedef-name decl.
794  QualType getTypedefType(const TypedefNameDecl *Decl,
795                          QualType Canon = QualType()) const;
796
797  QualType getRecordType(const RecordDecl *Decl) const;
798
799  QualType getEnumType(const EnumDecl *Decl) const;
800
801  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
802
803  QualType getAttributedType(AttributedType::Kind attrKind,
804                             QualType modifiedType,
805                             QualType equivalentType);
806
807  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
808                                        QualType Replacement) const;
809  QualType getSubstTemplateTypeParmPackType(
810                                          const TemplateTypeParmType *Replaced,
811                                            const TemplateArgument &ArgPack);
812
813  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
814                                   bool ParameterPack,
815                                   TemplateTypeParmDecl *ParmDecl = 0) const;
816
817  QualType getTemplateSpecializationType(TemplateName T,
818                                         const TemplateArgument *Args,
819                                         unsigned NumArgs,
820                                         QualType Canon = QualType()) const;
821
822  QualType getCanonicalTemplateSpecializationType(TemplateName T,
823                                                  const TemplateArgument *Args,
824                                                  unsigned NumArgs) const;
825
826  QualType getTemplateSpecializationType(TemplateName T,
827                                         const TemplateArgumentListInfo &Args,
828                                         QualType Canon = QualType()) const;
829
830  TypeSourceInfo *
831  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
832                                    const TemplateArgumentListInfo &Args,
833                                    QualType Canon = QualType()) const;
834
835  QualType getParenType(QualType NamedType) const;
836
837  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
838                             NestedNameSpecifier *NNS,
839                             QualType NamedType) const;
840  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
841                                NestedNameSpecifier *NNS,
842                                const IdentifierInfo *Name,
843                                QualType Canon = QualType()) const;
844
845  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
846                                                  NestedNameSpecifier *NNS,
847                                                  const IdentifierInfo *Name,
848                                    const TemplateArgumentListInfo &Args) const;
849  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
850                                                  NestedNameSpecifier *NNS,
851                                                  const IdentifierInfo *Name,
852                                                  unsigned NumArgs,
853                                            const TemplateArgument *Args) const;
854
855  QualType getPackExpansionType(QualType Pattern,
856                                llvm::Optional<unsigned> NumExpansions);
857
858  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
859                                ObjCInterfaceDecl *PrevDecl = 0) const;
860
861  QualType getObjCObjectType(QualType Base,
862                             ObjCProtocolDecl * const *Protocols,
863                             unsigned NumProtocols) const;
864
865  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
866  /// for the given ObjCObjectType.
867  QualType getObjCObjectPointerType(QualType OIT) const;
868
869  /// getTypeOfType - GCC extension.
870  QualType getTypeOfExprType(Expr *e) const;
871  QualType getTypeOfType(QualType t) const;
872
873  /// getDecltypeType - C++0x decltype.
874  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
875
876  /// getUnaryTransformType - unary type transforms
877  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
878                                 UnaryTransformType::UTTKind UKind) const;
879
880  /// getAutoType - C++0x deduced auto type.
881  QualType getAutoType(QualType DeducedType) const;
882
883  /// getAutoDeductType - C++0x deduction pattern for 'auto' type.
884  QualType getAutoDeductType() const;
885
886  /// getAutoRRefDeductType - C++0x deduction pattern for 'auto &&' type.
887  QualType getAutoRRefDeductType() const;
888
889  /// getTagDeclType - Return the unique reference to the type for the
890  /// specified TagDecl (struct/union/class/enum) decl.
891  QualType getTagDeclType(const TagDecl *Decl) const;
892
893  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
894  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
895  CanQualType getSizeType() const;
896
897  /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5),
898  /// defined in <stdint.h>.
899  CanQualType getIntMaxType() const;
900
901  /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5),
902  /// defined in <stdint.h>.
903  CanQualType getUIntMaxType() const;
904
905  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
906  /// returns a type compatible with the type defined in <stddef.h> as defined
907  /// by the target.
908  QualType getWCharType() const { return WCharTy; }
909
910  /// getSignedWCharType - Return the type of "signed wchar_t".
911  /// Used when in C++, as a GCC extension.
912  QualType getSignedWCharType() const;
913
914  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
915  /// Used when in C++, as a GCC extension.
916  QualType getUnsignedWCharType() const;
917
918  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
919  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
920  QualType getPointerDiffType() const;
921
922  // getCFConstantStringType - Return the C structure type used to represent
923  // constant CFStrings.
924  QualType getCFConstantStringType() const;
925
926  /// Get the structure type used to representation CFStrings, or NULL
927  /// if it hasn't yet been built.
928  QualType getRawCFConstantStringType() const {
929    if (CFConstantStringTypeDecl)
930      return getTagDeclType(CFConstantStringTypeDecl);
931    return QualType();
932  }
933  void setCFConstantStringType(QualType T);
934
935  // This setter/getter represents the ObjC type for an NSConstantString.
936  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
937  QualType getObjCConstantStringInterface() const {
938    return ObjCConstantStringType;
939  }
940
941  /// \brief Retrieve the type that 'id' has been defined to, which may be
942  /// different from the built-in 'id' if 'id' has been typedef'd.
943  QualType getObjCIdRedefinitionType() const {
944    if (ObjCIdRedefinitionType.isNull())
945      return getObjCIdType();
946    return ObjCIdRedefinitionType;
947  }
948
949  /// \brief Set the user-written type that redefines 'id'.
950  void setObjCIdRedefinitionType(QualType RedefType) {
951    ObjCIdRedefinitionType = RedefType;
952  }
953
954  /// \brief Retrieve the type that 'Class' has been defined to, which may be
955  /// different from the built-in 'Class' if 'Class' has been typedef'd.
956  QualType getObjCClassRedefinitionType() const {
957    if (ObjCClassRedefinitionType.isNull())
958      return getObjCClassType();
959    return ObjCClassRedefinitionType;
960  }
961
962  /// \brief Set the user-written type that redefines 'SEL'.
963  void setObjCClassRedefinitionType(QualType RedefType) {
964    ObjCClassRedefinitionType = RedefType;
965  }
966
967  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
968  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
969  QualType getObjCSelRedefinitionType() const {
970    if (ObjCSelRedefinitionType.isNull())
971      return getObjCSelType();
972    return ObjCSelRedefinitionType;
973  }
974
975
976  /// \brief Set the user-written type that redefines 'SEL'.
977  void setObjCSelRedefinitionType(QualType RedefType) {
978    ObjCSelRedefinitionType = RedefType;
979  }
980
981  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
982  /// otherwise, returns a NULL type;
983  QualType getObjCInstanceType() {
984    return getTypeDeclType(getObjCInstanceTypeDecl());
985  }
986
987  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
988  /// "instancetype" type.
989  TypedefDecl *getObjCInstanceTypeDecl();
990
991  /// \brief Set the type for the C FILE type.
992  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
993
994  /// \brief Retrieve the C FILE type.
995  QualType getFILEType() const {
996    if (FILEDecl)
997      return getTypeDeclType(FILEDecl);
998    return QualType();
999  }
1000
1001  /// \brief Set the type for the C jmp_buf type.
1002  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1003    this->jmp_bufDecl = jmp_bufDecl;
1004  }
1005
1006  /// \brief Retrieve the C jmp_buf type.
1007  QualType getjmp_bufType() const {
1008    if (jmp_bufDecl)
1009      return getTypeDeclType(jmp_bufDecl);
1010    return QualType();
1011  }
1012
1013  /// \brief Set the type for the C sigjmp_buf type.
1014  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1015    this->sigjmp_bufDecl = sigjmp_bufDecl;
1016  }
1017
1018  /// \brief Retrieve the C sigjmp_buf type.
1019  QualType getsigjmp_bufType() const {
1020    if (sigjmp_bufDecl)
1021      return getTypeDeclType(sigjmp_bufDecl);
1022    return QualType();
1023  }
1024
1025  /// \brief Set the type for the C ucontext_t type.
1026  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1027    this->ucontext_tDecl = ucontext_tDecl;
1028  }
1029
1030  /// \brief Retrieve the C ucontext_t type.
1031  QualType getucontext_tType() const {
1032    if (ucontext_tDecl)
1033      return getTypeDeclType(ucontext_tDecl);
1034    return QualType();
1035  }
1036
1037  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1038  QualType getLogicalOperationType() const {
1039    return getLangOptions().CPlusPlus ? BoolTy : IntTy;
1040  }
1041
1042  /// getObjCEncodingForType - Emit the ObjC type encoding for the
1043  /// given type into \arg S. If \arg NameFields is specified then
1044  /// record field names are also encoded.
1045  void getObjCEncodingForType(QualType t, std::string &S,
1046                              const FieldDecl *Field=0) const;
1047
1048  void getLegacyIntegralTypeEncoding(QualType &t) const;
1049
1050  // Put the string version of type qualifiers into S.
1051  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1052                                       std::string &S) const;
1053
1054  /// getObjCEncodingForFunctionDecl - Returns the encoded type for this
1055  /// function.  This is in the same format as Objective-C method encodings.
1056  ///
1057  /// \returns true if an error occurred (e.g., because one of the parameter
1058  /// types is incomplete), false otherwise.
1059  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1060
1061  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
1062  /// declaration.
1063  ///
1064  /// \returns true if an error occurred (e.g., because one of the parameter
1065  /// types is incomplete), false otherwise.
1066  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1067                                    bool Extended = false)
1068    const;
1069
1070  /// getObjCEncodingForBlock - Return the encoded type for this block
1071  /// declaration.
1072  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1073
1074  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1075  /// this method declaration. If non-NULL, Container must be either
1076  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1077  /// only be NULL when getting encodings for protocol properties.
1078  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1079                                      const Decl *Container,
1080                                      std::string &S) const;
1081
1082  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1083                                      ObjCProtocolDecl *rProto) const;
1084
1085  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
1086  /// purpose in characters.
1087  CharUnits getObjCEncodingTypeSize(QualType t) const;
1088
1089  /// \brief Retrieve the typedef corresponding to the predefined 'id' type
1090  /// in Objective-C.
1091  TypedefDecl *getObjCIdDecl() const;
1092
1093  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
1094  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
1095  QualType getObjCIdType() const {
1096    return getTypeDeclType(getObjCIdDecl());
1097  }
1098
1099  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1100  /// in Objective-C.
1101  TypedefDecl *getObjCSelDecl() const;
1102
1103  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1104  /// 'SEL' type.
1105  QualType getObjCSelType() const {
1106    return getTypeDeclType(getObjCSelDecl());
1107  }
1108
1109  /// \brief Retrieve the typedef declaration corresponding to the predefined
1110  /// Objective-C 'Class' type.
1111  TypedefDecl *getObjCClassDecl() const;
1112
1113  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
1114  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
1115  /// struct.
1116  QualType getObjCClassType() const {
1117    return getTypeDeclType(getObjCClassDecl());
1118  }
1119
1120  /// \brief Retrieve the Objective-C class declaration corresponding to
1121  /// the predefined 'Protocol' class.
1122  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1123
1124  /// \brief Retrieve the type of the Objective-C "Protocol" class.
1125  QualType getObjCProtoType() const {
1126    return getObjCInterfaceType(getObjCProtocolDecl());
1127  }
1128
1129  void setBuiltinVaListType(QualType T);
1130  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
1131
1132  /// getCVRQualifiedType - Returns a type with additional const,
1133  /// volatile, or restrict qualifiers.
1134  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1135    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1136  }
1137
1138  /// getQualifiedType - Un-split a SplitQualType.
1139  QualType getQualifiedType(SplitQualType split) const {
1140    return getQualifiedType(split.Ty, split.Quals);
1141  }
1142
1143  /// getQualifiedType - Returns a type with additional qualifiers.
1144  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1145    if (!Qs.hasNonFastQualifiers())
1146      return T.withFastQualifiers(Qs.getFastQualifiers());
1147    QualifierCollector Qc(Qs);
1148    const Type *Ptr = Qc.strip(T);
1149    return getExtQualType(Ptr, Qc);
1150  }
1151
1152  /// getQualifiedType - Returns a type with additional qualifiers.
1153  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1154    if (!Qs.hasNonFastQualifiers())
1155      return QualType(T, Qs.getFastQualifiers());
1156    return getExtQualType(T, Qs);
1157  }
1158
1159  /// getLifetimeQualifiedType - Returns a type with the given
1160  /// lifetime qualifier.
1161  QualType getLifetimeQualifiedType(QualType type,
1162                                    Qualifiers::ObjCLifetime lifetime) {
1163    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1164    assert(lifetime != Qualifiers::OCL_None);
1165
1166    Qualifiers qs;
1167    qs.addObjCLifetime(lifetime);
1168    return getQualifiedType(type, qs);
1169  }
1170
1171  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1172                                         SourceLocation NameLoc) const;
1173
1174  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1175                                         UnresolvedSetIterator End) const;
1176
1177  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1178                                        bool TemplateKeyword,
1179                                        TemplateDecl *Template) const;
1180
1181  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1182                                        const IdentifierInfo *Name) const;
1183  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1184                                        OverloadedOperatorKind Operator) const;
1185  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1186                                            TemplateName replacement) const;
1187  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1188                                        const TemplateArgument &ArgPack) const;
1189
1190  enum GetBuiltinTypeError {
1191    GE_None,              //< No error
1192    GE_Missing_stdio,     //< Missing a type from <stdio.h>
1193    GE_Missing_setjmp,    //< Missing a type from <setjmp.h>
1194    GE_Missing_ucontext   //< Missing a type from <ucontext.h>
1195  };
1196
1197  /// GetBuiltinType - Return the type for the specified builtin.  If
1198  /// IntegerConstantArgs is non-null, it is filled in with a bitmask of
1199  /// arguments to the builtin that are required to be integer constant
1200  /// expressions.
1201  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1202                          unsigned *IntegerConstantArgs = 0) const;
1203
1204private:
1205  CanQualType getFromTargetType(unsigned Type) const;
1206
1207  //===--------------------------------------------------------------------===//
1208  //                         Type Predicates.
1209  //===--------------------------------------------------------------------===//
1210
1211public:
1212  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
1213  /// garbage collection attribute.
1214  ///
1215  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1216
1217  /// areCompatibleVectorTypes - Return true if the given vector types
1218  /// are of the same unqualified type or if they are equivalent to the same
1219  /// GCC vector type, ignoring whether they are target-specific (AltiVec or
1220  /// Neon) types.
1221  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1222
1223  /// isObjCNSObjectType - Return true if this is an NSObject object with
1224  /// its NSObject attribute set.
1225  static bool isObjCNSObjectType(QualType Ty) {
1226    return Ty->isObjCNSObjectType();
1227  }
1228
1229  //===--------------------------------------------------------------------===//
1230  //                         Type Sizing and Analysis
1231  //===--------------------------------------------------------------------===//
1232
1233  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1234  /// scalar floating point type.
1235  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1236
1237  /// getTypeInfo - Get the size and alignment of the specified complete type in
1238  /// bits.
1239  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1240  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1241    return getTypeInfo(T.getTypePtr());
1242  }
1243
1244  /// getTypeSize - Return the size of the specified type, in bits.  This method
1245  /// does not work on incomplete types.
1246  uint64_t getTypeSize(QualType T) const {
1247    return getTypeInfo(T).first;
1248  }
1249  uint64_t getTypeSize(const Type *T) const {
1250    return getTypeInfo(T).first;
1251  }
1252
1253  /// getCharWidth - Return the size of the character type, in bits
1254  uint64_t getCharWidth() const {
1255    return getTypeSize(CharTy);
1256  }
1257
1258  /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1259  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1260
1261  /// toBits - Convert a size in characters to a size in bits.
1262  int64_t toBits(CharUnits CharSize) const;
1263
1264  /// getTypeSizeInChars - Return the size of the specified type, in characters.
1265  /// This method does not work on incomplete types.
1266  CharUnits getTypeSizeInChars(QualType T) const;
1267  CharUnits getTypeSizeInChars(const Type *T) const;
1268
1269  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
1270  /// This method does not work on incomplete types.
1271  unsigned getTypeAlign(QualType T) const {
1272    return getTypeInfo(T).second;
1273  }
1274  unsigned getTypeAlign(const Type *T) const {
1275    return getTypeInfo(T).second;
1276  }
1277
1278  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1279  /// characters. This method does not work on incomplete types.
1280  CharUnits getTypeAlignInChars(QualType T) const;
1281  CharUnits getTypeAlignInChars(const Type *T) const;
1282
1283  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1284  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1285
1286  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1287  /// type for the current target in bits.  This can be different than the ABI
1288  /// alignment in cases where it is beneficial for performance to overalign
1289  /// a data type.
1290  unsigned getPreferredTypeAlign(const Type *T) const;
1291
1292  /// getDeclAlign - Return a conservative estimate of the alignment of
1293  /// the specified decl.  Note that bitfields do not have a valid alignment, so
1294  /// this method will assert on them.
1295  /// If @p RefAsPointee, references are treated like their underlying type
1296  /// (for alignof), else they're treated like pointers (for CodeGen).
1297  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1298
1299  /// getASTRecordLayout - Get or compute information about the layout of the
1300  /// specified record (struct/union/class), which indicates its size and field
1301  /// position information.
1302  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1303
1304  /// getASTObjCInterfaceLayout - Get or compute information about the
1305  /// layout of the specified Objective-C interface.
1306  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1307    const;
1308
1309  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1310                        bool Simple = false) const;
1311
1312  /// getASTObjCImplementationLayout - Get or compute information about
1313  /// the layout of the specified Objective-C implementation. This may
1314  /// differ from the interface if synthesized ivars are present.
1315  const ASTRecordLayout &
1316  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1317
1318  /// getKeyFunction - Get the key function for the given record decl, or NULL
1319  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
1320  /// section 5.2.3:
1321  ///
1322  /// ...the first non-pure virtual function that is not inline at the point
1323  /// of class definition.
1324  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1325
1326  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1327  uint64_t getFieldOffset(const ValueDecl *FD) const;
1328
1329  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1330
1331  MangleContext *createMangleContext();
1332
1333  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1334                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1335
1336  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1337  void CollectInheritedProtocols(const Decl *CDecl,
1338                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1339
1340  //===--------------------------------------------------------------------===//
1341  //                            Type Operators
1342  //===--------------------------------------------------------------------===//
1343
1344  /// getCanonicalType - Return the canonical (structural) type corresponding to
1345  /// the specified potentially non-canonical type.  The non-canonical version
1346  /// of a type may have many "decorated" versions of types.  Decorators can
1347  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1348  /// to be free of any of these, allowing two canonical types to be compared
1349  /// for exact equality with a simple pointer comparison.
1350  CanQualType getCanonicalType(QualType T) const {
1351    return CanQualType::CreateUnsafe(T.getCanonicalType());
1352  }
1353
1354  const Type *getCanonicalType(const Type *T) const {
1355    return T->getCanonicalTypeInternal().getTypePtr();
1356  }
1357
1358  /// getCanonicalParamType - Return the canonical parameter type
1359  /// corresponding to the specific potentially non-canonical one.
1360  /// Qualifiers are stripped off, functions are turned into function
1361  /// pointers, and arrays decay one level into pointers.
1362  CanQualType getCanonicalParamType(QualType T) const;
1363
1364  /// \brief Determine whether the given types are equivalent.
1365  bool hasSameType(QualType T1, QualType T2) const {
1366    return getCanonicalType(T1) == getCanonicalType(T2);
1367  }
1368
1369  /// \brief Returns this type as a completely-unqualified array type,
1370  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1371  /// sugaring from the types, similar to the behavior of
1372  /// QualType::getUnqualifiedType().
1373  ///
1374  /// \param T is the qualified type, which may be an ArrayType
1375  ///
1376  /// \param Quals will receive the full set of qualifiers that were
1377  /// applied to the array.
1378  ///
1379  /// \returns if this is an array type, the completely unqualified array type
1380  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1381  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1382
1383  /// \brief Determine whether the given types are equivalent after
1384  /// cvr-qualifiers have been removed.
1385  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1386    return getCanonicalType(T1).getTypePtr() ==
1387           getCanonicalType(T2).getTypePtr();
1388  }
1389
1390  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1391
1392  /// \brief Retrieves the "canonical" nested name specifier for a
1393  /// given nested name specifier.
1394  ///
1395  /// The canonical nested name specifier is a nested name specifier
1396  /// that uniquely identifies a type or namespace within the type
1397  /// system. For example, given:
1398  ///
1399  /// \code
1400  /// namespace N {
1401  ///   struct S {
1402  ///     template<typename T> struct X { typename T* type; };
1403  ///   };
1404  /// }
1405  ///
1406  /// template<typename T> struct Y {
1407  ///   typename N::S::X<T>::type member;
1408  /// };
1409  /// \endcode
1410  ///
1411  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1412  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1413  /// by declarations in the type system and the canonical type for
1414  /// the template type parameter 'T' is template-param-0-0.
1415  NestedNameSpecifier *
1416  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1417
1418  /// \brief Retrieves the default calling convention to use for
1419  /// C++ instance methods.
1420  CallingConv getDefaultMethodCallConv();
1421
1422  /// \brief Retrieves the canonical representation of the given
1423  /// calling convention.
1424  CallingConv getCanonicalCallConv(CallingConv CC) const {
1425    if (!LangOpts.MRTD && CC == CC_C)
1426      return CC_Default;
1427    return CC;
1428  }
1429
1430  /// \brief Determines whether two calling conventions name the same
1431  /// calling convention.
1432  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1433    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1434  }
1435
1436  /// \brief Retrieves the "canonical" template name that refers to a
1437  /// given template.
1438  ///
1439  /// The canonical template name is the simplest expression that can
1440  /// be used to refer to a given template. For most templates, this
1441  /// expression is just the template declaration itself. For example,
1442  /// the template std::vector can be referred to via a variety of
1443  /// names---std::vector, ::std::vector, vector (if vector is in
1444  /// scope), etc.---but all of these names map down to the same
1445  /// TemplateDecl, which is used to form the canonical template name.
1446  ///
1447  /// Dependent template names are more interesting. Here, the
1448  /// template name could be something like T::template apply or
1449  /// std::allocator<T>::template rebind, where the nested name
1450  /// specifier itself is dependent. In this case, the canonical
1451  /// template name uses the shortest form of the dependent
1452  /// nested-name-specifier, which itself contains all canonical
1453  /// types, values, and templates.
1454  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1455
1456  /// \brief Determine whether the given template names refer to the same
1457  /// template.
1458  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1459
1460  /// \brief Retrieve the "canonical" template argument.
1461  ///
1462  /// The canonical template argument is the simplest template argument
1463  /// (which may be a type, value, expression, or declaration) that
1464  /// expresses the value of the argument.
1465  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1466    const;
1467
1468  /// Type Query functions.  If the type is an instance of the specified class,
1469  /// return the Type pointer for the underlying maximally pretty type.  This
1470  /// is a member of ASTContext because this may need to do some amount of
1471  /// canonicalization, e.g. to move type qualifiers into the element type.
1472  const ArrayType *getAsArrayType(QualType T) const;
1473  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1474    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1475  }
1476  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1477    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1478  }
1479  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1480    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1481  }
1482  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1483    const {
1484    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1485  }
1486
1487  /// getBaseElementType - Returns the innermost element type of an array type.
1488  /// For example, will return "int" for int[m][n]
1489  QualType getBaseElementType(const ArrayType *VAT) const;
1490
1491  /// getBaseElementType - Returns the innermost element type of a type
1492  /// (which needn't actually be an array type).
1493  QualType getBaseElementType(QualType QT) const;
1494
1495  /// getConstantArrayElementCount - Returns number of constant array elements.
1496  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1497
1498  /// \brief Perform adjustment on the parameter type of a function.
1499  ///
1500  /// This routine adjusts the given parameter type @p T to the actual
1501  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1502  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1503  QualType getAdjustedParameterType(QualType T);
1504
1505  /// \brief Retrieve the parameter type as adjusted for use in the signature
1506  /// of a function, decaying array and function types and removing top-level
1507  /// cv-qualifiers.
1508  QualType getSignatureParameterType(QualType T);
1509
1510  /// getArrayDecayedType - Return the properly qualified result of decaying the
1511  /// specified array type to a pointer.  This operation is non-trivial when
1512  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1513  /// this returns a pointer to a properly qualified element of the array.
1514  ///
1515  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1516  QualType getArrayDecayedType(QualType T) const;
1517
1518  /// getPromotedIntegerType - Returns the type that Promotable will
1519  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1520  /// integer type.
1521  QualType getPromotedIntegerType(QualType PromotableType) const;
1522
1523  /// \brief Recurses in pointer/array types until it finds an objc retainable
1524  /// type and returns its ownership.
1525  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1526
1527  /// \brief Whether this is a promotable bitfield reference according
1528  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1529  ///
1530  /// \returns the type this bit-field will promote to, or NULL if no
1531  /// promotion occurs.
1532  QualType isPromotableBitField(Expr *E) const;
1533
1534  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1535  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1536  /// LHS < RHS, return -1.
1537  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1538
1539  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1540  /// point types, ignoring the domain of the type (i.e. 'double' ==
1541  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1542  /// LHS < RHS, return -1.
1543  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1544
1545  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1546  /// point or a complex type (based on typeDomain/typeSize).
1547  /// 'typeDomain' is a real floating point or complex type.
1548  /// 'typeSize' is a real floating point or complex type.
1549  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1550                                             QualType typeDomain) const;
1551
1552  unsigned getTargetAddressSpace(QualType T) const {
1553    return getTargetAddressSpace(T.getQualifiers());
1554  }
1555
1556  unsigned getTargetAddressSpace(Qualifiers Q) const {
1557    return getTargetAddressSpace(Q.getAddressSpace());
1558  }
1559
1560  unsigned getTargetAddressSpace(unsigned AS) const {
1561    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1562      return AS;
1563    else
1564      return (*AddrSpaceMap)[AS - LangAS::Offset];
1565  }
1566
1567private:
1568  // Helper for integer ordering
1569  unsigned getIntegerRank(const Type *T) const;
1570
1571public:
1572
1573  //===--------------------------------------------------------------------===//
1574  //                    Type Compatibility Predicates
1575  //===--------------------------------------------------------------------===//
1576
1577  /// Compatibility predicates used to check assignment expressions.
1578  bool typesAreCompatible(QualType T1, QualType T2,
1579                          bool CompareUnqualified = false); // C99 6.2.7p1
1580
1581  bool propertyTypesAreCompatible(QualType, QualType);
1582  bool typesAreBlockPointerCompatible(QualType, QualType);
1583
1584  bool isObjCIdType(QualType T) const {
1585    return T == getObjCIdType();
1586  }
1587  bool isObjCClassType(QualType T) const {
1588    return T == getObjCClassType();
1589  }
1590  bool isObjCSelType(QualType T) const {
1591    return T == getObjCSelType();
1592  }
1593  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1594  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1595                                         bool ForCompare);
1596
1597  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1598
1599  // Check the safety of assignment from LHS to RHS
1600  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1601                               const ObjCObjectPointerType *RHSOPT);
1602  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1603                               const ObjCObjectType *RHS);
1604  bool canAssignObjCInterfacesInBlockPointer(
1605                                          const ObjCObjectPointerType *LHSOPT,
1606                                          const ObjCObjectPointerType *RHSOPT,
1607                                          bool BlockReturnType);
1608  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1609  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1610                                   const ObjCObjectPointerType *RHSOPT);
1611  bool canBindObjCObjectType(QualType To, QualType From);
1612
1613  // Functions for calculating composite types
1614  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1615                      bool Unqualified = false, bool BlockReturnType = false);
1616  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1617                              bool Unqualified = false);
1618  QualType mergeFunctionArgumentTypes(QualType, QualType,
1619                                      bool OfBlockPointer=false,
1620                                      bool Unqualified = false);
1621  QualType mergeTransparentUnionType(QualType, QualType,
1622                                     bool OfBlockPointer=false,
1623                                     bool Unqualified = false);
1624
1625  QualType mergeObjCGCQualifiers(QualType, QualType);
1626
1627  bool FunctionTypesMatchOnNSConsumedAttrs(
1628         const FunctionProtoType *FromFunctionType,
1629         const FunctionProtoType *ToFunctionType);
1630
1631  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1632    ObjCLayouts[CD] = 0;
1633  }
1634
1635  //===--------------------------------------------------------------------===//
1636  //                    Integer Predicates
1637  //===--------------------------------------------------------------------===//
1638
1639  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1640  // of bits in an integer type excluding any padding bits.
1641  unsigned getIntWidth(QualType T) const;
1642
1643  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1644  // unsigned integer type.  This method takes a signed type, and returns the
1645  // corresponding unsigned integer type.
1646  QualType getCorrespondingUnsignedType(QualType T);
1647
1648  //===--------------------------------------------------------------------===//
1649  //                    Type Iterators.
1650  //===--------------------------------------------------------------------===//
1651
1652  typedef std::vector<Type*>::iterator       type_iterator;
1653  typedef std::vector<Type*>::const_iterator const_type_iterator;
1654
1655  type_iterator types_begin() { return Types.begin(); }
1656  type_iterator types_end() { return Types.end(); }
1657  const_type_iterator types_begin() const { return Types.begin(); }
1658  const_type_iterator types_end() const { return Types.end(); }
1659
1660  //===--------------------------------------------------------------------===//
1661  //                    Integer Values
1662  //===--------------------------------------------------------------------===//
1663
1664  /// MakeIntValue - Make an APSInt of the appropriate width and
1665  /// signedness for the given \arg Value and integer \arg Type.
1666  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1667    llvm::APSInt Res(getIntWidth(Type),
1668                     !Type->isSignedIntegerOrEnumerationType());
1669    Res = Value;
1670    return Res;
1671  }
1672
1673  bool isSentinelNullExpr(const Expr *E);
1674
1675  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1676  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1677  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1678  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1679
1680  /// \brief returns true if there is at lease one @implementation in TU.
1681  bool AnyObjCImplementation() {
1682    return !ObjCImpls.empty();
1683  }
1684
1685  /// \brief Set the implementation of ObjCInterfaceDecl.
1686  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1687                             ObjCImplementationDecl *ImplD);
1688  /// \brief Set the implementation of ObjCCategoryDecl.
1689  void setObjCImplementation(ObjCCategoryDecl *CatD,
1690                             ObjCCategoryImplDecl *ImplD);
1691
1692  /// \brief Get the duplicate declaration of a ObjCMethod in the same
1693  /// interface, or null if non exists.
1694  const ObjCMethodDecl *getObjCMethodRedeclaration(
1695                                               const ObjCMethodDecl *MD) const {
1696    llvm::DenseMap<const ObjCMethodDecl*, const ObjCMethodDecl*>::const_iterator
1697      I = ObjCMethodRedecls.find(MD);
1698    if (I == ObjCMethodRedecls.end())
1699      return 0;
1700    return I->second;
1701  }
1702
1703  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1704                                  const ObjCMethodDecl *Redecl) {
1705    ObjCMethodRedecls[MD] = Redecl;
1706  }
1707
1708  /// \brief Returns the objc interface that \arg ND belongs to if it is a
1709  /// objc method/property/ivar etc. that is part of an interface,
1710  /// otherwise returns null.
1711  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1712
1713  /// \brief Set the copy inialization expression of a block var decl.
1714  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1715  /// \brief Get the copy initialization expression of VarDecl,or NULL if
1716  /// none exists.
1717  Expr *getBlockVarCopyInits(const VarDecl*VD);
1718
1719  /// \brief Allocate an uninitialized TypeSourceInfo.
1720  ///
1721  /// The caller should initialize the memory held by TypeSourceInfo using
1722  /// the TypeLoc wrappers.
1723  ///
1724  /// \param T the type that will be the basis for type source info. This type
1725  /// should refer to how the declarator was written in source code, not to
1726  /// what type semantic analysis resolved the declarator to.
1727  ///
1728  /// \param Size the size of the type info to create, or 0 if the size
1729  /// should be calculated based on the type.
1730  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1731
1732  /// \brief Allocate a TypeSourceInfo where all locations have been
1733  /// initialized to a given location, which defaults to the empty
1734  /// location.
1735  TypeSourceInfo *
1736  getTrivialTypeSourceInfo(QualType T,
1737                           SourceLocation Loc = SourceLocation()) const;
1738
1739  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1740
1741  /// \brief Add a deallocation callback that will be invoked when the
1742  /// ASTContext is destroyed.
1743  ///
1744  /// \brief Callback A callback function that will be invoked on destruction.
1745  ///
1746  /// \brief Data Pointer data that will be provided to the callback function
1747  /// when it is called.
1748  void AddDeallocation(void (*Callback)(void*), void *Data);
1749
1750  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1751  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1752
1753  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1754  /// lazily, only when used; this is only relevant for function or file scoped
1755  /// var definitions.
1756  ///
1757  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1758  /// it is not used.
1759  bool DeclMustBeEmitted(const Decl *D);
1760
1761
1762  /// \brief Used by ParmVarDecl to store on the side the
1763  /// index of the parameter when it exceeds the size of the normal bitfield.
1764  void setParameterIndex(const ParmVarDecl *D, unsigned index);
1765
1766  /// \brief Used by ParmVarDecl to retrieve on the side the
1767  /// index of the parameter when it exceeds the size of the normal bitfield.
1768  unsigned getParameterIndex(const ParmVarDecl *D) const;
1769
1770  //===--------------------------------------------------------------------===//
1771  //                    Statistics
1772  //===--------------------------------------------------------------------===//
1773
1774  /// \brief The number of implicitly-declared default constructors.
1775  static unsigned NumImplicitDefaultConstructors;
1776
1777  /// \brief The number of implicitly-declared default constructors for
1778  /// which declarations were built.
1779  static unsigned NumImplicitDefaultConstructorsDeclared;
1780
1781  /// \brief The number of implicitly-declared copy constructors.
1782  static unsigned NumImplicitCopyConstructors;
1783
1784  /// \brief The number of implicitly-declared copy constructors for
1785  /// which declarations were built.
1786  static unsigned NumImplicitCopyConstructorsDeclared;
1787
1788  /// \brief The number of implicitly-declared move constructors.
1789  static unsigned NumImplicitMoveConstructors;
1790
1791  /// \brief The number of implicitly-declared move constructors for
1792  /// which declarations were built.
1793  static unsigned NumImplicitMoveConstructorsDeclared;
1794
1795  /// \brief The number of implicitly-declared copy assignment operators.
1796  static unsigned NumImplicitCopyAssignmentOperators;
1797
1798  /// \brief The number of implicitly-declared copy assignment operators for
1799  /// which declarations were built.
1800  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
1801
1802  /// \brief The number of implicitly-declared move assignment operators.
1803  static unsigned NumImplicitMoveAssignmentOperators;
1804
1805  /// \brief The number of implicitly-declared move assignment operators for
1806  /// which declarations were built.
1807  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
1808
1809  /// \brief The number of implicitly-declared destructors.
1810  static unsigned NumImplicitDestructors;
1811
1812  /// \brief The number of implicitly-declared destructors for which
1813  /// declarations were built.
1814  static unsigned NumImplicitDestructorsDeclared;
1815
1816private:
1817  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1818  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1819
1820public:
1821  /// \brief Initialize built-in types.
1822  ///
1823  /// This routine may only be invoked once for a given ASTContext object.
1824  /// It is normally invoked by the ASTContext constructor. However, the
1825  /// constructor can be asked to delay initialization, which places the burden
1826  /// of calling this function on the user of that object.
1827  ///
1828  /// \param Target The target
1829  void InitBuiltinTypes(const TargetInfo &Target);
1830
1831private:
1832  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1833
1834  // Return the ObjC type encoding for a given type.
1835  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
1836                                  bool ExpandPointedToStructures,
1837                                  bool ExpandStructures,
1838                                  const FieldDecl *Field,
1839                                  bool OutermostType = false,
1840                                  bool EncodingProperty = false,
1841                                  bool StructField = false,
1842                                  bool EncodeBlockParameters = false,
1843                                  bool EncodeClassNames = false) const;
1844
1845  // Adds the encoding of the structure's members.
1846  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
1847                                       const FieldDecl *Field,
1848                                       bool includeVBases = true) const;
1849
1850  // Adds the encoding of a method parameter or return type.
1851  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
1852                                         QualType T, std::string& S,
1853                                         bool Extended) const;
1854
1855  const ASTRecordLayout &
1856  getObjCLayout(const ObjCInterfaceDecl *D,
1857                const ObjCImplementationDecl *Impl) const;
1858
1859private:
1860  /// \brief A set of deallocations that should be performed when the
1861  /// ASTContext is destroyed.
1862  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
1863
1864  // FIXME: This currently contains the set of StoredDeclMaps used
1865  // by DeclContext objects.  This probably should not be in ASTContext,
1866  // but we include it here so that ASTContext can quickly deallocate them.
1867  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
1868
1869  /// \brief A counter used to uniquely identify "blocks".
1870  mutable unsigned int UniqueBlockByRefTypeID;
1871
1872  friend class DeclContext;
1873  friend class DeclarationNameTable;
1874  void ReleaseDeclContextMaps();
1875};
1876
1877/// @brief Utility function for constructing a nullary selector.
1878static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
1879  IdentifierInfo* II = &Ctx.Idents.get(name);
1880  return Ctx.Selectors.getSelector(0, &II);
1881}
1882
1883/// @brief Utility function for constructing an unary selector.
1884static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
1885  IdentifierInfo* II = &Ctx.Idents.get(name);
1886  return Ctx.Selectors.getSelector(1, &II);
1887}
1888
1889}  // end namespace clang
1890
1891// operator new and delete aren't allowed inside namespaces.
1892// The throw specifications are mandated by the standard.
1893/// @brief Placement new for using the ASTContext's allocator.
1894///
1895/// This placement form of operator new uses the ASTContext's allocator for
1896/// obtaining memory. It is a non-throwing new, which means that it returns
1897/// null on error. (If that is what the allocator does. The current does, so if
1898/// this ever changes, this operator will have to be changed, too.)
1899/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1900/// @code
1901/// // Default alignment (8)
1902/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
1903/// // Specific alignment
1904/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
1905/// @endcode
1906/// Please note that you cannot use delete on the pointer; it must be
1907/// deallocated using an explicit destructor call followed by
1908/// @c Context.Deallocate(Ptr).
1909///
1910/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1911/// @param C The ASTContext that provides the allocator.
1912/// @param Alignment The alignment of the allocated memory (if the underlying
1913///                  allocator supports it).
1914/// @return The allocated memory. Could be NULL.
1915inline void *operator new(size_t Bytes, const clang::ASTContext &C,
1916                          size_t Alignment) throw () {
1917  return C.Allocate(Bytes, Alignment);
1918}
1919/// @brief Placement delete companion to the new above.
1920///
1921/// This operator is just a companion to the new above. There is no way of
1922/// invoking it directly; see the new operator for more details. This operator
1923/// is called implicitly by the compiler if a placement new expression using
1924/// the ASTContext throws in the object constructor.
1925inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t)
1926              throw () {
1927  C.Deallocate(Ptr);
1928}
1929
1930/// This placement form of operator new[] uses the ASTContext's allocator for
1931/// obtaining memory. It is a non-throwing new[], which means that it returns
1932/// null on error.
1933/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1934/// @code
1935/// // Default alignment (8)
1936/// char *data = new (Context) char[10];
1937/// // Specific alignment
1938/// char *data = new (Context, 4) char[10];
1939/// @endcode
1940/// Please note that you cannot use delete on the pointer; it must be
1941/// deallocated using an explicit destructor call followed by
1942/// @c Context.Deallocate(Ptr).
1943///
1944/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1945/// @param C The ASTContext that provides the allocator.
1946/// @param Alignment The alignment of the allocated memory (if the underlying
1947///                  allocator supports it).
1948/// @return The allocated memory. Could be NULL.
1949inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
1950                            size_t Alignment = 8) throw () {
1951  return C.Allocate(Bytes, Alignment);
1952}
1953
1954/// @brief Placement delete[] companion to the new[] above.
1955///
1956/// This operator is just a companion to the new[] above. There is no way of
1957/// invoking it directly; see the new[] operator for more details. This operator
1958/// is called implicitly by the compiler if a placement new[] expression using
1959/// the ASTContext throws in the object constructor.
1960inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t)
1961              throw () {
1962  C.Deallocate(Ptr);
1963}
1964
1965#endif
1966