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