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