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