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