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