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