ASTContext.h revision d99cbe66403ee39c2ee58024b9582b95649a4fc5
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 jmp_buf type.
134  TypeDecl *jmp_bufDecl;
135
136  /// \brief The type for the C sigjmp_buf 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
514  /// \brief Retrieve the C jmp_buf type.
515  QualType getjmp_bufType() {
516    if (jmp_bufDecl)
517      return getTypeDeclType(jmp_bufDecl);
518    return QualType();
519  }
520
521  /// \brief Set the type for the C sigjmp_buf type.
522  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
523    this->sigjmp_bufDecl = sigjmp_bufDecl;
524  }
525
526  /// \brief Retrieve the C sigjmp_buf type.
527  QualType getsigjmp_bufType() {
528    if (sigjmp_bufDecl)
529      return getTypeDeclType(sigjmp_bufDecl);
530    return QualType();
531  }
532
533  /// getObjCEncodingForType - Emit the ObjC type encoding for the
534  /// given type into \arg S. If \arg NameFields is specified then
535  /// record field names are also encoded.
536  void getObjCEncodingForType(QualType t, std::string &S,
537                              const FieldDecl *Field=0);
538
539  void getLegacyIntegralTypeEncoding(QualType &t) const;
540
541  // Put the string version of type qualifiers into S.
542  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
543                                       std::string &S) const;
544
545  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
546  /// declaration.
547  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
548
549  /// getObjCEncodingForPropertyDecl - Return the encoded type for
550  /// this method declaration. If non-NULL, Container must be either
551  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
552  /// only be NULL when getting encodings for protocol properties.
553  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
554                                      const Decl *Container,
555                                      std::string &S);
556
557  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
558  /// purpose.
559  int getObjCEncodingTypeSize(QualType t);
560
561  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
562  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
563  QualType getObjCIdType() const { return ObjCIdTypedefType; }
564  void setObjCIdType(QualType T);
565
566  void setObjCSelType(QualType T);
567  QualType getObjCSelType() const { return ObjCSelType; }
568
569  void setObjCProtoType(QualType QT);
570  QualType getObjCProtoType() const { return ObjCProtoType; }
571
572  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
573  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
574  /// struct.
575  QualType getObjCClassType() const { return ObjCClassTypedefType; }
576  void setObjCClassType(QualType T);
577
578  void setBuiltinVaListType(QualType T);
579  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
580
581  QualType getFixedWidthIntType(unsigned Width, bool Signed);
582
583  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
584                                        bool TemplateKeyword,
585                                        TemplateDecl *Template);
586  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
587                                        bool TemplateKeyword,
588                                        OverloadedFunctionDecl *Template);
589
590  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
591                                        const IdentifierInfo *Name);
592
593  enum GetBuiltinTypeError {
594    GE_None,              //< No error
595    GE_Missing_stdio,     //< Missing a type from <stdio.h>
596    GE_Missing_setjmp     //< Missing a type from <setjmp.h>
597  };
598
599  /// GetBuiltinType - Return the type for the specified builtin.
600  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error);
601
602private:
603  QualType getFromTargetType(unsigned Type) const;
604
605  //===--------------------------------------------------------------------===//
606  //                         Type Predicates.
607  //===--------------------------------------------------------------------===//
608
609public:
610  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
611  /// garbage collection attribute.
612  ///
613  QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const;
614
615  /// isObjCNSObjectType - Return true if this is an NSObject object with
616  /// its NSObject attribute set.
617  bool isObjCNSObjectType(QualType Ty) const;
618
619  //===--------------------------------------------------------------------===//
620  //                         Type Sizing and Analysis
621  //===--------------------------------------------------------------------===//
622
623  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
624  /// scalar floating point type.
625  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
626
627  /// getTypeInfo - Get the size and alignment of the specified complete type in
628  /// bits.
629  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
630  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
631    return getTypeInfo(T.getTypePtr());
632  }
633
634  /// getTypeSize - Return the size of the specified type, in bits.  This method
635  /// does not work on incomplete types.
636  uint64_t getTypeSize(QualType T) {
637    return getTypeInfo(T).first;
638  }
639  uint64_t getTypeSize(const Type *T) {
640    return getTypeInfo(T).first;
641  }
642
643  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
644  /// This method does not work on incomplete types.
645  unsigned getTypeAlign(QualType T) {
646    return getTypeInfo(T).second;
647  }
648  unsigned getTypeAlign(const Type *T) {
649    return getTypeInfo(T).second;
650  }
651
652  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
653  /// type for the current target in bits.  This can be different than the ABI
654  /// alignment in cases where it is beneficial for performance to overalign
655  /// a data type.
656  unsigned getPreferredTypeAlign(const Type *T);
657
658  /// getDeclAlignInBytes - Return the alignment of the specified decl
659  /// that should be returned by __alignof().  Note that bitfields do
660  /// not have a valid alignment, so this method will assert on them.
661  unsigned getDeclAlignInBytes(const Decl *D);
662
663  /// getASTRecordLayout - Get or compute information about the layout of the
664  /// specified record (struct/union/class), which indicates its size and field
665  /// position information.
666  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
667
668  /// getASTObjCInterfaceLayout - Get or compute information about the
669  /// layout of the specified Objective-C interface.
670  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
671
672  /// getASTObjCImplementationLayout - Get or compute information about
673  /// the layout of the specified Objective-C implementation. This may
674  /// differ from the interface if synthesized ivars are present.
675  const ASTRecordLayout &
676  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
677
678  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
679                        llvm::SmallVectorImpl<FieldDecl*> &Fields);
680
681  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
682                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
683                               bool CollectSynthesized = true);
684  void CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
685                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
686  void CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
687                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
688  unsigned CountSynthesizedIvars(const ObjCInterfaceDecl *OI);
689  unsigned CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD);
690
691  //===--------------------------------------------------------------------===//
692  //                            Type Operators
693  //===--------------------------------------------------------------------===//
694
695  /// getCanonicalType - Return the canonical (structural) type corresponding to
696  /// the specified potentially non-canonical type.  The non-canonical version
697  /// of a type may have many "decorated" versions of types.  Decorators can
698  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
699  /// to be free of any of these, allowing two canonical types to be compared
700  /// for exact equality with a simple pointer comparison.
701  QualType getCanonicalType(QualType T);
702  const Type *getCanonicalType(const Type *T) {
703    return T->getCanonicalTypeInternal().getTypePtr();
704  }
705
706  /// \brief Determine whether the given types are equivalent.
707  bool hasSameType(QualType T1, QualType T2) {
708    return getCanonicalType(T1) == getCanonicalType(T2);
709  }
710
711  /// \brief Determine whether the given types are equivalent after
712  /// cvr-qualifiers have been removed.
713  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
714    T1 = getCanonicalType(T1);
715    T2 = getCanonicalType(T2);
716    return T1.getUnqualifiedType() == T2.getUnqualifiedType();
717  }
718
719  /// \brief Retrieves the "canonical" declaration of
720
721  /// \brief Retrieves the "canonical" nested name specifier for a
722  /// given nested name specifier.
723  ///
724  /// The canonical nested name specifier is a nested name specifier
725  /// that uniquely identifies a type or namespace within the type
726  /// system. For example, given:
727  ///
728  /// \code
729  /// namespace N {
730  ///   struct S {
731  ///     template<typename T> struct X { typename T* type; };
732  ///   };
733  /// }
734  ///
735  /// template<typename T> struct Y {
736  ///   typename N::S::X<T>::type member;
737  /// };
738  /// \endcode
739  ///
740  /// Here, the nested-name-specifier for N::S::X<T>:: will be
741  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
742  /// by declarations in the type system and the canonical type for
743  /// the template type parameter 'T' is template-param-0-0.
744  NestedNameSpecifier *
745  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
746
747  /// \brief Retrieves the "canonical" template name that refers to a
748  /// given template.
749  ///
750  /// The canonical template name is the simplest expression that can
751  /// be used to refer to a given template. For most templates, this
752  /// expression is just the template declaration itself. For example,
753  /// the template std::vector can be referred to via a variety of
754  /// names---std::vector, ::std::vector, vector (if vector is in
755  /// scope), etc.---but all of these names map down to the same
756  /// TemplateDecl, which is used to form the canonical template name.
757  ///
758  /// Dependent template names are more interesting. Here, the
759  /// template name could be something like T::template apply or
760  /// std::allocator<T>::template rebind, where the nested name
761  /// specifier itself is dependent. In this case, the canonical
762  /// template name uses the shortest form of the dependent
763  /// nested-name-specifier, which itself contains all canonical
764  /// types, values, and templates.
765  TemplateName getCanonicalTemplateName(TemplateName Name);
766
767  /// \brief Retrieve the "canonical" template argument.
768  ///
769  /// The canonical template argument is the simplest template argument
770  /// (which may be a type, value, expression, or declaration) that
771  /// expresses the value of the argument.
772  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg);
773
774  /// Type Query functions.  If the type is an instance of the specified class,
775  /// return the Type pointer for the underlying maximally pretty type.  This
776  /// is a member of ASTContext because this may need to do some amount of
777  /// canonicalization, e.g. to move type qualifiers into the element type.
778  const ArrayType *getAsArrayType(QualType T);
779  const ConstantArrayType *getAsConstantArrayType(QualType T) {
780    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
781  }
782  const VariableArrayType *getAsVariableArrayType(QualType T) {
783    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
784  }
785  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
786    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
787  }
788
789  /// getBaseElementType - Returns the innermost element type of a variable
790  /// length array type. For example, will return "int" for int[m][n]
791  QualType getBaseElementType(const VariableArrayType *VAT);
792
793  /// getBaseElementType - Returns the innermost element type of a type
794  /// (which needn't actually be an array type).
795  QualType getBaseElementType(QualType QT);
796
797  /// getArrayDecayedType - Return the properly qualified result of decaying the
798  /// specified array type to a pointer.  This operation is non-trivial when
799  /// handling typedefs etc.  The canonical type of "T" must be an array type,
800  /// this returns a pointer to a properly qualified element of the array.
801  ///
802  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
803  QualType getArrayDecayedType(QualType T);
804
805  /// getIntegerTypeOrder - Returns the highest ranked integer type:
806  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
807  /// LHS < RHS, return -1.
808  int getIntegerTypeOrder(QualType LHS, QualType RHS);
809
810  /// getFloatingTypeOrder - Compare the rank of the two specified floating
811  /// point types, ignoring the domain of the type (i.e. 'double' ==
812  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
813  /// LHS < RHS, return -1.
814  int getFloatingTypeOrder(QualType LHS, QualType RHS);
815
816  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
817  /// point or a complex type (based on typeDomain/typeSize).
818  /// 'typeDomain' is a real floating point or complex type.
819  /// 'typeSize' is a real floating point or complex type.
820  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
821                                             QualType typeDomain) const;
822
823private:
824  // Helper for integer ordering
825  unsigned getIntegerRank(Type* T);
826
827public:
828
829  //===--------------------------------------------------------------------===//
830  //                    Type Compatibility Predicates
831  //===--------------------------------------------------------------------===//
832
833  /// Compatibility predicates used to check assignment expressions.
834  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
835
836  bool isObjCIdType(QualType T) const {
837    return T == ObjCIdTypedefType;
838  }
839  bool isObjCClassType(QualType T) const {
840    return T == ObjCClassTypedefType;
841  }
842  bool isObjCSelType(QualType T) const {
843    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
844    return T->getAsStructureType() == SelStructType;
845  }
846  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
847  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
848                                         bool ForCompare);
849
850  // Check the safety of assignment from LHS to RHS
851  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
852                               const ObjCObjectPointerType *RHSOPT);
853  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
854                               const ObjCInterfaceType *RHS);
855  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
856
857  // Functions for calculating composite types
858  QualType mergeTypes(QualType, QualType);
859  QualType mergeFunctionTypes(QualType, QualType);
860
861  //===--------------------------------------------------------------------===//
862  //                    Integer Predicates
863  //===--------------------------------------------------------------------===//
864
865  // The width of an integer, as defined in C99 6.2.6.2. This is the number
866  // of bits in an integer type excluding any padding bits.
867  unsigned getIntWidth(QualType T);
868
869  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
870  // unsigned integer type.  This method takes a signed type, and returns the
871  // corresponding unsigned integer type.
872  QualType getCorrespondingUnsignedType(QualType T);
873
874  //===--------------------------------------------------------------------===//
875  //                    Type Iterators.
876  //===--------------------------------------------------------------------===//
877
878  typedef std::vector<Type*>::iterator       type_iterator;
879  typedef std::vector<Type*>::const_iterator const_type_iterator;
880
881  type_iterator types_begin() { return Types.begin(); }
882  type_iterator types_end() { return Types.end(); }
883  const_type_iterator types_begin() const { return Types.begin(); }
884  const_type_iterator types_end() const { return Types.end(); }
885
886  //===--------------------------------------------------------------------===//
887  //                    Integer Values
888  //===--------------------------------------------------------------------===//
889
890  /// MakeIntValue - Make an APSInt of the appropriate width and
891  /// signedness for the given \arg Value and integer \arg Type.
892  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
893    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
894    Res = Value;
895    return Res;
896  }
897
898  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
899  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
900  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
901  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
902
903  /// \brief Set the implementation of ObjCInterfaceDecl.
904  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
905                             ObjCImplementationDecl *ImplD);
906  /// \brief Set the implementation of ObjCCategoryDecl.
907  void setObjCImplementation(ObjCCategoryDecl *CatD,
908                             ObjCCategoryImplDecl *ImplD);
909
910private:
911  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
912  void operator=(const ASTContext&); // DO NOT IMPLEMENT
913
914  void InitBuiltinTypes();
915  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
916
917  // Return the ObjC type encoding for a given type.
918  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
919                                  bool ExpandPointedToStructures,
920                                  bool ExpandStructures,
921                                  const FieldDecl *Field,
922                                  bool OutermostType = false,
923                                  bool EncodingProperty = false);
924
925  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
926                                       const ObjCImplementationDecl *Impl);
927};
928
929}  // end namespace clang
930
931// operator new and delete aren't allowed inside namespaces.
932// The throw specifications are mandated by the standard.
933/// @brief Placement new for using the ASTContext's allocator.
934///
935/// This placement form of operator new uses the ASTContext's allocator for
936/// obtaining memory. It is a non-throwing new, which means that it returns
937/// null on error. (If that is what the allocator does. The current does, so if
938/// this ever changes, this operator will have to be changed, too.)
939/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
940/// @code
941/// // Default alignment (16)
942/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
943/// // Specific alignment
944/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
945/// @endcode
946/// Please note that you cannot use delete on the pointer; it must be
947/// deallocated using an explicit destructor call followed by
948/// @c Context.Deallocate(Ptr).
949///
950/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
951/// @param C The ASTContext that provides the allocator.
952/// @param Alignment The alignment of the allocated memory (if the underlying
953///                  allocator supports it).
954/// @return The allocated memory. Could be NULL.
955inline void *operator new(size_t Bytes, clang::ASTContext &C,
956                          size_t Alignment) throw () {
957  return C.Allocate(Bytes, Alignment);
958}
959/// @brief Placement delete companion to the new above.
960///
961/// This operator is just a companion to the new above. There is no way of
962/// invoking it directly; see the new operator for more details. This operator
963/// is called implicitly by the compiler if a placement new expression using
964/// the ASTContext throws in the object constructor.
965inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
966              throw () {
967  C.Deallocate(Ptr);
968}
969
970/// This placement form of operator new[] uses the ASTContext's allocator for
971/// obtaining memory. It is a non-throwing new[], which means that it returns
972/// null on error.
973/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
974/// @code
975/// // Default alignment (16)
976/// char *data = new (Context) char[10];
977/// // Specific alignment
978/// char *data = new (Context, 8) char[10];
979/// @endcode
980/// Please note that you cannot use delete on the pointer; it must be
981/// deallocated using an explicit destructor call followed by
982/// @c Context.Deallocate(Ptr).
983///
984/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
985/// @param C The ASTContext that provides the allocator.
986/// @param Alignment The alignment of the allocated memory (if the underlying
987///                  allocator supports it).
988/// @return The allocated memory. Could be NULL.
989inline void *operator new[](size_t Bytes, clang::ASTContext& C,
990                            size_t Alignment = 16) throw () {
991  return C.Allocate(Bytes, Alignment);
992}
993
994/// @brief Placement delete[] companion to the new[] above.
995///
996/// This operator is just a companion to the new[] above. There is no way of
997/// invoking it directly; see the new[] operator for more details. This operator
998/// is called implicitly by the compiler if a placement new[] expression using
999/// the ASTContext throws in the object constructor.
1000inline void operator delete[](void *Ptr, clang::ASTContext &C) throw () {
1001  C.Deallocate(Ptr);
1002}
1003
1004#endif
1005