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