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