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