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