ASTContext.h revision 557c5b1717bc8919b1b40cf2064b51491ec53a44
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/Builtins.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/SourceLocation.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/Bitcode/SerializationFwd.h"
27#include "llvm/Support/Allocator.h"
28#include <vector>
29
30namespace llvm {
31  struct fltSemantics;
32}
33
34namespace clang {
35  class FileManager;
36  class ASTRecordLayout;
37  class Expr;
38  class IdentifierTable;
39  class SelectorTable;
40  class SourceManager;
41  class TargetInfo;
42  // Decls
43  class Decl;
44  class ObjCPropertyDecl;
45  class RecordDecl;
46  class TagDecl;
47  class TranslationUnitDecl;
48  class TypeDecl;
49  class TypedefDecl;
50  class TemplateTypeParmDecl;
51  class FieldDecl;
52  class ObjCIvarRefExpr;
53  class ObjCIvarDecl;
54
55/// ASTContext - This class holds long-lived AST nodes (such as types and
56/// decls) that can be referred to throughout the semantic analysis of a file.
57class ASTContext {
58  std::vector<Type*> Types;
59  llvm::FoldingSet<ExtQualType> ExtQualTypes;
60  llvm::FoldingSet<ComplexType> ComplexTypes;
61  llvm::FoldingSet<PointerType> PointerTypes;
62  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
63  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
64  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
65  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
66  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
67  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
68  std::vector<VariableArrayType*> VariableArrayTypes;
69  std::vector<DependentSizedArrayType*> DependentSizedArrayTypes;
70  llvm::FoldingSet<VectorType> VectorTypes;
71  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
72  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
73  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
74  llvm::FoldingSet<ClassTemplateSpecializationType>
75    ClassTemplateSpecializationTypes;
76  llvm::FoldingSet<QualifiedNameType> QualifiedNameTypes;
77  llvm::FoldingSet<TypenameType> TypenameTypes;
78  llvm::FoldingSet<ObjCQualifiedInterfaceType> ObjCQualifiedInterfaceTypes;
79  llvm::FoldingSet<ObjCQualifiedIdType> ObjCQualifiedIdTypes;
80
81  /// \brief The set of nested name specifiers.
82  ///
83  /// This set is managed by the NestedNameSpecifier class.
84  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
85  NestedNameSpecifier *GlobalNestedNameSpecifier;
86  friend class NestedNameSpecifier;
87
88  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
89  ///  This is lazily created.  This is intentionally not serialized.
90  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
91  llvm::DenseMap<const ObjCInterfaceDecl*,
92                 const ASTRecordLayout*> ASTObjCInterfaces;
93
94  llvm::DenseMap<unsigned, FixedWidthIntType*> SignedFixedWidthIntTypes;
95  llvm::DenseMap<unsigned, FixedWidthIntType*> UnsignedFixedWidthIntTypes;
96
97  // FIXME: Shouldn't ASTRecordForInterface/ASTFieldForIvarRef and
98  // addRecordToClass/getFieldDecl be part of the backend (i.e. CodeGenTypes and
99  // CodeGenFunction)?
100  llvm::DenseMap<const ObjCInterfaceDecl*,
101                 const RecordDecl*> ASTRecordForInterface;
102  llvm::DenseMap<const ObjCIvarRefExpr*, const FieldDecl*> ASTFieldForIvarRef;
103
104  /// BuiltinVaListType - built-in va list type.
105  /// This is initially null and set by Sema::LazilyCreateBuiltin when
106  /// a builtin that takes a valist is encountered.
107  QualType BuiltinVaListType;
108
109  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
110  QualType ObjCIdType;
111  const RecordType *IdStructType;
112
113  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
114  QualType ObjCSelType;
115  const RecordType *SelStructType;
116
117  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
118  QualType ObjCProtoType;
119  const RecordType *ProtoStructType;
120
121  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
122  QualType ObjCClassType;
123  const RecordType *ClassStructType;
124
125  QualType ObjCConstantStringType;
126  RecordDecl *CFConstantStringTypeDecl;
127
128  RecordDecl *ObjCFastEnumerationStateTypeDecl;
129
130  TranslationUnitDecl *TUDecl;
131
132  /// SourceMgr - The associated SourceManager object.
133  SourceManager &SourceMgr;
134
135  /// LangOpts - The language options used to create the AST associated with
136  ///  this ASTContext object.
137  LangOptions LangOpts;
138
139  /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects.
140  bool FreeMemory;
141  llvm::MallocAllocator MallocAlloc;
142  llvm::BumpPtrAllocator BumpAlloc;
143public:
144  TargetInfo &Target;
145  IdentifierTable &Idents;
146  SelectorTable &Selectors;
147  DeclarationNameTable DeclarationNames;
148
149  SourceManager& getSourceManager() { return SourceMgr; }
150  const SourceManager& getSourceManager() const { return SourceMgr; }
151  void *Allocate(unsigned Size, unsigned Align = 8) {
152    return FreeMemory ? MallocAlloc.Allocate(Size, Align) :
153                        BumpAlloc.Allocate(Size, Align);
154  }
155  void Deallocate(void *Ptr) {
156    if (FreeMemory)
157      MallocAlloc.Deallocate(Ptr);
158  }
159  const LangOptions& getLangOptions() const { return LangOpts; }
160
161  FullSourceLoc getFullLoc(SourceLocation Loc) const {
162    return FullSourceLoc(Loc,SourceMgr);
163  }
164
165  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
166
167  /// This is intentionally not serialized.  It is populated by the
168  /// ASTContext ctor, and there are no external pointers/references to
169  /// internal variables of BuiltinInfo.
170  Builtin::Context BuiltinInfo;
171
172  // Builtin Types.
173  QualType VoidTy;
174  QualType BoolTy;
175  QualType CharTy;
176  QualType WCharTy; // [C++ 3.9.1p5], integer type in C99.
177  QualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy;
178  QualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
179  QualType UnsignedLongLongTy;
180  QualType FloatTy, DoubleTy, LongDoubleTy;
181  QualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
182  QualType VoidPtrTy;
183  QualType OverloadTy;
184  QualType DependentTy;
185
186  ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
187             IdentifierTable &idents, SelectorTable &sels,
188             bool FreeMemory = true, unsigned size_reserve=0);
189
190  ~ASTContext();
191
192  void PrintStats() const;
193  const std::vector<Type*>& getTypes() const { return Types; }
194
195  //===--------------------------------------------------------------------===//
196  //                           Type Constructors
197  //===--------------------------------------------------------------------===//
198
199  /// getAddSpaceQualType - Return the uniqued reference to the type for an
200  /// address space qualified type with the specified type and address space.
201  /// The resulting type has a union of the qualifiers from T and the address
202  /// space. If T already has an address space specifier, it is silently
203  /// replaced.
204  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
205
206  /// getObjCGCQualType - Returns the uniqued reference to the type for an
207  /// objc gc qualified type. The retulting type has a union of the qualifiers
208  /// from T and the gc attribute.
209  QualType getObjCGCQualType(QualType T, QualType::GCAttrTypes gcAttr);
210
211  /// getComplexType - Return the uniqued reference to the type for a complex
212  /// number with the specified element type.
213  QualType getComplexType(QualType T);
214
215  /// getPointerType - Return the uniqued reference to the type for a pointer to
216  /// the specified type.
217  QualType getPointerType(QualType T);
218
219  /// getBlockPointerType - Return the uniqued reference to the type for a block
220  /// of the specified type.
221  QualType getBlockPointerType(QualType T);
222
223  /// getLValueReferenceType - Return the uniqued reference to the type for an
224  /// lvalue reference to the specified type.
225  QualType getLValueReferenceType(QualType T);
226
227  /// getRValueReferenceType - Return the uniqued reference to the type for an
228  /// rvalue reference to the specified type.
229  QualType getRValueReferenceType(QualType T);
230
231  /// getMemberPointerType - Return the uniqued reference to the type for a
232  /// member pointer to the specified type in the specified class. The class
233  /// is a Type because it could be a dependent name.
234  QualType getMemberPointerType(QualType T, const Type *Cls);
235
236  /// getVariableArrayType - Returns a non-unique reference to the type for a
237  /// variable array of the specified element type.
238  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
239                                ArrayType::ArraySizeModifier ASM,
240                                unsigned EltTypeQuals);
241
242  /// getDependentSizedArrayType - Returns a non-unique reference to
243  /// the type for a dependently-sized array of the specified element
244  /// type. FIXME: We will need these to be uniqued, or at least
245  /// comparable, at some point.
246  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
247                                      ArrayType::ArraySizeModifier ASM,
248                                      unsigned EltTypeQuals);
249
250  /// getIncompleteArrayType - Returns a unique reference to the type for a
251  /// incomplete array of the specified element type.
252  QualType getIncompleteArrayType(QualType EltTy,
253                                  ArrayType::ArraySizeModifier ASM,
254                                  unsigned EltTypeQuals);
255
256  /// getConstantArrayType - Return the unique reference to the type for a
257  /// constant array of the specified element type.
258  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
259                                ArrayType::ArraySizeModifier ASM,
260                                unsigned EltTypeQuals);
261
262  /// getVectorType - Return the unique reference to a vector type of
263  /// the specified element type and size. VectorType must be a built-in type.
264  QualType getVectorType(QualType VectorType, unsigned NumElts);
265
266  /// getExtVectorType - Return the unique reference to an extended vector type
267  /// of the specified element type and size.  VectorType must be a built-in
268  /// type.
269  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
270
271  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
272  ///
273  QualType getFunctionNoProtoType(QualType ResultTy);
274
275  /// getFunctionType - Return a normal function type with a typed argument
276  /// list.  isVariadic indicates whether the argument list includes '...'.
277  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
278                           unsigned NumArgs, bool isVariadic,
279                           unsigned TypeQuals);
280
281  /// getTypeDeclType - Return the unique reference to the type for
282  /// the specified type declaration.
283  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
284
285  /// getTypedefType - Return the unique reference to the type for the
286  /// specified typename decl.
287  QualType getTypedefType(TypedefDecl *Decl);
288  QualType getObjCInterfaceType(ObjCInterfaceDecl *Decl);
289  QualType buildObjCInterfaceType(ObjCInterfaceDecl *Decl);
290
291  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
292                                   IdentifierInfo *Name = 0);
293
294  QualType getClassTemplateSpecializationType(TemplateDecl *Template,
295                                              const TemplateArgument *Args,
296                                              unsigned NumArgs,
297                                              QualType Canon = QualType());
298
299  QualType getQualifiedNameType(NestedNameSpecifier *NNS,
300                                QualType NamedType);
301  QualType getTypenameType(NestedNameSpecifier *NNS,
302                           const IdentifierInfo *Name,
303                           QualType Canon = QualType());
304
305  /// getObjCQualifiedInterfaceType - Return a
306  /// ObjCQualifiedInterfaceType type for the given interface decl and
307  /// the conforming protocol list.
308  QualType getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
309                                         ObjCProtocolDecl **ProtocolList,
310                                         unsigned NumProtocols);
311
312  /// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for a
313  /// given 'id' and conforming protocol list.
314  QualType getObjCQualifiedIdType(ObjCProtocolDecl **ProtocolList,
315                                  unsigned NumProtocols);
316
317
318  /// getTypeOfType - GCC extension.
319  QualType getTypeOfExprType(Expr *e);
320  QualType getTypeOfType(QualType t);
321
322  /// getTagDeclType - Return the unique reference to the type for the
323  /// specified TagDecl (struct/union/class/enum) decl.
324  QualType getTagDeclType(TagDecl *Decl);
325
326  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
327  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
328  QualType getSizeType() const;
329
330  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
331  /// returns a type compatible with the type defined in <stddef.h> as defined
332  /// by the target.
333  QualType getWCharType() const { return WCharTy; }
334
335  /// getSignedWCharType - Return the type of "signed wchar_t".
336  /// Used when in C++, as a GCC extension.
337  QualType getSignedWCharType() const;
338
339  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
340  /// Used when in C++, as a GCC extension.
341  QualType getUnsignedWCharType() const;
342
343  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
344  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
345  QualType getPointerDiffType() const;
346
347  // getCFConstantStringType - Return the C structure type used to represent
348  // constant CFStrings.
349  QualType getCFConstantStringType();
350
351  // This setter/getter represents the ObjC type for an NSConstantString.
352  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
353  QualType getObjCConstantStringInterface() const {
354    return ObjCConstantStringType;
355  }
356
357  //// This gets the struct used to keep track of fast enumerations.
358  QualType getObjCFastEnumerationStateType();
359
360  /// getObjCEncodingForType - Emit the ObjC type encoding for the
361  /// given type into \arg S. If \arg NameFields is specified then
362  /// record field names are also encoded.
363  void getObjCEncodingForType(QualType t, std::string &S,
364                              FieldDecl *Field=NULL) const;
365
366  void getLegacyIntegralTypeEncoding(QualType &t) const;
367
368  // Put the string version of type qualifiers into S.
369  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
370                                       std::string &S) const;
371
372  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
373  /// declaration.
374  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
375
376  /// getObjCEncodingForPropertyDecl - Return the encoded type for
377  /// this method declaration. If non-NULL, Container must be either
378  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
379  /// only be NULL when getting encodings for protocol properties.
380  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
381                                      const Decl *Container,
382                                      std::string &S);
383
384  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
385  /// purpose.
386  int getObjCEncodingTypeSize(QualType t);
387
388  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
389  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
390  QualType getObjCIdType() const { return ObjCIdType; }
391  void setObjCIdType(TypedefDecl *Decl);
392
393  void setObjCSelType(TypedefDecl *Decl);
394  QualType getObjCSelType() const { return ObjCSelType; }
395
396  void setObjCProtoType(QualType QT);
397  QualType getObjCProtoType() const { return ObjCProtoType; }
398
399  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
400  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
401  /// struct.
402  QualType getObjCClassType() const { return ObjCClassType; }
403  void setObjCClassType(TypedefDecl *Decl);
404
405  void setBuiltinVaListType(QualType T);
406  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
407
408  QualType getFixedWidthIntType(unsigned Width, bool Signed);
409
410private:
411  QualType getFromTargetType(unsigned Type) const;
412
413  //===--------------------------------------------------------------------===//
414  //                         Type Predicates.
415  //===--------------------------------------------------------------------===//
416
417public:
418  /// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
419  /// to an object type.  This includes "id" and "Class" (two 'special' pointers
420  /// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
421  /// ID type).
422  bool isObjCObjectPointerType(QualType Ty) const;
423
424  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
425  /// garbage collection attribute.
426  ///
427  QualType::GCAttrTypes getObjCGCAttrKind(const QualType &Ty) const;
428
429  /// isObjCNSObjectType - Return true if this is an NSObject object with
430  /// its NSObject attribute set.
431  bool isObjCNSObjectType(QualType Ty) const;
432
433  //===--------------------------------------------------------------------===//
434  //                         Type Sizing and Analysis
435  //===--------------------------------------------------------------------===//
436
437  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
438  /// scalar floating point type.
439  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
440
441  /// getTypeInfo - Get the size and alignment of the specified complete type in
442  /// bits.
443  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
444  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
445    return getTypeInfo(T.getTypePtr());
446  }
447
448  /// getTypeSize - Return the size of the specified type, in bits.  This method
449  /// does not work on incomplete types.
450  uint64_t getTypeSize(QualType T) {
451    return getTypeInfo(T).first;
452  }
453  uint64_t getTypeSize(const Type *T) {
454    return getTypeInfo(T).first;
455  }
456
457  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
458  /// This method does not work on incomplete types.
459  unsigned getTypeAlign(QualType T) {
460    return getTypeInfo(T).second;
461  }
462  unsigned getTypeAlign(const Type *T) {
463    return getTypeInfo(T).second;
464  }
465
466  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
467  /// type for the current target in bits.  This can be different than the ABI
468  /// alignment in cases where it is beneficial for performance to overalign
469  /// a data type.
470  unsigned getPreferredTypeAlign(const Type *T);
471
472  /// getDeclAlignInBytes - Return the alignment of the specified decl
473  /// that should be returned by __alignof().  Note that bitfields do
474  /// not have a valid alignment, so this method will assert on them.
475  unsigned getDeclAlignInBytes(const Decl *D);
476
477  /// getASTRecordLayout - Get or compute information about the layout of the
478  /// specified record (struct/union/class), which indicates its size and field
479  /// position information.
480  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
481
482  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
483  const RecordDecl *addRecordToClass(const ObjCInterfaceDecl *D);
484  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
485                        std::vector<FieldDecl*> &Fields) const;
486  const FieldDecl *getFieldDecl(const ObjCIvarRefExpr *MRef) {
487    llvm::DenseMap<const ObjCIvarRefExpr *, const FieldDecl*>::iterator I
488      = ASTFieldForIvarRef.find(MRef);
489    assert (I != ASTFieldForIvarRef.end()  && "Unable to find field_decl");
490    return I->second;
491  }
492  void setFieldDecl(const ObjCInterfaceDecl *OI,
493                    const ObjCIvarDecl *Ivar,
494                    const ObjCIvarRefExpr *MRef);
495  //===--------------------------------------------------------------------===//
496  //                            Type Operators
497  //===--------------------------------------------------------------------===//
498
499  /// getCanonicalType - Return the canonical (structural) type corresponding to
500  /// the specified potentially non-canonical type.  The non-canonical version
501  /// of a type may have many "decorated" versions of types.  Decorators can
502  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
503  /// to be free of any of these, allowing two canonical types to be compared
504  /// for exact equality with a simple pointer comparison.
505  QualType getCanonicalType(QualType T);
506  const Type *getCanonicalType(const Type *T) {
507    return T->getCanonicalTypeInternal().getTypePtr();
508  }
509
510  /// \brief Determine whether the given types are equivalent.
511  bool hasSameType(QualType T1, QualType T2) {
512    return getCanonicalType(T1) == getCanonicalType(T2);
513  }
514
515  /// \brief Determine whether the given types are equivalent after
516  /// cvr-qualifiers have been removed.
517  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
518    T1 = getCanonicalType(T1);
519    T2 = getCanonicalType(T2);
520    return T1.getUnqualifiedType() == T2.getUnqualifiedType();
521  }
522
523  /// \brief Retrieves the "canonical" declaration of the given tag
524  /// declaration.
525  ///
526  /// The canonical declaration for the given tag declaration is
527  /// either the definition of the tag (if it is a complete type) or
528  /// the first declaration of that tag.
529  TagDecl *getCanonicalDecl(TagDecl *Tag) {
530    QualType T = getTagDeclType(Tag);
531    return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
532                           ->getDecl());
533  }
534
535  /// \brief Retrieves the "canonical" nested name specifier for a
536  /// given nested name specifier.
537  ///
538  /// The canonical nested name specifier is a nested name specifier
539  /// that uniquely identifies a type or namespace within the type
540  /// system. For example, given:
541  ///
542  /// \code
543  /// namespace N {
544  ///   struct S {
545  ///     template<typename T> struct X { typename T* type; };
546  ///   };
547  /// }
548  ///
549  /// template<typename T> struct Y {
550  ///   typename N::S::X<T>::type member;
551  /// };
552  /// \endcode
553  ///
554  /// Here, the nested-name-specifier for N::S::X<T>:: will be
555  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
556  /// by declarations in the type system and the canonical type for
557  /// the template type parameter 'T' is template-param-0-0.
558  NestedNameSpecifier *
559  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
560
561  /// Type Query functions.  If the type is an instance of the specified class,
562  /// return the Type pointer for the underlying maximally pretty type.  This
563  /// is a member of ASTContext because this may need to do some amount of
564  /// canonicalization, e.g. to move type qualifiers into the element type.
565  const ArrayType *getAsArrayType(QualType T);
566  const ConstantArrayType *getAsConstantArrayType(QualType T) {
567    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
568  }
569  const VariableArrayType *getAsVariableArrayType(QualType T) {
570    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
571  }
572  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
573    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
574  }
575
576  /// getBaseElementType - Returns the innermost element type of a variable
577  /// length array type. For example, will return "int" for int[m][n]
578  QualType getBaseElementType(const VariableArrayType *VAT);
579
580  /// getArrayDecayedType - Return the properly qualified result of decaying the
581  /// specified array type to a pointer.  This operation is non-trivial when
582  /// handling typedefs etc.  The canonical type of "T" must be an array type,
583  /// this returns a pointer to a properly qualified element of the array.
584  ///
585  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
586  QualType getArrayDecayedType(QualType T);
587
588  /// getIntegerTypeOrder - Returns the highest ranked integer type:
589  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
590  /// LHS < RHS, return -1.
591  int getIntegerTypeOrder(QualType LHS, QualType RHS);
592
593  /// getFloatingTypeOrder - Compare the rank of the two specified floating
594  /// point types, ignoring the domain of the type (i.e. 'double' ==
595  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
596  /// LHS < RHS, return -1.
597  int getFloatingTypeOrder(QualType LHS, QualType RHS);
598
599  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
600  /// point or a complex type (based on typeDomain/typeSize).
601  /// 'typeDomain' is a real floating point or complex type.
602  /// 'typeSize' is a real floating point or complex type.
603  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
604                                             QualType typeDomain) const;
605
606private:
607  // Helper for integer ordering
608  unsigned getIntegerRank(Type* T);
609
610public:
611
612  //===--------------------------------------------------------------------===//
613  //                    Type Compatibility Predicates
614  //===--------------------------------------------------------------------===//
615
616  /// Compatibility predicates used to check assignment expressions.
617  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
618  bool typesAreBlockCompatible(QualType lhs, QualType rhs);
619
620  bool isObjCIdType(QualType T) const {
621    return T == ObjCIdType;
622  }
623  bool isObjCIdStructType(QualType T) const {
624    if (!IdStructType) // ObjC isn't enabled
625      return false;
626    return T->getAsStructureType() == IdStructType;
627  }
628  bool isObjCClassType(QualType T) const {
629    return T == ObjCClassType;
630  }
631  bool isObjCClassStructType(QualType T) const {
632    if (!ClassStructType) // ObjC isn't enabled
633      return false;
634    return T->getAsStructureType() == ClassStructType;
635  }
636  bool isObjCSelType(QualType T) const {
637    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
638    return T->getAsStructureType() == SelStructType;
639  }
640
641  // Check the safety of assignment from LHS to RHS
642  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
643                               const ObjCInterfaceType *RHS);
644  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
645
646  // Functions for calculating composite types
647  QualType mergeTypes(QualType, QualType);
648  QualType mergeFunctionTypes(QualType, QualType);
649
650  //===--------------------------------------------------------------------===//
651  //                    Integer Predicates
652  //===--------------------------------------------------------------------===//
653
654  // The width of an integer, as defined in C99 6.2.6.2. This is the number
655  // of bits in an integer type excluding any padding bits.
656  unsigned getIntWidth(QualType T);
657
658  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
659  // unsigned integer type.  This method takes a signed type, and returns the
660  // corresponding unsigned integer type.
661  QualType getCorrespondingUnsignedType(QualType T);
662
663  //===--------------------------------------------------------------------===//
664  //                    Type Iterators.
665  //===--------------------------------------------------------------------===//
666
667  typedef std::vector<Type*>::iterator       type_iterator;
668  typedef std::vector<Type*>::const_iterator const_type_iterator;
669
670  type_iterator types_begin() { return Types.begin(); }
671  type_iterator types_end() { return Types.end(); }
672  const_type_iterator types_begin() const { return Types.begin(); }
673  const_type_iterator types_end() const { return Types.end(); }
674
675  //===--------------------------------------------------------------------===//
676  //                    Serialization
677  //===--------------------------------------------------------------------===//
678
679  void EmitASTBitcodeBuffer(std::vector<unsigned char> &Buffer) const;
680  static ASTContext *ReadASTBitcodeBuffer(llvm::MemoryBuffer &MBuffer,
681                                          FileManager &FMgr);
682
683  void Emit(llvm::Serializer& S) const;
684  static ASTContext *Create(llvm::Deserializer& D);
685
686  //===--------------------------------------------------------------------===//
687  //                    Integer Values
688  //===--------------------------------------------------------------------===//
689
690  /// MakeIntValue - Make an APSInt of the appropriate width and
691  /// signedness for the given \arg Value and integer \arg Type.
692  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
693    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
694    Res = Value;
695    return Res;
696  }
697
698private:
699  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
700  void operator=(const ASTContext&); // DO NOT IMPLEMENT
701
702  void InitBuiltinTypes();
703  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
704
705  // Return the ObjC type encoding for a given type.
706  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
707                                  bool ExpandPointedToStructures,
708                                  bool ExpandStructures,
709                                  FieldDecl *Field,
710                                  bool OutermostType = false,
711                                  bool EncodingProperty = false) const;
712
713};
714
715}  // end namespace clang
716
717// operator new and delete aren't allowed inside namespaces.
718// The throw specifications are mandated by the standard.
719/// @brief Placement new for using the ASTContext's allocator.
720///
721/// This placement form of operator new uses the ASTContext's allocator for
722/// obtaining memory. It is a non-throwing new, which means that it returns
723/// null on error. (If that is what the allocator does. The current does, so if
724/// this ever changes, this operator will have to be changed, too.)
725/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
726/// @code
727/// // Default alignment (16)
728/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
729/// // Specific alignment
730/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
731/// @endcode
732/// Please note that you cannot use delete on the pointer; it must be
733/// deallocated using an explicit destructor call followed by
734/// @c Context.Deallocate(Ptr).
735///
736/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
737/// @param C The ASTContext that provides the allocator.
738/// @param Alignment The alignment of the allocated memory (if the underlying
739///                  allocator supports it).
740/// @return The allocated memory. Could be NULL.
741inline void *operator new(size_t Bytes, clang::ASTContext &C,
742                          size_t Alignment = 16) throw () {
743  return C.Allocate(Bytes, Alignment);
744}
745/// @brief Placement delete companion to the new above.
746///
747/// This operator is just a companion to the new above. There is no way of
748/// invoking it directly; see the new operator for more details. This operator
749/// is called implicitly by the compiler if a placement new expression using
750/// the ASTContext throws in the object constructor.
751inline void operator delete(void *Ptr, clang::ASTContext &C)
752              throw () {
753  C.Deallocate(Ptr);
754}
755
756/// This placement form of operator new[] uses the ASTContext's allocator for
757/// obtaining memory. It is a non-throwing new[], which means that it returns
758/// null on error.
759/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
760/// @code
761/// // Default alignment (16)
762/// char *data = new (Context) char[10];
763/// // Specific alignment
764/// char *data = new (Context, 8) char[10];
765/// @endcode
766/// Please note that you cannot use delete on the pointer; it must be
767/// deallocated using an explicit destructor call followed by
768/// @c Context.Deallocate(Ptr).
769///
770/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
771/// @param C The ASTContext that provides the allocator.
772/// @param Alignment The alignment of the allocated memory (if the underlying
773///                  allocator supports it).
774/// @return The allocated memory. Could be NULL.
775inline void *operator new[](size_t Bytes, clang::ASTContext& C,
776                            size_t Alignment = 16) throw () {
777  return C.Allocate(Bytes, Alignment);
778}
779
780/// @brief Placement delete[] companion to the new[] above.
781///
782/// This operator is just a companion to the new[] above. There is no way of
783/// invoking it directly; see the new[] operator for more details. This operator
784/// is called implicitly by the compiler if a placement new[] expression using
785/// the ASTContext throws in the object constructor.
786inline void operator delete[](void *Ptr, clang::ASTContext &C) throw () {
787  C.Deallocate(Ptr);
788}
789
790#endif
791