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