ASTContext.h revision 50d62d1b4a98adbc83de8f8cd1379ea1c25656f7
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/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/PrettyPrinter.h"
23#include "clang/AST/TemplateName.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/CanonicalType.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/OwningPtr.h"
29#include "llvm/Support/Allocator.h"
30#include <vector>
31
32namespace llvm {
33  struct fltSemantics;
34}
35
36namespace clang {
37  class FileManager;
38  class ASTRecordLayout;
39  class Expr;
40  class ExternalASTSource;
41  class IdentifierTable;
42  class SelectorTable;
43  class SourceManager;
44  class TargetInfo;
45  // Decls
46  class Decl;
47  class ObjCPropertyDecl;
48  class RecordDecl;
49  class TagDecl;
50  class TranslationUnitDecl;
51  class TypeDecl;
52  class TypedefDecl;
53  class TemplateTypeParmDecl;
54  class FieldDecl;
55  class ObjCIvarRefExpr;
56  class ObjCIvarDecl;
57
58  namespace Builtin { class Context; }
59
60/// ASTContext - This class holds long-lived AST nodes (such as types and
61/// decls) that can be referred to throughout the semantic analysis of a file.
62class ASTContext {
63  std::vector<Type*> Types;
64  llvm::FoldingSet<ExtQualType> ExtQualTypes;
65  llvm::FoldingSet<ComplexType> ComplexTypes;
66  llvm::FoldingSet<PointerType> PointerTypes;
67  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
68  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
69  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
70  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
71  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
72  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
73  std::vector<VariableArrayType*> VariableArrayTypes;
74  llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
75  llvm::FoldingSet<DependentSizedExtVectorType> DependentSizedExtVectorTypes;
76  llvm::FoldingSet<VectorType> VectorTypes;
77  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
78  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
79  llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
80  llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
81  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
82  llvm::FoldingSet<TemplateSpecializationType> TemplateSpecializationTypes;
83  llvm::FoldingSet<QualifiedNameType> QualifiedNameTypes;
84  llvm::FoldingSet<TypenameType> TypenameTypes;
85  llvm::FoldingSet<ObjCInterfaceType> ObjCInterfaceTypes;
86  llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
87
88  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
89  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
90
91  /// \brief The set of nested name specifiers.
92  ///
93  /// This set is managed by the NestedNameSpecifier class.
94  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
95  NestedNameSpecifier *GlobalNestedNameSpecifier;
96  friend class NestedNameSpecifier;
97
98  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
99  ///  This is lazily created.  This is intentionally not serialized.
100  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
101  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
102
103  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
104  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
105
106  llvm::DenseMap<unsigned, FixedWidthIntType*> SignedFixedWidthIntTypes;
107  llvm::DenseMap<unsigned, FixedWidthIntType*> UnsignedFixedWidthIntTypes;
108
109  /// BuiltinVaListType - built-in va list type.
110  /// This is initially null and set by Sema::LazilyCreateBuiltin when
111  /// a builtin that takes a valist is encountered.
112  QualType BuiltinVaListType;
113
114  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
115  QualType ObjCIdTypedefType;
116
117  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
118  QualType ObjCSelType;
119  const RecordType *SelStructType;
120
121  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
122  QualType ObjCProtoType;
123  const RecordType *ProtoStructType;
124
125  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
126  QualType ObjCClassTypedefType;
127
128  QualType ObjCConstantStringType;
129  RecordDecl *CFConstantStringTypeDecl;
130
131  RecordDecl *ObjCFastEnumerationStateTypeDecl;
132
133  /// \brief The type for the C FILE type.
134  TypeDecl *FILEDecl;
135
136  /// \brief The type for the C jmp_buf type.
137  TypeDecl *jmp_bufDecl;
138
139  /// \brief The type for the C sigjmp_buf type.
140  TypeDecl *sigjmp_bufDecl;
141
142  /// \brief Keeps track of all declaration attributes.
143  ///
144  /// Since so few decls have attrs, we keep them in a hash map instead of
145  /// wasting space in the Decl class.
146  llvm::DenseMap<const Decl*, Attr*> DeclAttrs;
147
148  /// \brief Keeps track of the static data member templates from which
149  /// static data members of class template specializations were instantiated.
150  ///
151  /// This data structure stores the mapping from instantiations of static
152  /// data members to the static data member representations within the
153  /// class template from which they were instantiated.
154  ///
155  /// Given the following example:
156  ///
157  /// \code
158  /// template<typename T>
159  /// struct X {
160  ///   static T value;
161  /// };
162  ///
163  /// template<typename T>
164  ///   T X<T>::value = T(17);
165  ///
166  /// int *x = &X<int>::value;
167  /// \endcode
168  ///
169  /// This mapping will contain an entry that maps from the VarDecl for
170  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
171  /// class template X).
172  llvm::DenseMap<VarDecl *, VarDecl *> InstantiatedFromStaticDataMember;
173
174  TranslationUnitDecl *TUDecl;
175
176  /// SourceMgr - The associated SourceManager object.
177  SourceManager &SourceMgr;
178
179  /// LangOpts - The language options used to create the AST associated with
180  ///  this ASTContext object.
181  LangOptions LangOpts;
182
183  /// \brief Whether we have already loaded comment source ranges from an
184  /// external source.
185  bool LoadedExternalComments;
186
187  /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects.
188  bool FreeMemory;
189  llvm::MallocAllocator MallocAlloc;
190  llvm::BumpPtrAllocator BumpAlloc;
191
192  /// \brief Mapping from declarations to their comments, once we have
193  /// already looked up the comment associated with a given declaration.
194  llvm::DenseMap<const Decl *, std::string> DeclComments;
195
196public:
197  TargetInfo &Target;
198  IdentifierTable &Idents;
199  SelectorTable &Selectors;
200  Builtin::Context &BuiltinInfo;
201  DeclarationNameTable DeclarationNames;
202  llvm::OwningPtr<ExternalASTSource> ExternalSource;
203  clang::PrintingPolicy PrintingPolicy;
204
205  /// \brief Source ranges for all of the comments in the source file,
206  /// sorted in order of appearance in the translation unit.
207  std::vector<SourceRange> Comments;
208
209  SourceManager& getSourceManager() { return SourceMgr; }
210  const SourceManager& getSourceManager() const { return SourceMgr; }
211  void *Allocate(unsigned Size, unsigned Align = 8) {
212    return FreeMemory ? MallocAlloc.Allocate(Size, Align) :
213                        BumpAlloc.Allocate(Size, Align);
214  }
215  void Deallocate(void *Ptr) {
216    if (FreeMemory)
217      MallocAlloc.Deallocate(Ptr);
218  }
219  const LangOptions& getLangOptions() const { return LangOpts; }
220
221  FullSourceLoc getFullLoc(SourceLocation Loc) const {
222    return FullSourceLoc(Loc,SourceMgr);
223  }
224
225  /// \brief Retrieve the attributes for the given declaration.
226  Attr*& getDeclAttrs(const Decl *D) { return DeclAttrs[D]; }
227
228  /// \brief Erase the attributes corresponding to the given declaration.
229  void eraseDeclAttrs(const Decl *D) { DeclAttrs.erase(D); }
230
231  /// \brief If this variable is an instantiated static data member of a
232  /// class template specialization, returns the templated static data member
233  /// from which it was instantiated.
234  VarDecl *getInstantiatedFromStaticDataMember(VarDecl *Var);
235
236  /// \brief Note that the static data member \p Inst is an instantiation of
237  /// the static data member template \p Tmpl of a class template.
238  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl);
239
240  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
241
242  const char *getCommentForDecl(const Decl *D);
243
244  // Builtin Types.
245  QualType VoidTy;
246  QualType BoolTy;
247  QualType CharTy;
248  QualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
249  QualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
250  QualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
251  QualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
252  QualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
253  QualType UnsignedLongLongTy, UnsignedInt128Ty;
254  QualType FloatTy, DoubleTy, LongDoubleTy;
255  QualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
256  QualType VoidPtrTy, NullPtrTy;
257  QualType OverloadTy;
258  QualType DependentTy;
259  QualType UndeducedAutoTy;
260  QualType ObjCBuiltinIdTy, ObjCBuiltinClassTy;
261
262  ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
263             IdentifierTable &idents, SelectorTable &sels,
264             Builtin::Context &builtins,
265             bool FreeMemory = true, unsigned size_reserve=0);
266
267  ~ASTContext();
268
269  /// \brief Attach an external AST source to the AST context.
270  ///
271  /// The external AST source provides the ability to load parts of
272  /// the abstract syntax tree as needed from some external storage,
273  /// e.g., a precompiled header.
274  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
275
276  /// \brief Retrieve a pointer to the external AST source associated
277  /// with this AST context, if any.
278  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
279
280  void PrintStats() const;
281  const std::vector<Type*>& getTypes() const { return Types; }
282
283  //===--------------------------------------------------------------------===//
284  //                           Type Constructors
285  //===--------------------------------------------------------------------===//
286
287  /// getAddSpaceQualType - Return the uniqued reference to the type for an
288  /// address space qualified type with the specified type and address space.
289  /// The resulting type has a union of the qualifiers from T and the address
290  /// space. If T already has an address space specifier, it is silently
291  /// replaced.
292  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
293
294  /// getObjCGCQualType - Returns the uniqued reference to the type for an
295  /// objc gc qualified type. The retulting type has a union of the qualifiers
296  /// from T and the gc attribute.
297  QualType getObjCGCQualType(QualType T, QualType::GCAttrTypes gcAttr);
298
299  /// getNoReturnType - Add the noreturn attribute to the given type which must
300  /// be a FunctionType or a pointer to an allowable type or a BlockPointer.
301  QualType getNoReturnType(QualType T);
302
303  /// getComplexType - Return the uniqued reference to the type for a complex
304  /// number with the specified element type.
305  QualType getComplexType(QualType T);
306
307  /// getPointerType - Return the uniqued reference to the type for a pointer to
308  /// the specified type.
309  QualType getPointerType(QualType T);
310
311  /// getBlockPointerType - Return the uniqued reference to the type for a block
312  /// of the specified type.
313  QualType getBlockPointerType(QualType T);
314
315  /// getLValueReferenceType - Return the uniqued reference to the type for an
316  /// lvalue reference to the specified type.
317  QualType getLValueReferenceType(QualType T);
318
319  /// getRValueReferenceType - Return the uniqued reference to the type for an
320  /// rvalue reference to the specified type.
321  QualType getRValueReferenceType(QualType T);
322
323  /// getMemberPointerType - Return the uniqued reference to the type for a
324  /// member pointer to the specified type in the specified class. The class
325  /// is a Type because it could be a dependent name.
326  QualType getMemberPointerType(QualType T, const Type *Cls);
327
328  /// getVariableArrayType - Returns a non-unique reference to the type for a
329  /// variable array of the specified element type.
330  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
331                                ArrayType::ArraySizeModifier ASM,
332                                unsigned EltTypeQuals,
333                                SourceRange Brackets);
334
335  /// getDependentSizedArrayType - Returns a non-unique reference to
336  /// the type for a dependently-sized array of the specified element
337  /// type. FIXME: We will need these to be uniqued, or at least
338  /// comparable, at some point.
339  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
340                                      ArrayType::ArraySizeModifier ASM,
341                                      unsigned EltTypeQuals,
342                                      SourceRange Brackets);
343
344  /// getIncompleteArrayType - Returns a unique reference to the type for a
345  /// incomplete array of the specified element type.
346  QualType getIncompleteArrayType(QualType EltTy,
347                                  ArrayType::ArraySizeModifier ASM,
348                                  unsigned EltTypeQuals);
349
350  /// getConstantArrayType - Return the unique reference to the type for a
351  /// constant array of the specified element type.
352  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
353                                ArrayType::ArraySizeModifier ASM,
354                                unsigned EltTypeQuals);
355
356  /// getConstantArrayWithExprType - Return a reference to the type for a
357  /// constant array of the specified element type.
358  QualType getConstantArrayWithExprType(QualType EltTy,
359                                        const llvm::APInt &ArySize,
360                                        Expr *ArySizeExpr,
361                                        ArrayType::ArraySizeModifier ASM,
362                                        unsigned EltTypeQuals,
363                                        SourceRange Brackets);
364
365  /// getConstantArrayWithoutExprType - Return a reference to the type
366  /// for a constant array of the specified element type.
367  QualType getConstantArrayWithoutExprType(QualType EltTy,
368                                           const llvm::APInt &ArySize,
369                                           ArrayType::ArraySizeModifier ASM,
370                                           unsigned EltTypeQuals);
371
372  /// getVectorType - Return the unique reference to a vector type of
373  /// the specified element type and size. VectorType must be a built-in type.
374  QualType getVectorType(QualType VectorType, unsigned NumElts);
375
376  /// getExtVectorType - Return the unique reference to an extended vector type
377  /// of the specified element type and size.  VectorType must be a built-in
378  /// type.
379  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
380
381  /// getDependentSizedExtVectorType - Returns a non-unique reference to
382  /// the type for a dependently-sized vector of the specified element
383  /// type. FIXME: We will need these to be uniqued, or at least
384  /// comparable, at some point.
385  QualType getDependentSizedExtVectorType(QualType VectorType,
386                                          Expr *SizeExpr,
387                                          SourceLocation AttrLoc);
388
389  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
390  ///
391  QualType getFunctionNoProtoType(QualType ResultTy, bool NoReturn = false);
392
393  /// getFunctionType - Return a normal function type with a typed argument
394  /// list.  isVariadic indicates whether the argument list includes '...'.
395  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
396                           unsigned NumArgs, bool isVariadic,
397                           unsigned TypeQuals, bool hasExceptionSpec = false,
398                           bool hasAnyExceptionSpec = false,
399                           unsigned NumExs = 0, const QualType *ExArray = 0,
400                           bool NoReturn = false);
401
402  /// getTypeDeclType - Return the unique reference to the type for
403  /// the specified type declaration.
404  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
405
406  /// getTypedefType - Return the unique reference to the type for the
407  /// specified typename decl.
408  QualType getTypedefType(TypedefDecl *Decl);
409
410  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
411                                   bool ParameterPack,
412                                   IdentifierInfo *Name = 0);
413
414  QualType getTemplateSpecializationType(TemplateName T,
415                                         const TemplateArgument *Args,
416                                         unsigned NumArgs,
417                                         QualType Canon = QualType());
418
419  QualType getQualifiedNameType(NestedNameSpecifier *NNS,
420                                QualType NamedType);
421  QualType getTypenameType(NestedNameSpecifier *NNS,
422                           const IdentifierInfo *Name,
423                           QualType Canon = QualType());
424  QualType getTypenameType(NestedNameSpecifier *NNS,
425                           const TemplateSpecializationType *TemplateId,
426                           QualType Canon = QualType());
427
428  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
429                                ObjCProtocolDecl **Protocols = 0,
430                                unsigned NumProtocols = 0);
431
432  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for the
433  /// given interface decl and the conforming protocol list.
434  QualType getObjCObjectPointerType(QualType OIT,
435                                    ObjCProtocolDecl **ProtocolList = 0,
436                                    unsigned NumProtocols = 0);
437
438  /// getTypeOfType - GCC extension.
439  QualType getTypeOfExprType(Expr *e);
440  QualType getTypeOfType(QualType t);
441
442  /// getDecltypeType - C++0x decltype.
443  QualType getDecltypeType(Expr *e);
444
445  /// getTagDeclType - Return the unique reference to the type for the
446  /// specified TagDecl (struct/union/class/enum) decl.
447  QualType getTagDeclType(TagDecl *Decl);
448
449  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
450  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
451  QualType getSizeType() const;
452
453  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
454  /// returns a type compatible with the type defined in <stddef.h> as defined
455  /// by the target.
456  QualType getWCharType() const { return WCharTy; }
457
458  /// getSignedWCharType - Return the type of "signed wchar_t".
459  /// Used when in C++, as a GCC extension.
460  QualType getSignedWCharType() const;
461
462  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
463  /// Used when in C++, as a GCC extension.
464  QualType getUnsignedWCharType() const;
465
466  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
467  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
468  QualType getPointerDiffType() const;
469
470  // getCFConstantStringType - Return the C structure type used to represent
471  // constant CFStrings.
472  QualType getCFConstantStringType();
473
474  /// Get the structure type used to representation CFStrings, or NULL
475  /// if it hasn't yet been built.
476  QualType getRawCFConstantStringType() {
477    if (CFConstantStringTypeDecl)
478      return getTagDeclType(CFConstantStringTypeDecl);
479    return QualType();
480  }
481  void setCFConstantStringType(QualType T);
482
483  // This setter/getter represents the ObjC type for an NSConstantString.
484  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
485  QualType getObjCConstantStringInterface() const {
486    return ObjCConstantStringType;
487  }
488
489  //// This gets the struct used to keep track of fast enumerations.
490  QualType getObjCFastEnumerationStateType();
491
492  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
493  /// been built.
494  QualType getRawObjCFastEnumerationStateType() {
495    if (ObjCFastEnumerationStateTypeDecl)
496      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
497    return QualType();
498  }
499
500  void setObjCFastEnumerationStateType(QualType T);
501
502  /// \brief Set the type for the C FILE type.
503  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
504
505  /// \brief Retrieve the C FILE type.
506  QualType getFILEType() {
507    if (FILEDecl)
508      return getTypeDeclType(FILEDecl);
509    return QualType();
510  }
511
512  /// \brief Set the type for the C jmp_buf type.
513  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
514    this->jmp_bufDecl = jmp_bufDecl;
515  }
516
517  /// \brief Retrieve the C jmp_buf type.
518  QualType getjmp_bufType() {
519    if (jmp_bufDecl)
520      return getTypeDeclType(jmp_bufDecl);
521    return QualType();
522  }
523
524  /// \brief Set the type for the C sigjmp_buf type.
525  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
526    this->sigjmp_bufDecl = sigjmp_bufDecl;
527  }
528
529  /// \brief Retrieve the C sigjmp_buf type.
530  QualType getsigjmp_bufType() {
531    if (sigjmp_bufDecl)
532      return getTypeDeclType(sigjmp_bufDecl);
533    return QualType();
534  }
535
536  /// getObjCEncodingForType - Emit the ObjC type encoding for the
537  /// given type into \arg S. If \arg NameFields is specified then
538  /// record field names are also encoded.
539  void getObjCEncodingForType(QualType t, std::string &S,
540                              const FieldDecl *Field=0);
541
542  void getLegacyIntegralTypeEncoding(QualType &t) const;
543
544  // Put the string version of type qualifiers into S.
545  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
546                                       std::string &S) const;
547
548  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
549  /// declaration.
550  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
551
552  /// getObjCEncodingForPropertyDecl - Return the encoded type for
553  /// this method declaration. If non-NULL, Container must be either
554  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
555  /// only be NULL when getting encodings for protocol properties.
556  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
557                                      const Decl *Container,
558                                      std::string &S);
559
560  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
561  /// purpose.
562  int getObjCEncodingTypeSize(QualType t);
563
564  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
565  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
566  QualType getObjCIdType() const { return ObjCIdTypedefType; }
567  void setObjCIdType(QualType T);
568
569  void setObjCSelType(QualType T);
570  QualType getObjCSelType() const { return ObjCSelType; }
571
572  void setObjCProtoType(QualType QT);
573  QualType getObjCProtoType() const { return ObjCProtoType; }
574
575  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
576  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
577  /// struct.
578  QualType getObjCClassType() const { return ObjCClassTypedefType; }
579  void setObjCClassType(QualType T);
580
581  void setBuiltinVaListType(QualType T);
582  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
583
584  QualType getFixedWidthIntType(unsigned Width, bool Signed);
585
586  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
587                                        bool TemplateKeyword,
588                                        TemplateDecl *Template);
589  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
590                                        bool TemplateKeyword,
591                                        OverloadedFunctionDecl *Template);
592
593  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
594                                        const IdentifierInfo *Name);
595
596  enum GetBuiltinTypeError {
597    GE_None,              //< No error
598    GE_Missing_stdio,     //< Missing a type from <stdio.h>
599    GE_Missing_setjmp     //< Missing a type from <setjmp.h>
600  };
601
602  /// GetBuiltinType - Return the type for the specified builtin.
603  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error);
604
605private:
606  QualType getFromTargetType(unsigned Type) const;
607
608  //===--------------------------------------------------------------------===//
609  //                         Type Predicates.
610  //===--------------------------------------------------------------------===//
611
612public:
613  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
614  /// garbage collection attribute.
615  ///
616  QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const;
617
618  /// isObjCNSObjectType - Return true if this is an NSObject object with
619  /// its NSObject attribute set.
620  bool isObjCNSObjectType(QualType Ty) const;
621
622  //===--------------------------------------------------------------------===//
623  //                         Type Sizing and Analysis
624  //===--------------------------------------------------------------------===//
625
626  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
627  /// scalar floating point type.
628  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
629
630  /// getTypeInfo - Get the size and alignment of the specified complete type in
631  /// bits.
632  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
633  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
634    return getTypeInfo(T.getTypePtr());
635  }
636
637  /// getTypeSize - Return the size of the specified type, in bits.  This method
638  /// does not work on incomplete types.
639  uint64_t getTypeSize(QualType T) {
640    return getTypeInfo(T).first;
641  }
642  uint64_t getTypeSize(const Type *T) {
643    return getTypeInfo(T).first;
644  }
645
646  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
647  /// This method does not work on incomplete types.
648  unsigned getTypeAlign(QualType T) {
649    return getTypeInfo(T).second;
650  }
651  unsigned getTypeAlign(const Type *T) {
652    return getTypeInfo(T).second;
653  }
654
655  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
656  /// type for the current target in bits.  This can be different than the ABI
657  /// alignment in cases where it is beneficial for performance to overalign
658  /// a data type.
659  unsigned getPreferredTypeAlign(const Type *T);
660
661  /// getDeclAlignInBytes - Return the alignment of the specified decl
662  /// that should be returned by __alignof().  Note that bitfields do
663  /// not have a valid alignment, so this method will assert on them.
664  unsigned getDeclAlignInBytes(const Decl *D);
665
666  /// getASTRecordLayout - Get or compute information about the layout of the
667  /// specified record (struct/union/class), which indicates its size and field
668  /// position information.
669  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
670
671  /// getASTObjCInterfaceLayout - Get or compute information about the
672  /// layout of the specified Objective-C interface.
673  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
674
675  /// getASTObjCImplementationLayout - Get or compute information about
676  /// the layout of the specified Objective-C implementation. This may
677  /// differ from the interface if synthesized ivars are present.
678  const ASTRecordLayout &
679  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
680
681  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
682                        llvm::SmallVectorImpl<FieldDecl*> &Fields);
683
684  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
685                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
686                               bool CollectSynthesized = true);
687  void CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
688                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
689  void CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
690                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
691  unsigned CountSynthesizedIvars(const ObjCInterfaceDecl *OI);
692  unsigned CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD);
693
694  //===--------------------------------------------------------------------===//
695  //                            Type Operators
696  //===--------------------------------------------------------------------===//
697
698  /// getCanonicalType - Return the canonical (structural) type corresponding to
699  /// the specified potentially non-canonical type.  The non-canonical version
700  /// of a type may have many "decorated" versions of types.  Decorators can
701  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
702  /// to be free of any of these, allowing two canonical types to be compared
703  /// for exact equality with a simple pointer comparison.
704  CanQualType getCanonicalType(QualType T);
705  const Type *getCanonicalType(const Type *T) {
706    return T->getCanonicalTypeInternal().getTypePtr();
707  }
708
709  /// \brief Determine whether the given types are equivalent.
710  bool hasSameType(QualType T1, QualType T2) {
711    return getCanonicalType(T1) == getCanonicalType(T2);
712  }
713
714  /// \brief Determine whether the given types are equivalent after
715  /// cvr-qualifiers have been removed.
716  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
717    T1 = getCanonicalType(T1);
718    T2 = getCanonicalType(T2);
719    return T1.getUnqualifiedType() == T2.getUnqualifiedType();
720  }
721
722  /// \brief Retrieves the "canonical" declaration of
723
724  /// \brief Retrieves the "canonical" nested name specifier for a
725  /// given nested name specifier.
726  ///
727  /// The canonical nested name specifier is a nested name specifier
728  /// that uniquely identifies a type or namespace within the type
729  /// system. For example, given:
730  ///
731  /// \code
732  /// namespace N {
733  ///   struct S {
734  ///     template<typename T> struct X { typename T* type; };
735  ///   };
736  /// }
737  ///
738  /// template<typename T> struct Y {
739  ///   typename N::S::X<T>::type member;
740  /// };
741  /// \endcode
742  ///
743  /// Here, the nested-name-specifier for N::S::X<T>:: will be
744  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
745  /// by declarations in the type system and the canonical type for
746  /// the template type parameter 'T' is template-param-0-0.
747  NestedNameSpecifier *
748  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
749
750  /// \brief Retrieves the "canonical" template name that refers to a
751  /// given template.
752  ///
753  /// The canonical template name is the simplest expression that can
754  /// be used to refer to a given template. For most templates, this
755  /// expression is just the template declaration itself. For example,
756  /// the template std::vector can be referred to via a variety of
757  /// names---std::vector, ::std::vector, vector (if vector is in
758  /// scope), etc.---but all of these names map down to the same
759  /// TemplateDecl, which is used to form the canonical template name.
760  ///
761  /// Dependent template names are more interesting. Here, the
762  /// template name could be something like T::template apply or
763  /// std::allocator<T>::template rebind, where the nested name
764  /// specifier itself is dependent. In this case, the canonical
765  /// template name uses the shortest form of the dependent
766  /// nested-name-specifier, which itself contains all canonical
767  /// types, values, and templates.
768  TemplateName getCanonicalTemplateName(TemplateName Name);
769
770  /// \brief Retrieve the "canonical" template argument.
771  ///
772  /// The canonical template argument is the simplest template argument
773  /// (which may be a type, value, expression, or declaration) that
774  /// expresses the value of the argument.
775  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg);
776
777  /// Type Query functions.  If the type is an instance of the specified class,
778  /// return the Type pointer for the underlying maximally pretty type.  This
779  /// is a member of ASTContext because this may need to do some amount of
780  /// canonicalization, e.g. to move type qualifiers into the element type.
781  const ArrayType *getAsArrayType(QualType T);
782  const ConstantArrayType *getAsConstantArrayType(QualType T) {
783    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
784  }
785  const VariableArrayType *getAsVariableArrayType(QualType T) {
786    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
787  }
788  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
789    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
790  }
791
792  /// getBaseElementType - Returns the innermost element type of a variable
793  /// length array type. For example, will return "int" for int[m][n]
794  QualType getBaseElementType(const VariableArrayType *VAT);
795
796  /// getBaseElementType - Returns the innermost element type of a type
797  /// (which needn't actually be an array type).
798  QualType getBaseElementType(QualType QT);
799
800  /// getArrayDecayedType - Return the properly qualified result of decaying the
801  /// specified array type to a pointer.  This operation is non-trivial when
802  /// handling typedefs etc.  The canonical type of "T" must be an array type,
803  /// this returns a pointer to a properly qualified element of the array.
804  ///
805  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
806  QualType getArrayDecayedType(QualType T);
807
808  /// getIntegerTypeOrder - Returns the highest ranked integer type:
809  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
810  /// LHS < RHS, return -1.
811  int getIntegerTypeOrder(QualType LHS, QualType RHS);
812
813  /// getFloatingTypeOrder - Compare the rank of the two specified floating
814  /// point types, ignoring the domain of the type (i.e. 'double' ==
815  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
816  /// LHS < RHS, return -1.
817  int getFloatingTypeOrder(QualType LHS, QualType RHS);
818
819  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
820  /// point or a complex type (based on typeDomain/typeSize).
821  /// 'typeDomain' is a real floating point or complex type.
822  /// 'typeSize' is a real floating point or complex type.
823  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
824                                             QualType typeDomain) const;
825
826private:
827  // Helper for integer ordering
828  unsigned getIntegerRank(Type* T);
829
830public:
831
832  //===--------------------------------------------------------------------===//
833  //                    Type Compatibility Predicates
834  //===--------------------------------------------------------------------===//
835
836  /// Compatibility predicates used to check assignment expressions.
837  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
838
839  bool isObjCIdType(QualType T) const {
840    return T == ObjCIdTypedefType;
841  }
842  bool isObjCClassType(QualType T) const {
843    return T == ObjCClassTypedefType;
844  }
845  bool isObjCSelType(QualType T) const {
846    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
847    return T->getAsStructureType() == SelStructType;
848  }
849  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
850  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
851                                         bool ForCompare);
852
853  // Check the safety of assignment from LHS to RHS
854  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
855                               const ObjCObjectPointerType *RHSOPT);
856  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
857                               const ObjCInterfaceType *RHS);
858  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
859
860  // Functions for calculating composite types
861  QualType mergeTypes(QualType, QualType);
862  QualType mergeFunctionTypes(QualType, QualType);
863
864  //===--------------------------------------------------------------------===//
865  //                    Integer Predicates
866  //===--------------------------------------------------------------------===//
867
868  // The width of an integer, as defined in C99 6.2.6.2. This is the number
869  // of bits in an integer type excluding any padding bits.
870  unsigned getIntWidth(QualType T);
871
872  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
873  // unsigned integer type.  This method takes a signed type, and returns the
874  // corresponding unsigned integer type.
875  QualType getCorrespondingUnsignedType(QualType T);
876
877  //===--------------------------------------------------------------------===//
878  //                    Type Iterators.
879  //===--------------------------------------------------------------------===//
880
881  typedef std::vector<Type*>::iterator       type_iterator;
882  typedef std::vector<Type*>::const_iterator const_type_iterator;
883
884  type_iterator types_begin() { return Types.begin(); }
885  type_iterator types_end() { return Types.end(); }
886  const_type_iterator types_begin() const { return Types.begin(); }
887  const_type_iterator types_end() const { return Types.end(); }
888
889  //===--------------------------------------------------------------------===//
890  //                    Integer Values
891  //===--------------------------------------------------------------------===//
892
893  /// MakeIntValue - Make an APSInt of the appropriate width and
894  /// signedness for the given \arg Value and integer \arg Type.
895  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
896    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
897    Res = Value;
898    return Res;
899  }
900
901  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
902  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
903  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
904  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
905
906  /// \brief Set the implementation of ObjCInterfaceDecl.
907  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
908                             ObjCImplementationDecl *ImplD);
909  /// \brief Set the implementation of ObjCCategoryDecl.
910  void setObjCImplementation(ObjCCategoryDecl *CatD,
911                             ObjCCategoryImplDecl *ImplD);
912
913private:
914  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
915  void operator=(const ASTContext&); // DO NOT IMPLEMENT
916
917  void InitBuiltinTypes();
918  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
919
920  // Return the ObjC type encoding for a given type.
921  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
922                                  bool ExpandPointedToStructures,
923                                  bool ExpandStructures,
924                                  const FieldDecl *Field,
925                                  bool OutermostType = false,
926                                  bool EncodingProperty = false);
927
928  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
929                                       const ObjCImplementationDecl *Impl);
930};
931
932}  // end namespace clang
933
934// operator new and delete aren't allowed inside namespaces.
935// The throw specifications are mandated by the standard.
936/// @brief Placement new for using the ASTContext's allocator.
937///
938/// This placement form of operator new uses the ASTContext's allocator for
939/// obtaining memory. It is a non-throwing new, which means that it returns
940/// null on error. (If that is what the allocator does. The current does, so if
941/// this ever changes, this operator will have to be changed, too.)
942/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
943/// @code
944/// // Default alignment (16)
945/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
946/// // Specific alignment
947/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
948/// @endcode
949/// Please note that you cannot use delete on the pointer; it must be
950/// deallocated using an explicit destructor call followed by
951/// @c Context.Deallocate(Ptr).
952///
953/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
954/// @param C The ASTContext that provides the allocator.
955/// @param Alignment The alignment of the allocated memory (if the underlying
956///                  allocator supports it).
957/// @return The allocated memory. Could be NULL.
958inline void *operator new(size_t Bytes, clang::ASTContext &C,
959                          size_t Alignment) throw () {
960  return C.Allocate(Bytes, Alignment);
961}
962/// @brief Placement delete companion to the new above.
963///
964/// This operator is just a companion to the new above. There is no way of
965/// invoking it directly; see the new operator for more details. This operator
966/// is called implicitly by the compiler if a placement new expression using
967/// the ASTContext throws in the object constructor.
968inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
969              throw () {
970  C.Deallocate(Ptr);
971}
972
973/// This placement form of operator new[] uses the ASTContext's allocator for
974/// obtaining memory. It is a non-throwing new[], which means that it returns
975/// null on error.
976/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
977/// @code
978/// // Default alignment (16)
979/// char *data = new (Context) char[10];
980/// // Specific alignment
981/// char *data = new (Context, 8) char[10];
982/// @endcode
983/// Please note that you cannot use delete on the pointer; it must be
984/// deallocated using an explicit destructor call followed by
985/// @c Context.Deallocate(Ptr).
986///
987/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
988/// @param C The ASTContext that provides the allocator.
989/// @param Alignment The alignment of the allocated memory (if the underlying
990///                  allocator supports it).
991/// @return The allocated memory. Could be NULL.
992inline void *operator new[](size_t Bytes, clang::ASTContext& C,
993                            size_t Alignment = 16) throw () {
994  return C.Allocate(Bytes, Alignment);
995}
996
997/// @brief Placement delete[] companion to the new[] above.
998///
999/// This operator is just a companion to the new[] above. There is no way of
1000/// invoking it directly; see the new[] operator for more details. This operator
1001/// is called implicitly by the compiler if a placement new[] expression using
1002/// the ASTContext throws in the object constructor.
1003inline void operator delete[](void *Ptr, clang::ASTContext &C) throw () {
1004  C.Deallocate(Ptr);
1005}
1006
1007#endif
1008