ASTContext.h revision f7992132207d7ddc8810a135cec97ebe5805e500
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/// \file
11/// \brief Defines the clang::ASTContext interface.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16#define LLVM_CLANG_AST_ASTCONTEXT_H
17
18#include "clang/AST/CanonicalType.h"
19#include "clang/AST/CommentCommandTraits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/LambdaMangleContext.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/RawCommentList.h"
25#include "clang/AST/TemplateName.h"
26#include "clang/AST/Type.h"
27#include "clang/Basic/AddressSpaces.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/LangOptions.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/VersionTuple.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/FoldingSet.h"
35#include "llvm/ADT/IntrusiveRefCntPtr.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/TinyPtrVector.h"
39#include "llvm/Support/Allocator.h"
40#include <vector>
41
42namespace llvm {
43  struct fltSemantics;
44}
45
46namespace clang {
47  class FileManager;
48  class ASTRecordLayout;
49  class BlockExpr;
50  class CharUnits;
51  class DiagnosticsEngine;
52  class Expr;
53  class ExternalASTSource;
54  class ASTMutationListener;
55  class IdentifierTable;
56  class SelectorTable;
57  class TargetInfo;
58  class CXXABI;
59  // Decls
60  class DeclContext;
61  class CXXConversionDecl;
62  class CXXMethodDecl;
63  class CXXRecordDecl;
64  class Decl;
65  class FieldDecl;
66  class MangleContext;
67  class ObjCIvarDecl;
68  class ObjCIvarRefExpr;
69  class ObjCPropertyDecl;
70  class ParmVarDecl;
71  class RecordDecl;
72  class StoredDeclsMap;
73  class TagDecl;
74  class TemplateTemplateParmDecl;
75  class TemplateTypeParmDecl;
76  class TranslationUnitDecl;
77  class TypeDecl;
78  class TypedefNameDecl;
79  class UsingDecl;
80  class UsingShadowDecl;
81  class UnresolvedSetIterator;
82
83  namespace Builtin { class Context; }
84
85  namespace comments {
86    class FullComment;
87  }
88
89/// \brief Holds long-lived AST nodes (such as types and decls) that can be
90/// referred to throughout the semantic analysis of a file.
91class ASTContext : public RefCountedBase<ASTContext> {
92  ASTContext &this_() { return *this; }
93
94  mutable std::vector<Type*> Types;
95  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
96  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
97  mutable llvm::FoldingSet<PointerType> PointerTypes;
98  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
99  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
100  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
101  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
102  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
103  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
104  mutable std::vector<VariableArrayType*> VariableArrayTypes;
105  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
106  mutable llvm::FoldingSet<DependentSizedExtVectorType>
107    DependentSizedExtVectorTypes;
108  mutable llvm::FoldingSet<VectorType> VectorTypes;
109  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
110  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
111    FunctionProtoTypes;
112  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
113  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
114  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
115  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
116    SubstTemplateTypeParmTypes;
117  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
118    SubstTemplateTypeParmPackTypes;
119  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
120    TemplateSpecializationTypes;
121  mutable llvm::FoldingSet<ParenType> ParenTypes;
122  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
123  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
124  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
125                                     ASTContext&>
126    DependentTemplateSpecializationTypes;
127  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
128  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
129  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
130  mutable llvm::FoldingSet<AutoType> AutoTypes;
131  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
132  llvm::FoldingSet<AttributedType> AttributedTypes;
133
134  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
135  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
136  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
137    SubstTemplateTemplateParms;
138  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
139                                     ASTContext&>
140    SubstTemplateTemplateParmPacks;
141
142  /// \brief The set of nested name specifiers.
143  ///
144  /// This set is managed by the NestedNameSpecifier class.
145  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
146  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
147  friend class NestedNameSpecifier;
148
149  /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
150  ///
151  /// This is lazily created.  This is intentionally not serialized.
152  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
153    ASTRecordLayouts;
154  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
155    ObjCLayouts;
156
157  /// \brief A cache from types to size and alignment information.
158  typedef llvm::DenseMap<const Type*,
159                         std::pair<uint64_t, unsigned> > TypeInfoMap;
160  mutable TypeInfoMap MemoizedTypeInfo;
161
162  /// \brief A cache mapping from CXXRecordDecls to key functions.
163  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
164
165  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
166  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
167
168  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
169  /// interface.
170  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
171
172  /// \brief Mapping from __block VarDecls to their copy initialization expr.
173  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
174
175  /// \brief Mapping from class scope functions specialization to their
176  /// template patterns.
177  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
178    ClassScopeSpecializationPattern;
179
180  /// \brief Representation of a "canonical" template template parameter that
181  /// is used in canonical template names.
182  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
183    TemplateTemplateParmDecl *Parm;
184
185  public:
186    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
187      : Parm(Parm) { }
188
189    TemplateTemplateParmDecl *getParam() const { return Parm; }
190
191    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
192
193    static void Profile(llvm::FoldingSetNodeID &ID,
194                        TemplateTemplateParmDecl *Parm);
195  };
196  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
197    CanonTemplateTemplateParms;
198
199  TemplateTemplateParmDecl *
200    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
201
202  /// \brief The typedef for the __int128_t type.
203  mutable TypedefDecl *Int128Decl;
204
205  /// \brief The typedef for the __uint128_t type.
206  mutable TypedefDecl *UInt128Decl;
207
208  /// \brief The typedef for the target specific predefined
209  /// __builtin_va_list type.
210  mutable TypedefDecl *BuiltinVaListDecl;
211
212  /// \brief The typedef for the predefined \c id type.
213  mutable TypedefDecl *ObjCIdDecl;
214
215  /// \brief The typedef for the predefined \c SEL type.
216  mutable TypedefDecl *ObjCSelDecl;
217
218  /// \brief The typedef for the predefined \c Class type.
219  mutable TypedefDecl *ObjCClassDecl;
220
221  /// \brief The typedef for the predefined \c Protocol class in Objective-C.
222  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
223
224  /// \brief The typedef for the predefined 'BOOL' type.
225  mutable TypedefDecl *BOOLDecl;
226
227  // Typedefs which may be provided defining the structure of Objective-C
228  // pseudo-builtins
229  QualType ObjCIdRedefinitionType;
230  QualType ObjCClassRedefinitionType;
231  QualType ObjCSelRedefinitionType;
232
233  QualType ObjCConstantStringType;
234  mutable RecordDecl *CFConstantStringTypeDecl;
235
236  mutable QualType ObjCSuperType;
237
238  QualType ObjCNSStringType;
239
240  /// \brief The typedef declaration for the Objective-C "instancetype" type.
241  TypedefDecl *ObjCInstanceTypeDecl;
242
243  /// \brief The type for the C FILE type.
244  TypeDecl *FILEDecl;
245
246  /// \brief The type for the C jmp_buf type.
247  TypeDecl *jmp_bufDecl;
248
249  /// \brief The type for the C sigjmp_buf type.
250  TypeDecl *sigjmp_bufDecl;
251
252  /// \brief The type for the C ucontext_t type.
253  TypeDecl *ucontext_tDecl;
254
255  /// \brief Type for the Block descriptor for Blocks CodeGen.
256  ///
257  /// Since this is only used for generation of debug info, it is not
258  /// serialized.
259  mutable RecordDecl *BlockDescriptorType;
260
261  /// \brief Type for the Block descriptor for Blocks CodeGen.
262  ///
263  /// Since this is only used for generation of debug info, it is not
264  /// serialized.
265  mutable RecordDecl *BlockDescriptorExtendedType;
266
267  /// \brief Declaration for the CUDA cudaConfigureCall function.
268  FunctionDecl *cudaConfigureCallDecl;
269
270  TypeSourceInfo NullTypeSourceInfo;
271
272  /// \brief Keeps track of all declaration attributes.
273  ///
274  /// Since so few decls have attrs, we keep them in a hash map instead of
275  /// wasting space in the Decl class.
276  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
277
278  /// \brief Keeps track of the static data member templates from which
279  /// static data members of class template specializations were instantiated.
280  ///
281  /// This data structure stores the mapping from instantiations of static
282  /// data members to the static data member representations within the
283  /// class template from which they were instantiated along with the kind
284  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
285  ///
286  /// Given the following example:
287  ///
288  /// \code
289  /// template<typename T>
290  /// struct X {
291  ///   static T value;
292  /// };
293  ///
294  /// template<typename T>
295  ///   T X<T>::value = T(17);
296  ///
297  /// int *x = &X<int>::value;
298  /// \endcode
299  ///
300  /// This mapping will contain an entry that maps from the VarDecl for
301  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
302  /// class template X) and will be marked TSK_ImplicitInstantiation.
303  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
304    InstantiatedFromStaticDataMember;
305
306  /// \brief Keeps track of the declaration from which a UsingDecl was
307  /// created during instantiation.
308  ///
309  /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
310  /// or an UnresolvedUsingTypenameDecl.
311  ///
312  /// For example:
313  /// \code
314  /// template<typename T>
315  /// struct A {
316  ///   void f();
317  /// };
318  ///
319  /// template<typename T>
320  /// struct B : A<T> {
321  ///   using A<T>::f;
322  /// };
323  ///
324  /// template struct B<int>;
325  /// \endcode
326  ///
327  /// This mapping will contain an entry that maps from the UsingDecl in
328  /// B<int> to the UnresolvedUsingDecl in B<T>.
329  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
330
331  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
332    InstantiatedFromUsingShadowDecl;
333
334  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
335
336  /// \brief Mapping that stores the methods overridden by a given C++
337  /// member function.
338  ///
339  /// Since most C++ member functions aren't virtual and therefore
340  /// don't override anything, we store the overridden functions in
341  /// this map on the side rather than within the CXXMethodDecl structure.
342  typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
343  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
344
345  /// \brief Mapping from each declaration context to its corresponding lambda
346  /// mangling context.
347  llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
348
349  llvm::DenseMap<const DeclContext *, unsigned> UnnamedMangleContexts;
350  llvm::DenseMap<const TagDecl *, unsigned> UnnamedMangleNumbers;
351
352  /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
353  /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
354  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
355  ParameterIndexTable ParamIndices;
356
357  ImportDecl *FirstLocalImport;
358  ImportDecl *LastLocalImport;
359
360  TranslationUnitDecl *TUDecl;
361
362  /// \brief The associated SourceManager object.a
363  SourceManager &SourceMgr;
364
365  /// \brief The language options used to create the AST associated with
366  ///  this ASTContext object.
367  LangOptions &LangOpts;
368
369  /// \brief The allocator used to create AST objects.
370  ///
371  /// AST objects are never destructed; rather, all memory associated with the
372  /// AST objects will be released when the ASTContext itself is destroyed.
373  mutable llvm::BumpPtrAllocator BumpAlloc;
374
375  /// \brief Allocator for partial diagnostics.
376  PartialDiagnostic::StorageAllocator DiagAllocator;
377
378  /// \brief The current C++ ABI.
379  OwningPtr<CXXABI> ABI;
380  CXXABI *createCXXABI(const TargetInfo &T);
381
382  /// \brief The logical -> physical address space map.
383  const LangAS::Map *AddrSpaceMap;
384
385  friend class ASTDeclReader;
386  friend class ASTReader;
387  friend class ASTWriter;
388  friend class CXXRecordDecl;
389
390  const TargetInfo *Target;
391  clang::PrintingPolicy PrintingPolicy;
392
393public:
394  IdentifierTable &Idents;
395  SelectorTable &Selectors;
396  Builtin::Context &BuiltinInfo;
397  mutable DeclarationNameTable DeclarationNames;
398  OwningPtr<ExternalASTSource> ExternalSource;
399  ASTMutationListener *Listener;
400
401  const clang::PrintingPolicy &getPrintingPolicy() const {
402    return PrintingPolicy;
403  }
404
405  void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
406    PrintingPolicy = Policy;
407  }
408
409  SourceManager& getSourceManager() { return SourceMgr; }
410  const SourceManager& getSourceManager() const { return SourceMgr; }
411
412  llvm::BumpPtrAllocator &getAllocator() const {
413    return BumpAlloc;
414  }
415
416  void *Allocate(unsigned Size, unsigned Align = 8) const {
417    return BumpAlloc.Allocate(Size, Align);
418  }
419  void Deallocate(void *Ptr) const { }
420
421  /// Return the total amount of physical memory allocated for representing
422  /// AST nodes and type information.
423  size_t getASTAllocatedMemory() const {
424    return BumpAlloc.getTotalMemory();
425  }
426  /// Return the total memory used for various side tables.
427  size_t getSideTableAllocatedMemory() const;
428
429  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
430    return DiagAllocator;
431  }
432
433  const TargetInfo &getTargetInfo() const { return *Target; }
434
435  const LangOptions& getLangOpts() const { return LangOpts; }
436
437  DiagnosticsEngine &getDiagnostics() const;
438
439  FullSourceLoc getFullLoc(SourceLocation Loc) const {
440    return FullSourceLoc(Loc,SourceMgr);
441  }
442
443  /// \brief All comments in this translation unit.
444  RawCommentList Comments;
445
446  /// \brief True if comments are already loaded from ExternalASTSource.
447  mutable bool CommentsLoaded;
448
449  class RawCommentAndCacheFlags {
450  public:
451    enum Kind {
452      /// We searched for a comment attached to the particular declaration, but
453      /// didn't find any.
454      ///
455      /// getRaw() == 0.
456      NoCommentInDecl = 0,
457
458      /// We have found a comment attached to this particular declaration.
459      ///
460      /// getRaw() != 0.
461      FromDecl,
462
463      /// This declaration does not have an attached comment, and we have
464      /// searched the redeclaration chain.
465      ///
466      /// If getRaw() == 0, the whole redeclaration chain does not have any
467      /// comments.
468      ///
469      /// If getRaw() != 0, it is a comment propagated from other
470      /// redeclaration.
471      FromRedecl
472    };
473
474    Kind getKind() const LLVM_READONLY {
475      return Data.getInt();
476    }
477
478    void setKind(Kind K) {
479      Data.setInt(K);
480    }
481
482    const RawComment *getRaw() const LLVM_READONLY {
483      return Data.getPointer();
484    }
485
486    void setRaw(const RawComment *RC) {
487      Data.setPointer(RC);
488    }
489
490    const Decl *getOriginalDecl() const LLVM_READONLY {
491      return OriginalDecl;
492    }
493
494    void setOriginalDecl(const Decl *Orig) {
495      OriginalDecl = Orig;
496    }
497
498  private:
499    llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
500    const Decl *OriginalDecl;
501  };
502
503  /// \brief Mapping from declarations to comments attached to any
504  /// redeclaration.
505  ///
506  /// Raw comments are owned by Comments list.  This mapping is populated
507  /// lazily.
508  mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
509
510  /// \brief Mapping from declarations to parsed comments attached to any
511  /// redeclaration.
512  mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
513
514  /// \brief Return the documentation comment attached to a given declaration,
515  /// without looking into cache.
516  RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
517
518public:
519  RawCommentList &getRawCommentList() {
520    return Comments;
521  }
522
523  void addComment(const RawComment &RC) {
524    assert(LangOpts.RetainCommentsFromSystemHeaders ||
525           !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
526    Comments.addComment(RC, BumpAlloc);
527  }
528
529  /// \brief Return the documentation comment attached to a given declaration.
530  /// Returns NULL if no comment is attached.
531  ///
532  /// \param OriginalDecl if not NULL, is set to declaration AST node that had
533  /// the comment, if the comment we found comes from a redeclaration.
534  const RawComment *getRawCommentForAnyRedecl(
535                                      const Decl *D,
536                                      const Decl **OriginalDecl = NULL) const;
537
538  /// Return parsed documentation comment attached to a given declaration.
539  /// Returns NULL if no comment is attached.
540  ///
541  /// \param PP the Preprocessor used with this TU.  Could be NULL if
542  /// preprocessor is not available.
543  comments::FullComment *getCommentForDecl(const Decl *D,
544                                           const Preprocessor *PP) const;
545
546  comments::FullComment *cloneFullComment(comments::FullComment *FC,
547                                         const Decl *D) const;
548
549private:
550  mutable comments::CommandTraits CommentCommandTraits;
551
552public:
553  comments::CommandTraits &getCommentCommandTraits() const {
554    return CommentCommandTraits;
555  }
556
557  /// \brief Retrieve the attributes for the given declaration.
558  AttrVec& getDeclAttrs(const Decl *D);
559
560  /// \brief Erase the attributes corresponding to the given declaration.
561  void eraseDeclAttrs(const Decl *D);
562
563  /// \brief If this variable is an instantiated static data member of a
564  /// class template specialization, returns the templated static data member
565  /// from which it was instantiated.
566  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
567                                                           const VarDecl *Var);
568
569  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
570
571  void setClassScopeSpecializationPattern(FunctionDecl *FD,
572                                          FunctionDecl *Pattern);
573
574  /// \brief Note that the static data member \p Inst is an instantiation of
575  /// the static data member template \p Tmpl of a class template.
576  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
577                                           TemplateSpecializationKind TSK,
578                        SourceLocation PointOfInstantiation = SourceLocation());
579
580  /// \brief If the given using decl \p Inst is an instantiation of a
581  /// (possibly unresolved) using decl from a template instantiation,
582  /// return it.
583  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
584
585  /// \brief Remember that the using decl \p Inst is an instantiation
586  /// of the using decl \p Pattern of a class template.
587  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
588
589  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
590                                          UsingShadowDecl *Pattern);
591  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
592
593  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
594
595  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
596
597  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
598  /// the non-bitfield \p LastFD.
599  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
600                                      const FieldDecl *LastFD) const;
601
602  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
603  /// the bitfield \p LastFD.
604  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
605                                   const FieldDecl *LastFD) const;
606
607  /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
608  /// \p LastFD.
609  bool BitfieldFollowsBitfield(const FieldDecl *FD,
610                               const FieldDecl *LastFD) const;
611
612  /// \brief Return \c true if \p FD is not a bitfield which follows the
613  /// bitfield \p LastFD.
614  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
615                                  const FieldDecl *LastFD) const;
616
617  /// \brief Return \c true if \p FD is a bitfield which follows the
618  /// non-bitfield \p LastFD.
619  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
620                                  const FieldDecl *LastFD) const;
621
622  // Access to the set of methods overridden by the given C++ method.
623  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
624  overridden_cxx_method_iterator
625  overridden_methods_begin(const CXXMethodDecl *Method) const;
626
627  overridden_cxx_method_iterator
628  overridden_methods_end(const CXXMethodDecl *Method) const;
629
630  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
631
632  /// \brief Note that the given C++ \p Method overrides the given \p
633  /// Overridden method.
634  void addOverriddenMethod(const CXXMethodDecl *Method,
635                           const CXXMethodDecl *Overridden);
636
637  /// \brief Return C++ or ObjC overridden methods for the given \p Method.
638  ///
639  /// An ObjC method is considered to override any method in the class's
640  /// base classes, its protocols, or its categories' protocols, that has
641  /// the same selector and is of the same kind (class or instance).
642  /// A method in an implementation is not considered as overriding the same
643  /// method in the interface or its categories.
644  void getOverriddenMethods(
645                        const NamedDecl *Method,
646                        SmallVectorImpl<const NamedDecl *> &Overridden) const;
647
648  /// \brief Notify the AST context that a new import declaration has been
649  /// parsed or implicitly created within this translation unit.
650  void addedLocalImportDecl(ImportDecl *Import);
651
652  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
653    return Import->NextLocalImport;
654  }
655
656  /// \brief Iterator that visits import declarations.
657  class import_iterator {
658    ImportDecl *Import;
659
660  public:
661    typedef ImportDecl               *value_type;
662    typedef ImportDecl               *reference;
663    typedef ImportDecl               *pointer;
664    typedef int                       difference_type;
665    typedef std::forward_iterator_tag iterator_category;
666
667    import_iterator() : Import() { }
668    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
669
670    reference operator*() const { return Import; }
671    pointer operator->() const { return Import; }
672
673    import_iterator &operator++() {
674      Import = ASTContext::getNextLocalImport(Import);
675      return *this;
676    }
677
678    import_iterator operator++(int) {
679      import_iterator Other(*this);
680      ++(*this);
681      return Other;
682    }
683
684    friend bool operator==(import_iterator X, import_iterator Y) {
685      return X.Import == Y.Import;
686    }
687
688    friend bool operator!=(import_iterator X, import_iterator Y) {
689      return X.Import != Y.Import;
690    }
691  };
692
693  import_iterator local_import_begin() const {
694    return import_iterator(FirstLocalImport);
695  }
696  import_iterator local_import_end() const { return import_iterator(); }
697
698  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
699
700
701  // Builtin Types.
702  CanQualType VoidTy;
703  CanQualType BoolTy;
704  CanQualType CharTy;
705  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
706  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
707  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
708  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
709  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
710  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
711  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
712  CanQualType FloatTy, DoubleTy, LongDoubleTy;
713  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
714  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
715  CanQualType VoidPtrTy, NullPtrTy;
716  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
717  CanQualType BuiltinFnTy;
718  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
719  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
720  CanQualType ObjCBuiltinBoolTy;
721  CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
722  CanQualType OCLImage2dTy, OCLImage2dArrayTy;
723  CanQualType OCLImage3dTy;
724
725  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
726  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
727  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
728
729  // Type used to help define __builtin_va_list for some targets.
730  // The type is built when constructing 'BuiltinVaListDecl'.
731  mutable QualType VaListTagTy;
732
733  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
734             IdentifierTable &idents, SelectorTable &sels,
735             Builtin::Context &builtins,
736             unsigned size_reserve,
737             bool DelayInitialization = false);
738
739  ~ASTContext();
740
741  /// \brief Attach an external AST source to the AST context.
742  ///
743  /// The external AST source provides the ability to load parts of
744  /// the abstract syntax tree as needed from some external storage,
745  /// e.g., a precompiled header.
746  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
747
748  /// \brief Retrieve a pointer to the external AST source associated
749  /// with this AST context, if any.
750  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
751
752  /// \brief Attach an AST mutation listener to the AST context.
753  ///
754  /// The AST mutation listener provides the ability to track modifications to
755  /// the abstract syntax tree entities committed after they were initially
756  /// created.
757  void setASTMutationListener(ASTMutationListener *Listener) {
758    this->Listener = Listener;
759  }
760
761  /// \brief Retrieve a pointer to the AST mutation listener associated
762  /// with this AST context, if any.
763  ASTMutationListener *getASTMutationListener() const { return Listener; }
764
765  void PrintStats() const;
766  const std::vector<Type*>& getTypes() const { return Types; }
767
768  /// \brief Retrieve the declaration for the 128-bit signed integer type.
769  TypedefDecl *getInt128Decl() const;
770
771  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
772  TypedefDecl *getUInt128Decl() const;
773
774  //===--------------------------------------------------------------------===//
775  //                           Type Constructors
776  //===--------------------------------------------------------------------===//
777
778private:
779  /// \brief Return a type with extended qualifiers.
780  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
781
782  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
783
784public:
785  /// \brief Return the uniqued reference to the type for an address space
786  /// qualified type with the specified type and address space.
787  ///
788  /// The resulting type has a union of the qualifiers from T and the address
789  /// space. If T already has an address space specifier, it is silently
790  /// replaced.
791  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
792
793  /// \brief Return the uniqued reference to the type for an Objective-C
794  /// gc-qualified type.
795  ///
796  /// The retulting type has a union of the qualifiers from T and the gc
797  /// attribute.
798  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
799
800  /// \brief Return the uniqued reference to the type for a \c restrict
801  /// qualified type.
802  ///
803  /// The resulting type has a union of the qualifiers from \p T and
804  /// \c restrict.
805  QualType getRestrictType(QualType T) const {
806    return T.withFastQualifiers(Qualifiers::Restrict);
807  }
808
809  /// \brief Return the uniqued reference to the type for a \c volatile
810  /// qualified type.
811  ///
812  /// The resulting type has a union of the qualifiers from \p T and
813  /// \c volatile.
814  QualType getVolatileType(QualType T) const {
815    return T.withFastQualifiers(Qualifiers::Volatile);
816  }
817
818  /// \brief Return the uniqued reference to the type for a \c const
819  /// qualified type.
820  ///
821  /// The resulting type has a union of the qualifiers from \p T and \c const.
822  ///
823  /// It can be reasonably expected that this will always be equivalent to
824  /// calling T.withConst().
825  QualType getConstType(QualType T) const { return T.withConst(); }
826
827  /// \brief Change the ExtInfo on a function type.
828  const FunctionType *adjustFunctionType(const FunctionType *Fn,
829                                         FunctionType::ExtInfo EInfo);
830
831  /// \brief Return the uniqued reference to the type for a complex
832  /// number with the specified element type.
833  QualType getComplexType(QualType T) const;
834  CanQualType getComplexType(CanQualType T) const {
835    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
836  }
837
838  /// \brief Return the uniqued reference to the type for a pointer to
839  /// the specified type.
840  QualType getPointerType(QualType T) const;
841  CanQualType getPointerType(CanQualType T) const {
842    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
843  }
844
845  /// \brief Return the uniqued reference to the atomic type for the specified
846  /// type.
847  QualType getAtomicType(QualType T) const;
848
849  /// \brief Return the uniqued reference to the type for a block of the
850  /// specified type.
851  QualType getBlockPointerType(QualType T) const;
852
853  /// Gets the struct used to keep track of the descriptor for pointer to
854  /// blocks.
855  QualType getBlockDescriptorType() const;
856
857  /// Gets the struct used to keep track of the extended descriptor for
858  /// pointer to blocks.
859  QualType getBlockDescriptorExtendedType() const;
860
861  void setcudaConfigureCallDecl(FunctionDecl *FD) {
862    cudaConfigureCallDecl = FD;
863  }
864  FunctionDecl *getcudaConfigureCallDecl() {
865    return cudaConfigureCallDecl;
866  }
867
868  /// Returns true iff we need copy/dispose helpers for the given type.
869  bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
870
871
872  /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
873  /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
874  /// has extended lifetime.
875  bool getByrefLifetime(QualType Ty,
876                        Qualifiers::ObjCLifetime &Lifetime,
877                        bool &HasByrefExtendedLayout) const;
878
879  /// \brief Return the uniqued reference to the type for an lvalue reference
880  /// to the specified type.
881  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
882    const;
883
884  /// \brief Return the uniqued reference to the type for an rvalue reference
885  /// to the specified type.
886  QualType getRValueReferenceType(QualType T) const;
887
888  /// \brief Return the uniqued reference to the type for a member pointer to
889  /// the specified type in the specified class.
890  ///
891  /// The class \p Cls is a \c Type because it could be a dependent name.
892  QualType getMemberPointerType(QualType T, const Type *Cls) const;
893
894  /// \brief Return a non-unique reference to the type for a variable array of
895  /// the specified element type.
896  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
897                                ArrayType::ArraySizeModifier ASM,
898                                unsigned IndexTypeQuals,
899                                SourceRange Brackets) const;
900
901  /// \brief Return a non-unique reference to the type for a dependently-sized
902  /// array of the specified element type.
903  ///
904  /// FIXME: We will need these to be uniqued, or at least comparable, at some
905  /// point.
906  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
907                                      ArrayType::ArraySizeModifier ASM,
908                                      unsigned IndexTypeQuals,
909                                      SourceRange Brackets) const;
910
911  /// \brief Return a unique reference to the type for an incomplete array of
912  /// the specified element type.
913  QualType getIncompleteArrayType(QualType EltTy,
914                                  ArrayType::ArraySizeModifier ASM,
915                                  unsigned IndexTypeQuals) const;
916
917  /// \brief Return the unique reference to the type for a constant array of
918  /// the specified element type.
919  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
920                                ArrayType::ArraySizeModifier ASM,
921                                unsigned IndexTypeQuals) const;
922
923  /// \brief Returns a vla type where known sizes are replaced with [*].
924  QualType getVariableArrayDecayedType(QualType Ty) const;
925
926  /// \brief Return the unique reference to a vector type of the specified
927  /// element type and size.
928  ///
929  /// \pre \p VectorType must be a built-in type.
930  QualType getVectorType(QualType VectorType, unsigned NumElts,
931                         VectorType::VectorKind VecKind) const;
932
933  /// \brief Return the unique reference to an extended vector type
934  /// of the specified element type and size.
935  ///
936  /// \pre \p VectorType must be a built-in type.
937  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
938
939  /// \pre Return a non-unique reference to the type for a dependently-sized
940  /// vector of the specified element type.
941  ///
942  /// FIXME: We will need these to be uniqued, or at least comparable, at some
943  /// point.
944  QualType getDependentSizedExtVectorType(QualType VectorType,
945                                          Expr *SizeExpr,
946                                          SourceLocation AttrLoc) const;
947
948  /// \brief Return a K&R style C function type like 'int()'.
949  QualType getFunctionNoProtoType(QualType ResultTy,
950                                  const FunctionType::ExtInfo &Info) const;
951
952  QualType getFunctionNoProtoType(QualType ResultTy) const {
953    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
954  }
955
956  /// \brief Return a normal function type with a typed argument list.
957  QualType getFunctionType(QualType ResultTy,
958                           const QualType *Args, unsigned NumArgs,
959                           const FunctionProtoType::ExtProtoInfo &EPI) const;
960
961  /// \brief Return the unique reference to the type for the specified type
962  /// declaration.
963  QualType getTypeDeclType(const TypeDecl *Decl,
964                           const TypeDecl *PrevDecl = 0) const {
965    assert(Decl && "Passed null for Decl param");
966    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
967
968    if (PrevDecl) {
969      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
970      Decl->TypeForDecl = PrevDecl->TypeForDecl;
971      return QualType(PrevDecl->TypeForDecl, 0);
972    }
973
974    return getTypeDeclTypeSlow(Decl);
975  }
976
977  /// \brief Return the unique reference to the type for the specified
978  /// typedef-name decl.
979  QualType getTypedefType(const TypedefNameDecl *Decl,
980                          QualType Canon = QualType()) const;
981
982  QualType getRecordType(const RecordDecl *Decl) const;
983
984  QualType getEnumType(const EnumDecl *Decl) const;
985
986  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
987
988  QualType getAttributedType(AttributedType::Kind attrKind,
989                             QualType modifiedType,
990                             QualType equivalentType);
991
992  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
993                                        QualType Replacement) const;
994  QualType getSubstTemplateTypeParmPackType(
995                                          const TemplateTypeParmType *Replaced,
996                                            const TemplateArgument &ArgPack);
997
998  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
999                                   bool ParameterPack,
1000                                   TemplateTypeParmDecl *ParmDecl = 0) const;
1001
1002  QualType getTemplateSpecializationType(TemplateName T,
1003                                         const TemplateArgument *Args,
1004                                         unsigned NumArgs,
1005                                         QualType Canon = QualType()) const;
1006
1007  QualType getCanonicalTemplateSpecializationType(TemplateName T,
1008                                                  const TemplateArgument *Args,
1009                                                  unsigned NumArgs) const;
1010
1011  QualType getTemplateSpecializationType(TemplateName T,
1012                                         const TemplateArgumentListInfo &Args,
1013                                         QualType Canon = QualType()) const;
1014
1015  TypeSourceInfo *
1016  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1017                                    const TemplateArgumentListInfo &Args,
1018                                    QualType Canon = QualType()) const;
1019
1020  QualType getParenType(QualType NamedType) const;
1021
1022  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1023                             NestedNameSpecifier *NNS,
1024                             QualType NamedType) const;
1025  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1026                                NestedNameSpecifier *NNS,
1027                                const IdentifierInfo *Name,
1028                                QualType Canon = QualType()) const;
1029
1030  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1031                                                  NestedNameSpecifier *NNS,
1032                                                  const IdentifierInfo *Name,
1033                                    const TemplateArgumentListInfo &Args) const;
1034  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1035                                                  NestedNameSpecifier *NNS,
1036                                                  const IdentifierInfo *Name,
1037                                                  unsigned NumArgs,
1038                                            const TemplateArgument *Args) const;
1039
1040  QualType getPackExpansionType(QualType Pattern,
1041                                llvm::Optional<unsigned> NumExpansions);
1042
1043  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1044                                ObjCInterfaceDecl *PrevDecl = 0) const;
1045
1046  QualType getObjCObjectType(QualType Base,
1047                             ObjCProtocolDecl * const *Protocols,
1048                             unsigned NumProtocols) const;
1049
1050  /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1051  QualType getObjCObjectPointerType(QualType OIT) const;
1052
1053  /// \brief GCC extension.
1054  QualType getTypeOfExprType(Expr *e) const;
1055  QualType getTypeOfType(QualType t) const;
1056
1057  /// \brief C++11 decltype.
1058  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1059
1060  /// \brief Unary type transforms
1061  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1062                                 UnaryTransformType::UTTKind UKind) const;
1063
1064  /// \brief C++11 deduced auto type.
1065  QualType getAutoType(QualType DeducedType) const;
1066
1067  /// \brief C++11 deduction pattern for 'auto' type.
1068  QualType getAutoDeductType() const;
1069
1070  /// \brief C++11 deduction pattern for 'auto &&' type.
1071  QualType getAutoRRefDeductType() const;
1072
1073  /// \brief Return the unique reference to the type for the specified TagDecl
1074  /// (struct/union/class/enum) decl.
1075  QualType getTagDeclType(const TagDecl *Decl) const;
1076
1077  /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1078  /// <stddef.h>.
1079  ///
1080  /// The sizeof operator requires this (C99 6.5.3.4p4).
1081  CanQualType getSizeType() const;
1082
1083  /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1084  /// <stdint.h>.
1085  CanQualType getIntMaxType() const;
1086
1087  /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1088  /// <stdint.h>.
1089  CanQualType getUIntMaxType() const;
1090
1091  /// \brief In C++, this returns the unique wchar_t type.  In C99, this
1092  /// returns a type compatible with the type defined in <stddef.h> as defined
1093  /// by the target.
1094  QualType getWCharType() const { return WCharTy; }
1095
1096  /// \brief Return the type of "signed wchar_t".
1097  ///
1098  /// Used when in C++, as a GCC extension.
1099  QualType getSignedWCharType() const;
1100
1101  /// \brief Return the type of "unsigned wchar_t".
1102  ///
1103  /// Used when in C++, as a GCC extension.
1104  QualType getUnsignedWCharType() const;
1105
1106  /// \brief In C99, this returns a type compatible with the type
1107  /// defined in <stddef.h> as defined by the target.
1108  QualType getWIntType() const { return WIntTy; }
1109
1110  /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1111  /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1112  QualType getPointerDiffType() const;
1113
1114  /// \brief Return the unique type for "pid_t" defined in
1115  /// <sys/types.h>. We need this to compute the correct type for vfork().
1116  QualType getProcessIDType() const;
1117
1118  /// \brief Return the C structure type used to represent constant CFStrings.
1119  QualType getCFConstantStringType() const;
1120
1121  /// \brief Returns the C struct type for objc_super
1122  QualType getObjCSuperType() const;
1123  void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1124
1125  /// Get the structure type used to representation CFStrings, or NULL
1126  /// if it hasn't yet been built.
1127  QualType getRawCFConstantStringType() const {
1128    if (CFConstantStringTypeDecl)
1129      return getTagDeclType(CFConstantStringTypeDecl);
1130    return QualType();
1131  }
1132  void setCFConstantStringType(QualType T);
1133
1134  // This setter/getter represents the ObjC type for an NSConstantString.
1135  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1136  QualType getObjCConstantStringInterface() const {
1137    return ObjCConstantStringType;
1138  }
1139
1140  QualType getObjCNSStringType() const {
1141    return ObjCNSStringType;
1142  }
1143
1144  void setObjCNSStringType(QualType T) {
1145    ObjCNSStringType = T;
1146  }
1147
1148  /// \brief Retrieve the type that \c id has been defined to, which may be
1149  /// different from the built-in \c id if \c id has been typedef'd.
1150  QualType getObjCIdRedefinitionType() const {
1151    if (ObjCIdRedefinitionType.isNull())
1152      return getObjCIdType();
1153    return ObjCIdRedefinitionType;
1154  }
1155
1156  /// \brief Set the user-written type that redefines \c id.
1157  void setObjCIdRedefinitionType(QualType RedefType) {
1158    ObjCIdRedefinitionType = RedefType;
1159  }
1160
1161  /// \brief Retrieve the type that \c Class has been defined to, which may be
1162  /// different from the built-in \c Class if \c Class has been typedef'd.
1163  QualType getObjCClassRedefinitionType() const {
1164    if (ObjCClassRedefinitionType.isNull())
1165      return getObjCClassType();
1166    return ObjCClassRedefinitionType;
1167  }
1168
1169  /// \brief Set the user-written type that redefines 'SEL'.
1170  void setObjCClassRedefinitionType(QualType RedefType) {
1171    ObjCClassRedefinitionType = RedefType;
1172  }
1173
1174  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1175  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1176  QualType getObjCSelRedefinitionType() const {
1177    if (ObjCSelRedefinitionType.isNull())
1178      return getObjCSelType();
1179    return ObjCSelRedefinitionType;
1180  }
1181
1182
1183  /// \brief Set the user-written type that redefines 'SEL'.
1184  void setObjCSelRedefinitionType(QualType RedefType) {
1185    ObjCSelRedefinitionType = RedefType;
1186  }
1187
1188  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1189  /// otherwise, returns a NULL type;
1190  QualType getObjCInstanceType() {
1191    return getTypeDeclType(getObjCInstanceTypeDecl());
1192  }
1193
1194  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1195  /// "instancetype" type.
1196  TypedefDecl *getObjCInstanceTypeDecl();
1197
1198  /// \brief Set the type for the C FILE type.
1199  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1200
1201  /// \brief Retrieve the C FILE type.
1202  QualType getFILEType() const {
1203    if (FILEDecl)
1204      return getTypeDeclType(FILEDecl);
1205    return QualType();
1206  }
1207
1208  /// \brief Set the type for the C jmp_buf type.
1209  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1210    this->jmp_bufDecl = jmp_bufDecl;
1211  }
1212
1213  /// \brief Retrieve the C jmp_buf type.
1214  QualType getjmp_bufType() const {
1215    if (jmp_bufDecl)
1216      return getTypeDeclType(jmp_bufDecl);
1217    return QualType();
1218  }
1219
1220  /// \brief Set the type for the C sigjmp_buf type.
1221  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1222    this->sigjmp_bufDecl = sigjmp_bufDecl;
1223  }
1224
1225  /// \brief Retrieve the C sigjmp_buf type.
1226  QualType getsigjmp_bufType() const {
1227    if (sigjmp_bufDecl)
1228      return getTypeDeclType(sigjmp_bufDecl);
1229    return QualType();
1230  }
1231
1232  /// \brief Set the type for the C ucontext_t type.
1233  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1234    this->ucontext_tDecl = ucontext_tDecl;
1235  }
1236
1237  /// \brief Retrieve the C ucontext_t type.
1238  QualType getucontext_tType() const {
1239    if (ucontext_tDecl)
1240      return getTypeDeclType(ucontext_tDecl);
1241    return QualType();
1242  }
1243
1244  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1245  QualType getLogicalOperationType() const {
1246    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1247  }
1248
1249  /// \brief Emit the Objective-CC type encoding for the given type \p T into
1250  /// \p S.
1251  ///
1252  /// If \p Field is specified then record field names are also encoded.
1253  void getObjCEncodingForType(QualType T, std::string &S,
1254                              const FieldDecl *Field=0) const;
1255
1256  void getLegacyIntegralTypeEncoding(QualType &t) const;
1257
1258  /// \brief Put the string version of the type qualifiers \p QT into \p S.
1259  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1260                                       std::string &S) const;
1261
1262  /// \brief Emit the encoded type for the function \p Decl into \p S.
1263  ///
1264  /// This is in the same format as Objective-C method encodings.
1265  ///
1266  /// \returns true if an error occurred (e.g., because one of the parameter
1267  /// types is incomplete), false otherwise.
1268  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1269
1270  /// \brief Emit the encoded type for the method declaration \p Decl into
1271  /// \p S.
1272  ///
1273  /// \returns true if an error occurred (e.g., because one of the parameter
1274  /// types is incomplete), false otherwise.
1275  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1276                                    bool Extended = false)
1277    const;
1278
1279  /// \brief Return the encoded type for this block declaration.
1280  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1281
1282  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1283  /// this method declaration. If non-NULL, Container must be either
1284  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1285  /// only be NULL when getting encodings for protocol properties.
1286  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1287                                      const Decl *Container,
1288                                      std::string &S) const;
1289
1290  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1291                                      ObjCProtocolDecl *rProto) const;
1292
1293  /// \brief Return the size of type \p T for Objective-C encoding purpose,
1294  /// in characters.
1295  CharUnits getObjCEncodingTypeSize(QualType T) const;
1296
1297  /// \brief Retrieve the typedef corresponding to the predefined \c id type
1298  /// in Objective-C.
1299  TypedefDecl *getObjCIdDecl() const;
1300
1301  /// \brief Represents the Objective-CC \c id type.
1302  ///
1303  /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1304  /// pointer type, a pointer to a struct.
1305  QualType getObjCIdType() const {
1306    return getTypeDeclType(getObjCIdDecl());
1307  }
1308
1309  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1310  /// in Objective-C.
1311  TypedefDecl *getObjCSelDecl() const;
1312
1313  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1314  /// 'SEL' type.
1315  QualType getObjCSelType() const {
1316    return getTypeDeclType(getObjCSelDecl());
1317  }
1318
1319  /// \brief Retrieve the typedef declaration corresponding to the predefined
1320  /// Objective-C 'Class' type.
1321  TypedefDecl *getObjCClassDecl() const;
1322
1323  /// \brief Represents the Objective-C \c Class type.
1324  ///
1325  /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1326  /// pointer type, a pointer to a struct.
1327  QualType getObjCClassType() const {
1328    return getTypeDeclType(getObjCClassDecl());
1329  }
1330
1331  /// \brief Retrieve the Objective-C class declaration corresponding to
1332  /// the predefined \c Protocol class.
1333  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1334
1335  /// \brief Retrieve declaration of 'BOOL' typedef
1336  TypedefDecl *getBOOLDecl() const {
1337    return BOOLDecl;
1338  }
1339
1340  /// \brief Save declaration of 'BOOL' typedef
1341  void setBOOLDecl(TypedefDecl *TD) {
1342    BOOLDecl = TD;
1343  }
1344
1345  /// \brief type of 'BOOL' type.
1346  QualType getBOOLType() const {
1347    return getTypeDeclType(getBOOLDecl());
1348  }
1349
1350  /// \brief Retrieve the type of the Objective-C \c Protocol class.
1351  QualType getObjCProtoType() const {
1352    return getObjCInterfaceType(getObjCProtocolDecl());
1353  }
1354
1355  /// \brief Retrieve the C type declaration corresponding to the predefined
1356  /// \c __builtin_va_list type.
1357  TypedefDecl *getBuiltinVaListDecl() const;
1358
1359  /// \brief Retrieve the type of the \c __builtin_va_list type.
1360  QualType getBuiltinVaListType() const {
1361    return getTypeDeclType(getBuiltinVaListDecl());
1362  }
1363
1364  /// \brief Retrieve the C type declaration corresponding to the predefined
1365  /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1366  /// for some targets.
1367  QualType getVaListTagType() const;
1368
1369  /// \brief Return a type with additional \c const, \c volatile, or
1370  /// \c restrict qualifiers.
1371  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1372    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1373  }
1374
1375  /// \brief Un-split a SplitQualType.
1376  QualType getQualifiedType(SplitQualType split) const {
1377    return getQualifiedType(split.Ty, split.Quals);
1378  }
1379
1380  /// \brief Return a type with additional qualifiers.
1381  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1382    if (!Qs.hasNonFastQualifiers())
1383      return T.withFastQualifiers(Qs.getFastQualifiers());
1384    QualifierCollector Qc(Qs);
1385    const Type *Ptr = Qc.strip(T);
1386    return getExtQualType(Ptr, Qc);
1387  }
1388
1389  /// \brief Return a type with additional qualifiers.
1390  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1391    if (!Qs.hasNonFastQualifiers())
1392      return QualType(T, Qs.getFastQualifiers());
1393    return getExtQualType(T, Qs);
1394  }
1395
1396  /// \brief Return a type with the given lifetime qualifier.
1397  ///
1398  /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1399  QualType getLifetimeQualifiedType(QualType type,
1400                                    Qualifiers::ObjCLifetime lifetime) {
1401    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1402    assert(lifetime != Qualifiers::OCL_None);
1403
1404    Qualifiers qs;
1405    qs.addObjCLifetime(lifetime);
1406    return getQualifiedType(type, qs);
1407  }
1408
1409  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1410                                         SourceLocation NameLoc) const;
1411
1412  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1413                                         UnresolvedSetIterator End) const;
1414
1415  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1416                                        bool TemplateKeyword,
1417                                        TemplateDecl *Template) const;
1418
1419  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1420                                        const IdentifierInfo *Name) const;
1421  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1422                                        OverloadedOperatorKind Operator) const;
1423  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1424                                            TemplateName replacement) const;
1425  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1426                                        const TemplateArgument &ArgPack) const;
1427
1428  enum GetBuiltinTypeError {
1429    GE_None,              ///< No error
1430    GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1431    GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1432    GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1433  };
1434
1435  /// \brief Return the type for the specified builtin.
1436  ///
1437  /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1438  /// arguments to the builtin that are required to be integer constant
1439  /// expressions.
1440  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1441                          unsigned *IntegerConstantArgs = 0) const;
1442
1443private:
1444  CanQualType getFromTargetType(unsigned Type) const;
1445  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1446
1447  //===--------------------------------------------------------------------===//
1448  //                         Type Predicates.
1449  //===--------------------------------------------------------------------===//
1450
1451public:
1452  /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1453  /// collection attributes.
1454  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1455
1456  /// \brief Return true if the given vector types are of the same unqualified
1457  /// type or if they are equivalent to the same GCC vector type.
1458  ///
1459  /// \note This ignores whether they are target-specific (AltiVec or Neon)
1460  /// types.
1461  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1462
1463  /// \brief Return true if this is an \c NSObject object with its \c NSObject
1464  /// attribute set.
1465  static bool isObjCNSObjectType(QualType Ty) {
1466    return Ty->isObjCNSObjectType();
1467  }
1468
1469  //===--------------------------------------------------------------------===//
1470  //                         Type Sizing and Analysis
1471  //===--------------------------------------------------------------------===//
1472
1473  /// \brief Return the APFloat 'semantics' for the specified scalar floating
1474  /// point type.
1475  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1476
1477  /// \brief Get the size and alignment of the specified complete type in bits.
1478  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1479  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1480    return getTypeInfo(T.getTypePtr());
1481  }
1482
1483  /// \brief Return the size of the specified (complete) type \p T, in bits.
1484  uint64_t getTypeSize(QualType T) const {
1485    return getTypeInfo(T).first;
1486  }
1487  uint64_t getTypeSize(const Type *T) const {
1488    return getTypeInfo(T).first;
1489  }
1490
1491  /// \brief Return the size of the character type, in bits.
1492  uint64_t getCharWidth() const {
1493    return getTypeSize(CharTy);
1494  }
1495
1496  /// \brief Convert a size in bits to a size in characters.
1497  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1498
1499  /// \brief Convert a size in characters to a size in bits.
1500  int64_t toBits(CharUnits CharSize) const;
1501
1502  /// \brief Return the size of the specified (complete) type \p T, in
1503  /// characters.
1504  CharUnits getTypeSizeInChars(QualType T) const;
1505  CharUnits getTypeSizeInChars(const Type *T) const;
1506
1507  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1508  /// bits.
1509  unsigned getTypeAlign(QualType T) const {
1510    return getTypeInfo(T).second;
1511  }
1512  unsigned getTypeAlign(const Type *T) const {
1513    return getTypeInfo(T).second;
1514  }
1515
1516  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1517  /// characters.
1518  CharUnits getTypeAlignInChars(QualType T) const;
1519  CharUnits getTypeAlignInChars(const Type *T) const;
1520
1521  // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1522  // type is a record, its data size is returned.
1523  std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1524
1525  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1526  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1527
1528  /// \brief Return the "preferred" alignment of the specified type \p T for
1529  /// the current target, in bits.
1530  ///
1531  /// This can be different than the ABI alignment in cases where it is
1532  /// beneficial for performance to overalign a data type.
1533  unsigned getPreferredTypeAlign(const Type *T) const;
1534
1535  /// \brief Return a conservative estimate of the alignment of the specified
1536  /// decl \p D.
1537  ///
1538  /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1539  /// alignment.
1540  ///
1541  /// If \p RefAsPointee, references are treated like their underlying type
1542  /// (for alignof), else they're treated like pointers (for CodeGen).
1543  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1544
1545  /// \brief Get or compute information about the layout of the specified
1546  /// record (struct/union/class) \p D, which indicates its size and field
1547  /// position information.
1548  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1549
1550  /// \brief Get or compute information about the layout of the specified
1551  /// Objective-C interface.
1552  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1553    const;
1554
1555  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1556                        bool Simple = false) const;
1557
1558  /// \brief Get or compute information about the layout of the specified
1559  /// Objective-C implementation.
1560  ///
1561  /// This may differ from the interface if synthesized ivars are present.
1562  const ASTRecordLayout &
1563  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1564
1565  /// \brief Get the key function for the given record decl, or NULL if there
1566  /// isn't one.
1567  ///
1568  /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1569  ///
1570  /// ...the first non-pure virtual function that is not inline at the point
1571  /// of class definition.
1572  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1573
1574  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1575  uint64_t getFieldOffset(const ValueDecl *FD) const;
1576
1577  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1578
1579  MangleContext *createMangleContext();
1580
1581  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1582                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1583
1584  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1585  void CollectInheritedProtocols(const Decl *CDecl,
1586                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1587
1588  //===--------------------------------------------------------------------===//
1589  //                            Type Operators
1590  //===--------------------------------------------------------------------===//
1591
1592  /// \brief Return the canonical (structural) type corresponding to the
1593  /// specified potentially non-canonical type \p T.
1594  ///
1595  /// The non-canonical version of a type may have many "decorated" versions of
1596  /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
1597  /// returned type is guaranteed to be free of any of these, allowing two
1598  /// canonical types to be compared for exact equality with a simple pointer
1599  /// comparison.
1600  CanQualType getCanonicalType(QualType T) const {
1601    return CanQualType::CreateUnsafe(T.getCanonicalType());
1602  }
1603
1604  const Type *getCanonicalType(const Type *T) const {
1605    return T->getCanonicalTypeInternal().getTypePtr();
1606  }
1607
1608  /// \brief Return the canonical parameter type corresponding to the specific
1609  /// potentially non-canonical one.
1610  ///
1611  /// Qualifiers are stripped off, functions are turned into function
1612  /// pointers, and arrays decay one level into pointers.
1613  CanQualType getCanonicalParamType(QualType T) const;
1614
1615  /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1616  bool hasSameType(QualType T1, QualType T2) const {
1617    return getCanonicalType(T1) == getCanonicalType(T2);
1618  }
1619
1620  /// \brief Return this type as a completely-unqualified array type,
1621  /// capturing the qualifiers in \p Quals.
1622  ///
1623  /// This will remove the minimal amount of sugaring from the types, similar
1624  /// to the behavior of QualType::getUnqualifiedType().
1625  ///
1626  /// \param T is the qualified type, which may be an ArrayType
1627  ///
1628  /// \param Quals will receive the full set of qualifiers that were
1629  /// applied to the array.
1630  ///
1631  /// \returns if this is an array type, the completely unqualified array type
1632  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1633  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1634
1635  /// \brief Determine whether the given types are equivalent after
1636  /// cvr-qualifiers have been removed.
1637  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1638    return getCanonicalType(T1).getTypePtr() ==
1639           getCanonicalType(T2).getTypePtr();
1640  }
1641
1642  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1643
1644  /// \brief Retrieves the "canonical" nested name specifier for a
1645  /// given nested name specifier.
1646  ///
1647  /// The canonical nested name specifier is a nested name specifier
1648  /// that uniquely identifies a type or namespace within the type
1649  /// system. For example, given:
1650  ///
1651  /// \code
1652  /// namespace N {
1653  ///   struct S {
1654  ///     template<typename T> struct X { typename T* type; };
1655  ///   };
1656  /// }
1657  ///
1658  /// template<typename T> struct Y {
1659  ///   typename N::S::X<T>::type member;
1660  /// };
1661  /// \endcode
1662  ///
1663  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1664  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1665  /// by declarations in the type system and the canonical type for
1666  /// the template type parameter 'T' is template-param-0-0.
1667  NestedNameSpecifier *
1668  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1669
1670  /// \brief Retrieves the default calling convention to use for
1671  /// C++ instance methods.
1672  CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1673
1674  /// \brief Retrieves the canonical representation of the given
1675  /// calling convention.
1676  CallingConv getCanonicalCallConv(CallingConv CC) const;
1677
1678  /// \brief Determines whether two calling conventions name the same
1679  /// calling convention.
1680  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1681    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1682  }
1683
1684  /// \brief Retrieves the "canonical" template name that refers to a
1685  /// given template.
1686  ///
1687  /// The canonical template name is the simplest expression that can
1688  /// be used to refer to a given template. For most templates, this
1689  /// expression is just the template declaration itself. For example,
1690  /// the template std::vector can be referred to via a variety of
1691  /// names---std::vector, \::std::vector, vector (if vector is in
1692  /// scope), etc.---but all of these names map down to the same
1693  /// TemplateDecl, which is used to form the canonical template name.
1694  ///
1695  /// Dependent template names are more interesting. Here, the
1696  /// template name could be something like T::template apply or
1697  /// std::allocator<T>::template rebind, where the nested name
1698  /// specifier itself is dependent. In this case, the canonical
1699  /// template name uses the shortest form of the dependent
1700  /// nested-name-specifier, which itself contains all canonical
1701  /// types, values, and templates.
1702  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1703
1704  /// \brief Determine whether the given template names refer to the same
1705  /// template.
1706  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1707
1708  /// \brief Retrieve the "canonical" template argument.
1709  ///
1710  /// The canonical template argument is the simplest template argument
1711  /// (which may be a type, value, expression, or declaration) that
1712  /// expresses the value of the argument.
1713  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1714    const;
1715
1716  /// Type Query functions.  If the type is an instance of the specified class,
1717  /// return the Type pointer for the underlying maximally pretty type.  This
1718  /// is a member of ASTContext because this may need to do some amount of
1719  /// canonicalization, e.g. to move type qualifiers into the element type.
1720  const ArrayType *getAsArrayType(QualType T) const;
1721  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1722    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1723  }
1724  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1725    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1726  }
1727  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1728    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1729  }
1730  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1731    const {
1732    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1733  }
1734
1735  /// \brief Return the innermost element type of an array type.
1736  ///
1737  /// For example, will return "int" for int[m][n]
1738  QualType getBaseElementType(const ArrayType *VAT) const;
1739
1740  /// \brief Return the innermost element type of a type (which needn't
1741  /// actually be an array type).
1742  QualType getBaseElementType(QualType QT) const;
1743
1744  /// \brief Return number of constant array elements.
1745  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1746
1747  /// \brief Perform adjustment on the parameter type of a function.
1748  ///
1749  /// This routine adjusts the given parameter type @p T to the actual
1750  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1751  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1752  QualType getAdjustedParameterType(QualType T) const;
1753
1754  /// \brief Retrieve the parameter type as adjusted for use in the signature
1755  /// of a function, decaying array and function types and removing top-level
1756  /// cv-qualifiers.
1757  QualType getSignatureParameterType(QualType T) const;
1758
1759  /// \brief Return the properly qualified result of decaying the specified
1760  /// array type to a pointer.
1761  ///
1762  /// This operation is non-trivial when handling typedefs etc.  The canonical
1763  /// type of \p T must be an array type, this returns a pointer to a properly
1764  /// qualified element of the array.
1765  ///
1766  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1767  QualType getArrayDecayedType(QualType T) const;
1768
1769  /// \brief Return the type that \p PromotableType will promote to: C99
1770  /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1771  QualType getPromotedIntegerType(QualType PromotableType) const;
1772
1773  /// \brief Recurses in pointer/array types until it finds an Objective-C
1774  /// retainable type and returns its ownership.
1775  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1776
1777  /// \brief Whether this is a promotable bitfield reference according
1778  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1779  ///
1780  /// \returns the type this bit-field will promote to, or NULL if no
1781  /// promotion occurs.
1782  QualType isPromotableBitField(Expr *E) const;
1783
1784  /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1785  ///
1786  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1787  /// \p LHS < \p RHS, return -1.
1788  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1789
1790  /// \brief Compare the rank of the two specified floating point types,
1791  /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1792  ///
1793  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1794  /// \p LHS < \p RHS, return -1.
1795  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1796
1797  /// \brief Return a real floating point or a complex type (based on
1798  /// \p typeDomain/\p typeSize).
1799  ///
1800  /// \param typeDomain a real floating point or complex type.
1801  /// \param typeSize a real floating point or complex type.
1802  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1803                                             QualType typeDomain) const;
1804
1805  unsigned getTargetAddressSpace(QualType T) const {
1806    return getTargetAddressSpace(T.getQualifiers());
1807  }
1808
1809  unsigned getTargetAddressSpace(Qualifiers Q) const {
1810    return getTargetAddressSpace(Q.getAddressSpace());
1811  }
1812
1813  unsigned getTargetAddressSpace(unsigned AS) const {
1814    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1815      return AS;
1816    else
1817      return (*AddrSpaceMap)[AS - LangAS::Offset];
1818  }
1819
1820private:
1821  // Helper for integer ordering
1822  unsigned getIntegerRank(const Type *T) const;
1823
1824public:
1825
1826  //===--------------------------------------------------------------------===//
1827  //                    Type Compatibility Predicates
1828  //===--------------------------------------------------------------------===//
1829
1830  /// Compatibility predicates used to check assignment expressions.
1831  bool typesAreCompatible(QualType T1, QualType T2,
1832                          bool CompareUnqualified = false); // C99 6.2.7p1
1833
1834  bool propertyTypesAreCompatible(QualType, QualType);
1835  bool typesAreBlockPointerCompatible(QualType, QualType);
1836
1837  bool isObjCIdType(QualType T) const {
1838    return T == getObjCIdType();
1839  }
1840  bool isObjCClassType(QualType T) const {
1841    return T == getObjCClassType();
1842  }
1843  bool isObjCSelType(QualType T) const {
1844    return T == getObjCSelType();
1845  }
1846  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1847  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1848                                         bool ForCompare);
1849
1850  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1851
1852  // Check the safety of assignment from LHS to RHS
1853  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1854                               const ObjCObjectPointerType *RHSOPT);
1855  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1856                               const ObjCObjectType *RHS);
1857  bool canAssignObjCInterfacesInBlockPointer(
1858                                          const ObjCObjectPointerType *LHSOPT,
1859                                          const ObjCObjectPointerType *RHSOPT,
1860                                          bool BlockReturnType);
1861  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1862  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1863                                   const ObjCObjectPointerType *RHSOPT);
1864  bool canBindObjCObjectType(QualType To, QualType From);
1865
1866  // Functions for calculating composite types
1867  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1868                      bool Unqualified = false, bool BlockReturnType = false);
1869  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1870                              bool Unqualified = false);
1871  QualType mergeFunctionArgumentTypes(QualType, QualType,
1872                                      bool OfBlockPointer=false,
1873                                      bool Unqualified = false);
1874  QualType mergeTransparentUnionType(QualType, QualType,
1875                                     bool OfBlockPointer=false,
1876                                     bool Unqualified = false);
1877
1878  QualType mergeObjCGCQualifiers(QualType, QualType);
1879
1880  bool FunctionTypesMatchOnNSConsumedAttrs(
1881         const FunctionProtoType *FromFunctionType,
1882         const FunctionProtoType *ToFunctionType);
1883
1884  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1885    ObjCLayouts[CD] = 0;
1886  }
1887
1888  //===--------------------------------------------------------------------===//
1889  //                    Integer Predicates
1890  //===--------------------------------------------------------------------===//
1891
1892  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1893  // of bits in an integer type excluding any padding bits.
1894  unsigned getIntWidth(QualType T) const;
1895
1896  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1897  // unsigned integer type.  This method takes a signed type, and returns the
1898  // corresponding unsigned integer type.
1899  QualType getCorrespondingUnsignedType(QualType T) const;
1900
1901  //===--------------------------------------------------------------------===//
1902  //                    Type Iterators.
1903  //===--------------------------------------------------------------------===//
1904
1905  typedef std::vector<Type*>::iterator       type_iterator;
1906  typedef std::vector<Type*>::const_iterator const_type_iterator;
1907
1908  type_iterator types_begin() { return Types.begin(); }
1909  type_iterator types_end() { return Types.end(); }
1910  const_type_iterator types_begin() const { return Types.begin(); }
1911  const_type_iterator types_end() const { return Types.end(); }
1912
1913  //===--------------------------------------------------------------------===//
1914  //                    Integer Values
1915  //===--------------------------------------------------------------------===//
1916
1917  /// \brief Make an APSInt of the appropriate width and signedness for the
1918  /// given \p Value and integer \p Type.
1919  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1920    llvm::APSInt Res(getIntWidth(Type),
1921                     !Type->isSignedIntegerOrEnumerationType());
1922    Res = Value;
1923    return Res;
1924  }
1925
1926  bool isSentinelNullExpr(const Expr *E);
1927
1928  /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
1929  /// none exists.
1930  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1931  /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
1932  /// none exists.
1933  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1934
1935  /// \brief Return true if there is at least one \@implementation in the TU.
1936  bool AnyObjCImplementation() {
1937    return !ObjCImpls.empty();
1938  }
1939
1940  /// \brief Set the implementation of ObjCInterfaceDecl.
1941  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1942                             ObjCImplementationDecl *ImplD);
1943  /// \brief Set the implementation of ObjCCategoryDecl.
1944  void setObjCImplementation(ObjCCategoryDecl *CatD,
1945                             ObjCCategoryImplDecl *ImplD);
1946
1947  /// \brief Get the duplicate declaration of a ObjCMethod in the same
1948  /// interface, or null if none exists.
1949  const ObjCMethodDecl *getObjCMethodRedeclaration(
1950                                               const ObjCMethodDecl *MD) const {
1951    return ObjCMethodRedecls.lookup(MD);
1952  }
1953
1954  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1955                                  const ObjCMethodDecl *Redecl) {
1956    assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
1957    ObjCMethodRedecls[MD] = Redecl;
1958  }
1959
1960  /// \brief Returns the Objective-C interface that \p ND belongs to if it is
1961  /// an Objective-C method/property/ivar etc. that is part of an interface,
1962  /// otherwise returns null.
1963  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1964
1965  /// \brief Set the copy inialization expression of a block var decl.
1966  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1967  /// \brief Get the copy initialization expression of the VarDecl \p VD, or
1968  /// NULL if none exists.
1969  Expr *getBlockVarCopyInits(const VarDecl* VD);
1970
1971  /// \brief Allocate an uninitialized TypeSourceInfo.
1972  ///
1973  /// The caller should initialize the memory held by TypeSourceInfo using
1974  /// the TypeLoc wrappers.
1975  ///
1976  /// \param T the type that will be the basis for type source info. This type
1977  /// should refer to how the declarator was written in source code, not to
1978  /// what type semantic analysis resolved the declarator to.
1979  ///
1980  /// \param Size the size of the type info to create, or 0 if the size
1981  /// should be calculated based on the type.
1982  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1983
1984  /// \brief Allocate a TypeSourceInfo where all locations have been
1985  /// initialized to a given location, which defaults to the empty
1986  /// location.
1987  TypeSourceInfo *
1988  getTrivialTypeSourceInfo(QualType T,
1989                           SourceLocation Loc = SourceLocation()) const;
1990
1991  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1992
1993  /// \brief Add a deallocation callback that will be invoked when the
1994  /// ASTContext is destroyed.
1995  ///
1996  /// \param Callback A callback function that will be invoked on destruction.
1997  ///
1998  /// \param Data Pointer data that will be provided to the callback function
1999  /// when it is called.
2000  void AddDeallocation(void (*Callback)(void*), void *Data);
2001
2002  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
2003  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2004
2005  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2006  /// lazily, only when used; this is only relevant for function or file scoped
2007  /// var definitions.
2008  ///
2009  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2010  /// it is not used.
2011  bool DeclMustBeEmitted(const Decl *D);
2012
2013  void addUnnamedTag(const TagDecl *Tag);
2014  int getUnnamedTagManglingNumber(const TagDecl *Tag) const;
2015
2016  /// \brief Retrieve the lambda mangling number for a lambda expression.
2017  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
2018
2019  /// \brief Used by ParmVarDecl to store on the side the
2020  /// index of the parameter when it exceeds the size of the normal bitfield.
2021  void setParameterIndex(const ParmVarDecl *D, unsigned index);
2022
2023  /// \brief Used by ParmVarDecl to retrieve on the side the
2024  /// index of the parameter when it exceeds the size of the normal bitfield.
2025  unsigned getParameterIndex(const ParmVarDecl *D) const;
2026
2027  //===--------------------------------------------------------------------===//
2028  //                    Statistics
2029  //===--------------------------------------------------------------------===//
2030
2031  /// \brief The number of implicitly-declared default constructors.
2032  static unsigned NumImplicitDefaultConstructors;
2033
2034  /// \brief The number of implicitly-declared default constructors for
2035  /// which declarations were built.
2036  static unsigned NumImplicitDefaultConstructorsDeclared;
2037
2038  /// \brief The number of implicitly-declared copy constructors.
2039  static unsigned NumImplicitCopyConstructors;
2040
2041  /// \brief The number of implicitly-declared copy constructors for
2042  /// which declarations were built.
2043  static unsigned NumImplicitCopyConstructorsDeclared;
2044
2045  /// \brief The number of implicitly-declared move constructors.
2046  static unsigned NumImplicitMoveConstructors;
2047
2048  /// \brief The number of implicitly-declared move constructors for
2049  /// which declarations were built.
2050  static unsigned NumImplicitMoveConstructorsDeclared;
2051
2052  /// \brief The number of implicitly-declared copy assignment operators.
2053  static unsigned NumImplicitCopyAssignmentOperators;
2054
2055  /// \brief The number of implicitly-declared copy assignment operators for
2056  /// which declarations were built.
2057  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2058
2059  /// \brief The number of implicitly-declared move assignment operators.
2060  static unsigned NumImplicitMoveAssignmentOperators;
2061
2062  /// \brief The number of implicitly-declared move assignment operators for
2063  /// which declarations were built.
2064  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2065
2066  /// \brief The number of implicitly-declared destructors.
2067  static unsigned NumImplicitDestructors;
2068
2069  /// \brief The number of implicitly-declared destructors for which
2070  /// declarations were built.
2071  static unsigned NumImplicitDestructorsDeclared;
2072
2073private:
2074  ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2075  void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2076
2077public:
2078  /// \brief Initialize built-in types.
2079  ///
2080  /// This routine may only be invoked once for a given ASTContext object.
2081  /// It is normally invoked by the ASTContext constructor. However, the
2082  /// constructor can be asked to delay initialization, which places the burden
2083  /// of calling this function on the user of that object.
2084  ///
2085  /// \param Target The target
2086  void InitBuiltinTypes(const TargetInfo &Target);
2087
2088private:
2089  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2090
2091  // Return the Objective-C type encoding for a given type.
2092  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2093                                  bool ExpandPointedToStructures,
2094                                  bool ExpandStructures,
2095                                  const FieldDecl *Field,
2096                                  bool OutermostType = false,
2097                                  bool EncodingProperty = false,
2098                                  bool StructField = false,
2099                                  bool EncodeBlockParameters = false,
2100                                  bool EncodeClassNames = false) const;
2101
2102  // Adds the encoding of the structure's members.
2103  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2104                                       const FieldDecl *Field,
2105                                       bool includeVBases = true) const;
2106
2107  // Adds the encoding of a method parameter or return type.
2108  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2109                                         QualType T, std::string& S,
2110                                         bool Extended) const;
2111
2112  const ASTRecordLayout &
2113  getObjCLayout(const ObjCInterfaceDecl *D,
2114                const ObjCImplementationDecl *Impl) const;
2115
2116private:
2117  /// \brief A set of deallocations that should be performed when the
2118  /// ASTContext is destroyed.
2119  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2120
2121  // FIXME: This currently contains the set of StoredDeclMaps used
2122  // by DeclContext objects.  This probably should not be in ASTContext,
2123  // but we include it here so that ASTContext can quickly deallocate them.
2124  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2125
2126  /// \brief A counter used to uniquely identify "blocks".
2127  mutable unsigned int UniqueBlockByRefTypeID;
2128
2129  friend class DeclContext;
2130  friend class DeclarationNameTable;
2131  void ReleaseDeclContextMaps();
2132};
2133
2134/// \brief Utility function for constructing a nullary selector.
2135static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2136  IdentifierInfo* II = &Ctx.Idents.get(name);
2137  return Ctx.Selectors.getSelector(0, &II);
2138}
2139
2140/// \brief Utility function for constructing an unary selector.
2141static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2142  IdentifierInfo* II = &Ctx.Idents.get(name);
2143  return Ctx.Selectors.getSelector(1, &II);
2144}
2145
2146}  // end namespace clang
2147
2148// operator new and delete aren't allowed inside namespaces.
2149
2150/// @brief Placement new for using the ASTContext's allocator.
2151///
2152/// This placement form of operator new uses the ASTContext's allocator for
2153/// obtaining memory.
2154///
2155/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2156/// here need to also be made there.
2157///
2158/// We intentionally avoid using a nothrow specification here so that the calls
2159/// to this operator will not perform a null check on the result -- the
2160/// underlying allocator never returns null pointers.
2161///
2162/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2163/// @code
2164/// // Default alignment (8)
2165/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2166/// // Specific alignment
2167/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2168/// @endcode
2169/// Please note that you cannot use delete on the pointer; it must be
2170/// deallocated using an explicit destructor call followed by
2171/// @c Context.Deallocate(Ptr).
2172///
2173/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2174/// @param C The ASTContext that provides the allocator.
2175/// @param Alignment The alignment of the allocated memory (if the underlying
2176///                  allocator supports it).
2177/// @return The allocated memory. Could be NULL.
2178inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2179                          size_t Alignment) {
2180  return C.Allocate(Bytes, Alignment);
2181}
2182/// @brief Placement delete companion to the new above.
2183///
2184/// This operator is just a companion to the new above. There is no way of
2185/// invoking it directly; see the new operator for more details. This operator
2186/// is called implicitly by the compiler if a placement new expression using
2187/// the ASTContext throws in the object constructor.
2188inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2189  C.Deallocate(Ptr);
2190}
2191
2192/// This placement form of operator new[] uses the ASTContext's allocator for
2193/// obtaining memory.
2194///
2195/// We intentionally avoid using a nothrow specification here so that the calls
2196/// to this operator will not perform a null check on the result -- the
2197/// underlying allocator never returns null pointers.
2198///
2199/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2200/// @code
2201/// // Default alignment (8)
2202/// char *data = new (Context) char[10];
2203/// // Specific alignment
2204/// char *data = new (Context, 4) char[10];
2205/// @endcode
2206/// Please note that you cannot use delete on the pointer; it must be
2207/// deallocated using an explicit destructor call followed by
2208/// @c Context.Deallocate(Ptr).
2209///
2210/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2211/// @param C The ASTContext that provides the allocator.
2212/// @param Alignment The alignment of the allocated memory (if the underlying
2213///                  allocator supports it).
2214/// @return The allocated memory. Could be NULL.
2215inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2216                            size_t Alignment = 8) {
2217  return C.Allocate(Bytes, Alignment);
2218}
2219
2220/// @brief Placement delete[] companion to the new[] above.
2221///
2222/// This operator is just a companion to the new[] above. There is no way of
2223/// invoking it directly; see the new[] operator for more details. This operator
2224/// is called implicitly by the compiler if a placement new[] expression using
2225/// the ASTContext throws in the object constructor.
2226inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2227  C.Deallocate(Ptr);
2228}
2229
2230#endif
2231