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