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