ASTContext.h revision 43822eaeddeaa419b90f23c68af6b23c46788a58
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/DeclarationName.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/SourceLocation.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/Bitcode/SerializationFwd.h"
27#include "llvm/Support/Allocator.h"
28#include <vector>
29
30namespace llvm {
31  struct fltSemantics;
32}
33
34namespace clang {
35  class ASTRecordLayout;
36  class Expr;
37  class IdentifierTable;
38  class SelectorTable;
39  class SourceManager;
40  class TargetInfo;
41  // Decls
42  class Decl;
43  class ObjCPropertyDecl;
44  class RecordDecl;
45  class TagDecl;
46  class TranslationUnitDecl;
47  class TypeDecl;
48  class TypedefDecl;
49  class TemplateTypeParmDecl;
50  class FieldDecl;
51  class ObjCIvarRefExpr;
52  class ObjCIvarDecl;
53
54/// ASTContext - This class holds long-lived AST nodes (such as types and
55/// decls) that can be referred to throughout the semantic analysis of a file.
56class ASTContext {
57  std::vector<Type*> Types;
58  llvm::FoldingSet<ASQualType> ASQualTypes;
59  llvm::FoldingSet<ComplexType> ComplexTypes;
60  llvm::FoldingSet<PointerType> PointerTypes;
61  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
62  llvm::FoldingSet<ReferenceType> ReferenceTypes;
63  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
64  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
65  std::vector<VariableArrayType*> VariableArrayTypes;
66  std::vector<DependentSizedArrayType*> DependentSizedArrayTypes;
67  llvm::FoldingSet<VectorType> VectorTypes;
68  llvm::FoldingSet<FunctionTypeNoProto> FunctionTypeNoProtos;
69  llvm::FoldingSet<FunctionTypeProto> FunctionTypeProtos;
70  llvm::FoldingSet<ObjCQualifiedInterfaceType> ObjCQualifiedInterfaceTypes;
71  llvm::FoldingSet<ObjCQualifiedIdType> ObjCQualifiedIdTypes;
72  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
73  ///  This is lazily created.  This is intentionally not serialized.
74  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
75  llvm::DenseMap<const ObjCInterfaceDecl*,
76                 const ASTRecordLayout*> ASTObjCInterfaces;
77
78  llvm::DenseMap<const ObjCInterfaceDecl*,
79                 const RecordDecl*> ASTRecordForInterface;
80  llvm::DenseMap<const ObjCIvarRefExpr*, const FieldDecl*> ASTFieldForIvarRef;
81
82  /// BuiltinVaListType - built-in va list type.
83  /// This is initially null and set by Sema::LazilyCreateBuiltin when
84  /// a builtin that takes a valist is encountered.
85  QualType BuiltinVaListType;
86
87  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
88  QualType ObjCIdType;
89  const RecordType *IdStructType;
90
91  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
92  QualType ObjCSelType;
93  const RecordType *SelStructType;
94
95  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
96  QualType ObjCProtoType;
97  const RecordType *ProtoStructType;
98
99  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
100  QualType ObjCClassType;
101  const RecordType *ClassStructType;
102
103  QualType ObjCConstantStringType;
104  RecordDecl *CFConstantStringTypeDecl;
105
106  RecordDecl *ObjCFastEnumerationStateTypeDecl;
107
108  TranslationUnitDecl *TUDecl;
109
110  /// SourceMgr - The associated SourceManager object.
111  SourceManager &SourceMgr;
112
113  /// LangOpts - The language options used to create the AST associated with
114  ///  this ASTContext object.
115  LangOptions LangOpts;
116
117  /// Allocator - The allocator object used to create AST objects.
118  llvm::MallocAllocator Allocator;
119
120public:
121  TargetInfo &Target;
122  IdentifierTable &Idents;
123  SelectorTable &Selectors;
124  DeclarationNameTable DeclarationNames;
125
126  SourceManager& getSourceManager() { return SourceMgr; }
127  llvm::MallocAllocator &getAllocator() { return Allocator; }
128  const LangOptions& getLangOptions() const { return LangOpts; }
129
130  FullSourceLoc getFullLoc(SourceLocation Loc) const {
131    return FullSourceLoc(Loc,SourceMgr);
132  }
133
134  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
135
136  /// This is intentionally not serialized.  It is populated by the
137  /// ASTContext ctor, and there are no external pointers/references to
138  /// internal variables of BuiltinInfo.
139  Builtin::Context BuiltinInfo;
140
141  // Builtin Types.
142  QualType VoidTy;
143  QualType BoolTy;
144  QualType CharTy;
145  QualType WCharTy; // [C++ 3.9.1p5]
146  QualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy;
147  QualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
148  QualType UnsignedLongLongTy;
149  QualType FloatTy, DoubleTy, LongDoubleTy;
150  QualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
151  QualType VoidPtrTy;
152  QualType OverloadTy;
153  QualType DependentTy;
154
155  ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
156             IdentifierTable &idents, SelectorTable &sels,
157             unsigned size_reserve=0);
158
159  ~ASTContext();
160
161  void PrintStats() const;
162  const std::vector<Type*>& getTypes() const { return Types; }
163
164  //===--------------------------------------------------------------------===//
165  //                           Type Constructors
166  //===--------------------------------------------------------------------===//
167
168  /// getASQualType - Return the uniqued reference to the type for an address
169  /// space qualified type with the specified type and address space.  The
170  /// resulting type has a union of the qualifiers from T and the address space.
171  // If T already has an address space specifier, it is silently replaced.
172  QualType getASQualType(QualType T, unsigned AddressSpace);
173
174  /// getComplexType - Return the uniqued reference to the type for a complex
175  /// number with the specified element type.
176  QualType getComplexType(QualType T);
177
178  /// getPointerType - Return the uniqued reference to the type for a pointer to
179  /// the specified type.
180  QualType getPointerType(QualType T);
181
182  /// getBlockPointerType - Return the uniqued reference to the type for a block
183  /// of the specified type.
184  QualType getBlockPointerType(QualType T);
185
186  /// getReferenceType - Return the uniqued reference to the type for a
187  /// reference to the specified type.
188  QualType getReferenceType(QualType T);
189
190  /// getVariableArrayType - Returns a non-unique reference to the type for a
191  /// variable array of the specified element type.
192  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
193                                ArrayType::ArraySizeModifier ASM,
194                                unsigned EltTypeQuals);
195
196  /// getDependentSizedArrayType - Returns a non-unique reference to
197  /// the type for a dependently-sized array of the specified element
198  /// type. FIXME: We will need these to be uniqued, or at least
199  /// comparable, at some point.
200  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
201                                      ArrayType::ArraySizeModifier ASM,
202                                      unsigned EltTypeQuals);
203
204  /// getIncompleteArrayType - Returns a unique reference to the type for a
205  /// incomplete array of the specified element type.
206  QualType getIncompleteArrayType(QualType EltTy,
207                                  ArrayType::ArraySizeModifier ASM,
208                                  unsigned EltTypeQuals);
209
210  /// getConstantArrayType - Return the unique reference to the type for a
211  /// constant array of the specified element type.
212  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
213                                ArrayType::ArraySizeModifier ASM,
214                                unsigned EltTypeQuals);
215
216  /// getVectorType - Return the unique reference to a vector type of
217  /// the specified element type and size. VectorType must be a built-in type.
218  QualType getVectorType(QualType VectorType, unsigned NumElts);
219
220  /// getExtVectorType - Return the unique reference to an extended vector type
221  /// of the specified element type and size.  VectorType must be a built-in
222  /// type.
223  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
224
225  /// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
226  ///
227  QualType getFunctionTypeNoProto(QualType ResultTy);
228
229  /// getFunctionType - Return a normal function type with a typed argument
230  /// list.  isVariadic indicates whether the argument list includes '...'.
231  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
232                           unsigned NumArgs, bool isVariadic,
233                           unsigned TypeQuals);
234
235  /// getTypeDeclType - Return the unique reference to the type for
236  /// the specified type declaration.
237  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
238
239  /// getTypedefType - Return the unique reference to the type for the
240  /// specified typename decl.
241  QualType getTypedefType(TypedefDecl *Decl);
242  QualType getTemplateTypeParmType(TemplateTypeParmDecl *Decl);
243  QualType getObjCInterfaceType(ObjCInterfaceDecl *Decl);
244
245  /// getObjCQualifiedInterfaceType - Return a
246  /// ObjCQualifiedInterfaceType type for the given interface decl and
247  /// the conforming protocol list.
248  QualType getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
249             ObjCProtocolDecl **ProtocolList, unsigned NumProtocols);
250
251  /// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for a
252  /// given 'id' and conforming protocol list.
253  QualType getObjCQualifiedIdType(ObjCProtocolDecl **ProtocolList,
254                                  unsigned NumProtocols);
255
256
257  /// getTypeOfType - GCC extension.
258  QualType getTypeOfExpr(Expr *e);
259  QualType getTypeOfType(QualType t);
260
261  /// getTagDeclType - Return the unique reference to the type for the
262  /// specified TagDecl (struct/union/class/enum) decl.
263  QualType getTagDeclType(TagDecl *Decl);
264
265  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
266  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
267  QualType getSizeType() const;
268
269  /// getWCharType - Return the unique type for "wchar_t" (C99 7.17), defined
270  /// in <stddef.h>. Wide strings require this (C99 6.4.5p5).
271  QualType getWCharType() const;
272
273  /// getSignedWCharType - Return the type of "signed wchar_t".
274  /// Used when in C++, as a GCC extension.
275  QualType getSignedWCharType() const;
276
277  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
278  /// Used when in C++, as a GCC extension.
279  QualType getUnsignedWCharType() const;
280
281  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
282  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
283  QualType getPointerDiffType() const;
284
285  // getCFConstantStringType - Return the C structure type used to represent
286  // constant CFStrings.
287  QualType getCFConstantStringType();
288
289  // This setter/getter represents the ObjC type for an NSConstantString.
290  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
291  QualType getObjCConstantStringInterface() const {
292    return ObjCConstantStringType;
293  }
294
295  //// This gets the struct used to keep track of fast enumerations.
296  QualType getObjCFastEnumerationStateType();
297
298  /// getObjCEncodingForType - Emit the ObjC type encoding for the
299  /// given type into \arg S. If \arg NameFields is specified then
300  /// record field names are also encoded.
301  void getObjCEncodingForType(QualType t, std::string &S,
302                              FieldDecl *Field=NULL) const;
303
304  // Put the string version of type qualifiers into S.
305  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
306                                       std::string &S) const;
307
308  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
309  /// declaration.
310  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
311
312  /// getObjCEncodingForPropertyDecl - Return the encoded type for
313  /// this method declaration. If non-NULL, Container must be either
314  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
315  /// only be NULL when getting encodings for protocol properties.
316  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
317                                      const Decl *Container,
318                                      std::string &S);
319
320  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
321  /// purpose.
322  int getObjCEncodingTypeSize(QualType t);
323
324  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
325  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
326  QualType getObjCIdType() const { return ObjCIdType; }
327  void setObjCIdType(TypedefDecl *Decl);
328
329  void setObjCSelType(TypedefDecl *Decl);
330  QualType getObjCSelType() const { return ObjCSelType; }
331
332  void setObjCProtoType(QualType QT);
333  QualType getObjCProtoType() const { return ObjCProtoType; }
334
335  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
336  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
337  /// struct.
338  QualType getObjCClassType() const { return ObjCClassType; }
339  void setObjCClassType(TypedefDecl *Decl);
340
341  void setBuiltinVaListType(QualType T);
342  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
343
344private:
345  QualType getFromTargetType(unsigned Type) const;
346
347  //===--------------------------------------------------------------------===//
348  //                         Type Predicates.
349  //===--------------------------------------------------------------------===//
350
351public:
352  /// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
353  /// to an object type.  This includes "id" and "Class" (two 'special' pointers
354  /// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
355  /// ID type).
356  bool isObjCObjectPointerType(QualType Ty) const;
357
358  //===--------------------------------------------------------------------===//
359  //                         Type Sizing and Analysis
360  //===--------------------------------------------------------------------===//
361
362  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
363  /// scalar floating point type.
364  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
365
366  /// getTypeInfo - Get the size and alignment of the specified complete type in
367  /// bits.
368  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
369  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
370    return getTypeInfo(T.getTypePtr());
371  }
372
373  /// getTypeSize - Return the size of the specified type, in bits.  This method
374  /// does not work on incomplete types.
375  uint64_t getTypeSize(QualType T) {
376    return getTypeInfo(T).first;
377  }
378  uint64_t getTypeSize(const Type *T) {
379    return getTypeInfo(T).first;
380  }
381
382  /// getTypeAlign - Return the alignment of the specified type, in bits.  This
383  /// method does not work on incomplete types.
384  unsigned getTypeAlign(QualType T) {
385    return getTypeInfo(T).second;
386  }
387  unsigned getTypeAlign(const Type *T) {
388    return getTypeInfo(T).second;
389  }
390
391  /// getASTRecordLayout - Get or compute information about the layout of the
392  /// specified record (struct/union/class), which indicates its size and field
393  /// position information.
394  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
395
396  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
397  const RecordDecl *addRecordToClass(const ObjCInterfaceDecl *D);
398  const FieldDecl *getFieldDecl(const ObjCIvarRefExpr *MRef) {
399    llvm::DenseMap<const ObjCIvarRefExpr *, const FieldDecl*>::iterator I
400      = ASTFieldForIvarRef.find(MRef);
401    assert (I != ASTFieldForIvarRef.end()  && "Unable to find field_decl");
402    return I->second;
403  }
404  void setFieldDecl(const ObjCInterfaceDecl *OI,
405                    const ObjCIvarDecl *Ivar,
406                    const ObjCIvarRefExpr *MRef);
407  //===--------------------------------------------------------------------===//
408  //                            Type Operators
409  //===--------------------------------------------------------------------===//
410
411  /// getCanonicalType - Return the canonical (structural) type corresponding to
412  /// the specified potentially non-canonical type.  The non-canonical version
413  /// of a type may have many "decorated" versions of types.  Decorators can
414  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
415  /// to be free of any of these, allowing two canonical types to be compared
416  /// for exact equality with a simple pointer comparison.
417  QualType getCanonicalType(QualType T);
418  const Type *getCanonicalType(const Type *T) {
419    return T->getCanonicalTypeInternal().getTypePtr();
420  }
421
422  /// Type Query functions.  If the type is an instance of the specified class,
423  /// return the Type pointer for the underlying maximally pretty type.  This
424  /// is a member of ASTContext because this may need to do some amount of
425  /// canonicalization, e.g. to move type qualifiers into the element type.
426  const ArrayType *getAsArrayType(QualType T);
427  const ConstantArrayType *getAsConstantArrayType(QualType T) {
428    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
429  }
430  const VariableArrayType *getAsVariableArrayType(QualType T) {
431    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
432  }
433  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
434    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
435  }
436
437  /// getArrayDecayedType - Return the properly qualified result of decaying the
438  /// specified array type to a pointer.  This operation is non-trivial when
439  /// handling typedefs etc.  The canonical type of "T" must be an array type,
440  /// this returns a pointer to a properly qualified element of the array.
441  ///
442  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
443  QualType getArrayDecayedType(QualType T);
444
445  /// getIntegerTypeOrder - Returns the highest ranked integer type:
446  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
447  /// LHS < RHS, return -1.
448  int getIntegerTypeOrder(QualType LHS, QualType RHS);
449
450  /// getFloatingTypeOrder - Compare the rank of the two specified floating
451  /// point types, ignoring the domain of the type (i.e. 'double' ==
452  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
453  /// LHS < RHS, return -1.
454  int getFloatingTypeOrder(QualType LHS, QualType RHS);
455
456  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
457  /// point or a complex type (based on typeDomain/typeSize).
458  /// 'typeDomain' is a real floating point or complex type.
459  /// 'typeSize' is a real floating point or complex type.
460  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
461                                             QualType typeDomain) const;
462
463  //===--------------------------------------------------------------------===//
464  //                    Type Compatibility Predicates
465  //===--------------------------------------------------------------------===//
466
467  /// Compatibility predicates used to check assignment expressions.
468  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
469  bool typesAreBlockCompatible(QualType lhs, QualType rhs);
470
471  bool isObjCIdType(QualType T) const {
472    if (!IdStructType) // ObjC isn't enabled
473      return false;
474    return T->getAsStructureType() == IdStructType;
475  }
476  bool isObjCClassType(QualType T) const {
477    if (!ClassStructType) // ObjC isn't enabled
478      return false;
479    return T->getAsStructureType() == ClassStructType;
480  }
481  bool isObjCSelType(QualType T) const {
482    assert(SelStructType && "isObjCSelType used before 'SEL' type is built");
483    return T->getAsStructureType() == SelStructType;
484  }
485
486  // Check the safety of assignment from LHS to RHS
487  bool canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
488                               const ObjCInterfaceType *RHS);
489
490  // Functions for calculating composite types
491  QualType mergeTypes(QualType, QualType);
492  QualType mergeFunctionTypes(QualType, QualType);
493
494  //===--------------------------------------------------------------------===//
495  //                    Integer Predicates
496  //===--------------------------------------------------------------------===//
497
498  // The width of an integer, as defined in C99 6.2.6.2. This is the number
499  // of bits in an integer type excluding any padding bits.
500  unsigned getIntWidth(QualType T);
501
502  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
503  // unsigned integer type.  This method takes a signed type, and returns the
504  // corresponding unsigned integer type.
505  QualType getCorrespondingUnsignedType(QualType T);
506
507  //===--------------------------------------------------------------------===//
508  //                    Type Iterators.
509  //===--------------------------------------------------------------------===//
510
511  typedef std::vector<Type*>::iterator       type_iterator;
512  typedef std::vector<Type*>::const_iterator const_type_iterator;
513
514  type_iterator types_begin() { return Types.begin(); }
515  type_iterator types_end() { return Types.end(); }
516  const_type_iterator types_begin() const { return Types.begin(); }
517  const_type_iterator types_end() const { return Types.end(); }
518
519  //===--------------------------------------------------------------------===//
520  //                    Serialization
521  //===--------------------------------------------------------------------===//
522
523  void Emit(llvm::Serializer& S) const;
524  static ASTContext* Create(llvm::Deserializer& D);
525
526private:
527  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
528  void operator=(const ASTContext&); // DO NOT IMPLEMENT
529
530  void InitBuiltinTypes();
531  void InitBuiltinType(QualType &R, BuiltinType::Kind K);
532
533  /// setTagDefinition - Used by RecordDecl::completeDefinition and
534  /// EnumDecl::completeDefinition to inform
535  /// about which RecordDecl/EnumDecl serves as the definition of a particular
536  /// struct/union/class/enum.
537  void setTagDefinition(TagDecl* R);
538  friend class EnumDecl;
539  friend class RecordDecl;
540
541  // Return the ObjC type encoding for a given type.
542  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
543                                  bool ExpandPointedToStructures,
544                                  bool ExpandStructures,
545                                  FieldDecl *Field) const;
546
547};
548
549}  // end namespace clang
550
551#endif
552