ASTContext.h revision 0a74a4ccc4ecfe1a2792ab72c83815323d8fc914
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  /// Return parsed documentation comment attached to a given declaration.
585  /// Returns NULL if no comment is attached. Does not look at any
586  /// redeclarations of the declaration.
587  comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
588
589  comments::FullComment *cloneFullComment(comments::FullComment *FC,
590                                         const Decl *D) const;
591
592private:
593  mutable comments::CommandTraits CommentCommandTraits;
594
595public:
596  comments::CommandTraits &getCommentCommandTraits() const {
597    return CommentCommandTraits;
598  }
599
600  /// \brief Retrieve the attributes for the given declaration.
601  AttrVec& getDeclAttrs(const Decl *D);
602
603  /// \brief Erase the attributes corresponding to the given declaration.
604  void eraseDeclAttrs(const Decl *D);
605
606  /// \brief If this variable is an instantiated static data member of a
607  /// class template specialization, returns the templated static data member
608  /// from which it was instantiated.
609  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
610                                                           const VarDecl *Var);
611
612  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
613
614  void setClassScopeSpecializationPattern(FunctionDecl *FD,
615                                          FunctionDecl *Pattern);
616
617  /// \brief Note that the static data member \p Inst is an instantiation of
618  /// the static data member template \p Tmpl of a class template.
619  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
620                                           TemplateSpecializationKind TSK,
621                        SourceLocation PointOfInstantiation = SourceLocation());
622
623  /// \brief If the given using decl \p Inst is an instantiation of a
624  /// (possibly unresolved) using decl from a template instantiation,
625  /// return it.
626  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
627
628  /// \brief Remember that the using decl \p Inst is an instantiation
629  /// of the using decl \p Pattern of a class template.
630  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
631
632  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
633                                          UsingShadowDecl *Pattern);
634  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
635
636  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
637
638  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
639
640  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
641  /// the non-bitfield \p LastFD.
642  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
643                                      const FieldDecl *LastFD) const;
644
645  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
646  /// the bitfield \p LastFD.
647  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
648                                   const FieldDecl *LastFD) const;
649
650  /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
651  /// \p LastFD.
652  bool BitfieldFollowsBitfield(const FieldDecl *FD,
653                               const FieldDecl *LastFD) const;
654
655  /// \brief Return \c true if \p FD is not a bitfield which follows the
656  /// bitfield \p LastFD.
657  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
658                                  const FieldDecl *LastFD) const;
659
660  /// \brief Return \c true if \p FD is a bitfield which follows the
661  /// non-bitfield \p LastFD.
662  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
663                                  const FieldDecl *LastFD) const;
664
665  // Access to the set of methods overridden by the given C++ method.
666  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
667  overridden_cxx_method_iterator
668  overridden_methods_begin(const CXXMethodDecl *Method) const;
669
670  overridden_cxx_method_iterator
671  overridden_methods_end(const CXXMethodDecl *Method) const;
672
673  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
674
675  /// \brief Note that the given C++ \p Method overrides the given \p
676  /// Overridden method.
677  void addOverriddenMethod(const CXXMethodDecl *Method,
678                           const CXXMethodDecl *Overridden);
679
680  /// \brief Return C++ or ObjC overridden methods for the given \p Method.
681  ///
682  /// An ObjC method is considered to override any method in the class's
683  /// base classes, its protocols, or its categories' protocols, that has
684  /// the same selector and is of the same kind (class or instance).
685  /// A method in an implementation is not considered as overriding the same
686  /// method in the interface or its categories.
687  void getOverriddenMethods(
688                        const NamedDecl *Method,
689                        SmallVectorImpl<const NamedDecl *> &Overridden) const;
690
691  /// \brief Notify the AST context that a new import declaration has been
692  /// parsed or implicitly created within this translation unit.
693  void addedLocalImportDecl(ImportDecl *Import);
694
695  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
696    return Import->NextLocalImport;
697  }
698
699  /// \brief Iterator that visits import declarations.
700  class import_iterator {
701    ImportDecl *Import;
702
703  public:
704    typedef ImportDecl               *value_type;
705    typedef ImportDecl               *reference;
706    typedef ImportDecl               *pointer;
707    typedef int                       difference_type;
708    typedef std::forward_iterator_tag iterator_category;
709
710    import_iterator() : Import() { }
711    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
712
713    reference operator*() const { return Import; }
714    pointer operator->() const { return Import; }
715
716    import_iterator &operator++() {
717      Import = ASTContext::getNextLocalImport(Import);
718      return *this;
719    }
720
721    import_iterator operator++(int) {
722      import_iterator Other(*this);
723      ++(*this);
724      return Other;
725    }
726
727    friend bool operator==(import_iterator X, import_iterator Y) {
728      return X.Import == Y.Import;
729    }
730
731    friend bool operator!=(import_iterator X, import_iterator Y) {
732      return X.Import != Y.Import;
733    }
734  };
735
736  import_iterator local_import_begin() const {
737    return import_iterator(FirstLocalImport);
738  }
739  import_iterator local_import_end() const { return import_iterator(); }
740
741  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
742
743
744  // Builtin Types.
745  CanQualType VoidTy;
746  CanQualType BoolTy;
747  CanQualType CharTy;
748  CanQualType WCharTy;  // [C++ 3.9.1p5].
749  CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
750  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
751  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
752  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
753  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
754  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
755  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
756  CanQualType FloatTy, DoubleTy, LongDoubleTy;
757  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
758  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
759  CanQualType VoidPtrTy, NullPtrTy;
760  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
761  CanQualType BuiltinFnTy;
762  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
763  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
764  CanQualType ObjCBuiltinBoolTy;
765  CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
766  CanQualType OCLImage2dTy, OCLImage2dArrayTy;
767  CanQualType OCLImage3dTy;
768  CanQualType OCLSamplerTy, OCLEventTy;
769
770  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
771  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
772  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
773
774  // Type used to help define __builtin_va_list for some targets.
775  // The type is built when constructing 'BuiltinVaListDecl'.
776  mutable QualType VaListTagTy;
777
778  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
779             IdentifierTable &idents, SelectorTable &sels,
780             Builtin::Context &builtins,
781             unsigned size_reserve,
782             bool DelayInitialization = false);
783
784  ~ASTContext();
785
786  /// \brief Attach an external AST source to the AST context.
787  ///
788  /// The external AST source provides the ability to load parts of
789  /// the abstract syntax tree as needed from some external storage,
790  /// e.g., a precompiled header.
791  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
792
793  /// \brief Retrieve a pointer to the external AST source associated
794  /// with this AST context, if any.
795  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
796
797  /// \brief Attach an AST mutation listener to the AST context.
798  ///
799  /// The AST mutation listener provides the ability to track modifications to
800  /// the abstract syntax tree entities committed after they were initially
801  /// created.
802  void setASTMutationListener(ASTMutationListener *Listener) {
803    this->Listener = Listener;
804  }
805
806  /// \brief Retrieve a pointer to the AST mutation listener associated
807  /// with this AST context, if any.
808  ASTMutationListener *getASTMutationListener() const { return Listener; }
809
810  void PrintStats() const;
811  const SmallVectorImpl<Type *>& getTypes() const { return Types; }
812
813  /// \brief Retrieve the declaration for the 128-bit signed integer type.
814  TypedefDecl *getInt128Decl() const;
815
816  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
817  TypedefDecl *getUInt128Decl() const;
818
819  //===--------------------------------------------------------------------===//
820  //                           Type Constructors
821  //===--------------------------------------------------------------------===//
822
823private:
824  /// \brief Return a type with extended qualifiers.
825  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
826
827  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
828
829public:
830  /// \brief Return the uniqued reference to the type for an address space
831  /// qualified type with the specified type and address space.
832  ///
833  /// The resulting type has a union of the qualifiers from T and the address
834  /// space. If T already has an address space specifier, it is silently
835  /// replaced.
836  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
837
838  /// \brief Return the uniqued reference to the type for an Objective-C
839  /// gc-qualified type.
840  ///
841  /// The retulting type has a union of the qualifiers from T and the gc
842  /// attribute.
843  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
844
845  /// \brief Return the uniqued reference to the type for a \c restrict
846  /// qualified type.
847  ///
848  /// The resulting type has a union of the qualifiers from \p T and
849  /// \c restrict.
850  QualType getRestrictType(QualType T) const {
851    return T.withFastQualifiers(Qualifiers::Restrict);
852  }
853
854  /// \brief Return the uniqued reference to the type for a \c volatile
855  /// qualified type.
856  ///
857  /// The resulting type has a union of the qualifiers from \p T and
858  /// \c volatile.
859  QualType getVolatileType(QualType T) const {
860    return T.withFastQualifiers(Qualifiers::Volatile);
861  }
862
863  /// \brief Return the uniqued reference to the type for a \c const
864  /// qualified type.
865  ///
866  /// The resulting type has a union of the qualifiers from \p T and \c const.
867  ///
868  /// It can be reasonably expected that this will always be equivalent to
869  /// calling T.withConst().
870  QualType getConstType(QualType T) const { return T.withConst(); }
871
872  /// \brief Change the ExtInfo on a function type.
873  const FunctionType *adjustFunctionType(const FunctionType *Fn,
874                                         FunctionType::ExtInfo EInfo);
875
876  /// \brief Change the result type of a function type once it is deduced.
877  void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
878
879  /// \brief Return the uniqued reference to the type for a complex
880  /// number with the specified element type.
881  QualType getComplexType(QualType T) const;
882  CanQualType getComplexType(CanQualType T) const {
883    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
884  }
885
886  /// \brief Return the uniqued reference to the type for a pointer to
887  /// the specified type.
888  QualType getPointerType(QualType T) const;
889  CanQualType getPointerType(CanQualType T) const {
890    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
891  }
892
893  /// \brief Return the uniqued reference to the atomic type for the specified
894  /// type.
895  QualType getAtomicType(QualType T) const;
896
897  /// \brief Return the uniqued reference to the type for a block of the
898  /// specified type.
899  QualType getBlockPointerType(QualType T) const;
900
901  /// Gets the struct used to keep track of the descriptor for pointer to
902  /// blocks.
903  QualType getBlockDescriptorType() const;
904
905  /// Gets the struct used to keep track of the extended descriptor for
906  /// pointer to blocks.
907  QualType getBlockDescriptorExtendedType() const;
908
909  void setcudaConfigureCallDecl(FunctionDecl *FD) {
910    cudaConfigureCallDecl = FD;
911  }
912  FunctionDecl *getcudaConfigureCallDecl() {
913    return cudaConfigureCallDecl;
914  }
915
916  /// Returns true iff we need copy/dispose helpers for the given type.
917  bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
918
919
920  /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
921  /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
922  /// has extended lifetime.
923  bool getByrefLifetime(QualType Ty,
924                        Qualifiers::ObjCLifetime &Lifetime,
925                        bool &HasByrefExtendedLayout) const;
926
927  /// \brief Return the uniqued reference to the type for an lvalue reference
928  /// to the specified type.
929  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
930    const;
931
932  /// \brief Return the uniqued reference to the type for an rvalue reference
933  /// to the specified type.
934  QualType getRValueReferenceType(QualType T) const;
935
936  /// \brief Return the uniqued reference to the type for a member pointer to
937  /// the specified type in the specified class.
938  ///
939  /// The class \p Cls is a \c Type because it could be a dependent name.
940  QualType getMemberPointerType(QualType T, const Type *Cls) const;
941
942  /// \brief Return a non-unique reference to the type for a variable array of
943  /// the specified element type.
944  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
945                                ArrayType::ArraySizeModifier ASM,
946                                unsigned IndexTypeQuals,
947                                SourceRange Brackets) const;
948
949  /// \brief Return a non-unique reference to the type for a dependently-sized
950  /// array of the specified element type.
951  ///
952  /// FIXME: We will need these to be uniqued, or at least comparable, at some
953  /// point.
954  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
955                                      ArrayType::ArraySizeModifier ASM,
956                                      unsigned IndexTypeQuals,
957                                      SourceRange Brackets) const;
958
959  /// \brief Return a unique reference to the type for an incomplete array of
960  /// the specified element type.
961  QualType getIncompleteArrayType(QualType EltTy,
962                                  ArrayType::ArraySizeModifier ASM,
963                                  unsigned IndexTypeQuals) const;
964
965  /// \brief Return the unique reference to the type for a constant array of
966  /// the specified element type.
967  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
968                                ArrayType::ArraySizeModifier ASM,
969                                unsigned IndexTypeQuals) const;
970
971  /// \brief Returns a vla type where known sizes are replaced with [*].
972  QualType getVariableArrayDecayedType(QualType Ty) const;
973
974  /// \brief Return the unique reference to a vector type of the specified
975  /// element type and size.
976  ///
977  /// \pre \p VectorType must be a built-in type.
978  QualType getVectorType(QualType VectorType, unsigned NumElts,
979                         VectorType::VectorKind VecKind) const;
980
981  /// \brief Return the unique reference to an extended vector type
982  /// of the specified element type and size.
983  ///
984  /// \pre \p VectorType must be a built-in type.
985  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
986
987  /// \pre Return a non-unique reference to the type for a dependently-sized
988  /// vector of the specified element type.
989  ///
990  /// FIXME: We will need these to be uniqued, or at least comparable, at some
991  /// point.
992  QualType getDependentSizedExtVectorType(QualType VectorType,
993                                          Expr *SizeExpr,
994                                          SourceLocation AttrLoc) const;
995
996  /// \brief Return a K&R style C function type like 'int()'.
997  QualType getFunctionNoProtoType(QualType ResultTy,
998                                  const FunctionType::ExtInfo &Info) const;
999
1000  QualType getFunctionNoProtoType(QualType ResultTy) const {
1001    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1002  }
1003
1004  /// \brief Return a normal function type with a typed argument list.
1005  QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1006                           const FunctionProtoType::ExtProtoInfo &EPI) const;
1007
1008  /// \brief Return the unique reference to the type for the specified type
1009  /// declaration.
1010  QualType getTypeDeclType(const TypeDecl *Decl,
1011                           const TypeDecl *PrevDecl = 0) const {
1012    assert(Decl && "Passed null for Decl param");
1013    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1014
1015    if (PrevDecl) {
1016      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1017      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1018      return QualType(PrevDecl->TypeForDecl, 0);
1019    }
1020
1021    return getTypeDeclTypeSlow(Decl);
1022  }
1023
1024  /// \brief Return the unique reference to the type for the specified
1025  /// typedef-name decl.
1026  QualType getTypedefType(const TypedefNameDecl *Decl,
1027                          QualType Canon = QualType()) const;
1028
1029  QualType getRecordType(const RecordDecl *Decl) const;
1030
1031  QualType getEnumType(const EnumDecl *Decl) const;
1032
1033  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1034
1035  QualType getAttributedType(AttributedType::Kind attrKind,
1036                             QualType modifiedType,
1037                             QualType equivalentType);
1038
1039  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1040                                        QualType Replacement) const;
1041  QualType getSubstTemplateTypeParmPackType(
1042                                          const TemplateTypeParmType *Replaced,
1043                                            const TemplateArgument &ArgPack);
1044
1045  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
1046                                   bool ParameterPack,
1047                                   TemplateTypeParmDecl *ParmDecl = 0) const;
1048
1049  QualType getTemplateSpecializationType(TemplateName T,
1050                                         const TemplateArgument *Args,
1051                                         unsigned NumArgs,
1052                                         QualType Canon = QualType()) const;
1053
1054  QualType getCanonicalTemplateSpecializationType(TemplateName T,
1055                                                  const TemplateArgument *Args,
1056                                                  unsigned NumArgs) const;
1057
1058  QualType getTemplateSpecializationType(TemplateName T,
1059                                         const TemplateArgumentListInfo &Args,
1060                                         QualType Canon = QualType()) const;
1061
1062  TypeSourceInfo *
1063  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1064                                    const TemplateArgumentListInfo &Args,
1065                                    QualType Canon = QualType()) const;
1066
1067  QualType getParenType(QualType NamedType) const;
1068
1069  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1070                             NestedNameSpecifier *NNS,
1071                             QualType NamedType) const;
1072  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1073                                NestedNameSpecifier *NNS,
1074                                const IdentifierInfo *Name,
1075                                QualType Canon = QualType()) const;
1076
1077  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1078                                                  NestedNameSpecifier *NNS,
1079                                                  const IdentifierInfo *Name,
1080                                    const TemplateArgumentListInfo &Args) const;
1081  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1082                                                  NestedNameSpecifier *NNS,
1083                                                  const IdentifierInfo *Name,
1084                                                  unsigned NumArgs,
1085                                            const TemplateArgument *Args) const;
1086
1087  QualType getPackExpansionType(QualType Pattern,
1088                                Optional<unsigned> NumExpansions);
1089
1090  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1091                                ObjCInterfaceDecl *PrevDecl = 0) const;
1092
1093  QualType getObjCObjectType(QualType Base,
1094                             ObjCProtocolDecl * const *Protocols,
1095                             unsigned NumProtocols) const;
1096
1097  /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1098  QualType getObjCObjectPointerType(QualType OIT) const;
1099
1100  /// \brief GCC extension.
1101  QualType getTypeOfExprType(Expr *e) const;
1102  QualType getTypeOfType(QualType t) const;
1103
1104  /// \brief C++11 decltype.
1105  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1106
1107  /// \brief Unary type transforms
1108  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1109                                 UnaryTransformType::UTTKind UKind) const;
1110
1111  /// \brief C++11 deduced auto type.
1112  QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
1113                       bool IsDependent = false) const;
1114
1115  /// \brief C++11 deduction pattern for 'auto' type.
1116  QualType getAutoDeductType() const;
1117
1118  /// \brief C++11 deduction pattern for 'auto &&' type.
1119  QualType getAutoRRefDeductType() const;
1120
1121  /// \brief Return the unique reference to the type for the specified TagDecl
1122  /// (struct/union/class/enum) decl.
1123  QualType getTagDeclType(const TagDecl *Decl) const;
1124
1125  /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1126  /// <stddef.h>.
1127  ///
1128  /// The sizeof operator requires this (C99 6.5.3.4p4).
1129  CanQualType getSizeType() const;
1130
1131  /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1132  /// <stdint.h>.
1133  CanQualType getIntMaxType() const;
1134
1135  /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1136  /// <stdint.h>.
1137  CanQualType getUIntMaxType() const;
1138
1139  /// \brief Return the unique wchar_t type available in C++ (and available as
1140  /// __wchar_t as a Microsoft extension).
1141  QualType getWCharType() const { return WCharTy; }
1142
1143  /// \brief Return the type of wide characters. In C++, this returns the
1144  /// unique wchar_t type. In C99, this returns a type compatible with the type
1145  /// defined in <stddef.h> as defined by the target.
1146  QualType getWideCharType() const { return WideCharTy; }
1147
1148  /// \brief Return the type of "signed wchar_t".
1149  ///
1150  /// Used when in C++, as a GCC extension.
1151  QualType getSignedWCharType() const;
1152
1153  /// \brief Return the type of "unsigned wchar_t".
1154  ///
1155  /// Used when in C++, as a GCC extension.
1156  QualType getUnsignedWCharType() const;
1157
1158  /// \brief In C99, this returns a type compatible with the type
1159  /// defined in <stddef.h> as defined by the target.
1160  QualType getWIntType() const { return WIntTy; }
1161
1162  /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1163  /// as defined by the target.
1164  QualType getIntPtrType() const;
1165
1166  /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1167  /// as defined by the target.
1168  QualType getUIntPtrType() const;
1169
1170  /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1171  /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1172  QualType getPointerDiffType() const;
1173
1174  /// \brief Return the unique type for "pid_t" defined in
1175  /// <sys/types.h>. We need this to compute the correct type for vfork().
1176  QualType getProcessIDType() const;
1177
1178  /// \brief Return the C structure type used to represent constant CFStrings.
1179  QualType getCFConstantStringType() const;
1180
1181  /// \brief Returns the C struct type for objc_super
1182  QualType getObjCSuperType() const;
1183  void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1184
1185  /// Get the structure type used to representation CFStrings, or NULL
1186  /// if it hasn't yet been built.
1187  QualType getRawCFConstantStringType() const {
1188    if (CFConstantStringTypeDecl)
1189      return getTagDeclType(CFConstantStringTypeDecl);
1190    return QualType();
1191  }
1192  void setCFConstantStringType(QualType T);
1193
1194  // This setter/getter represents the ObjC type for an NSConstantString.
1195  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1196  QualType getObjCConstantStringInterface() const {
1197    return ObjCConstantStringType;
1198  }
1199
1200  QualType getObjCNSStringType() const {
1201    return ObjCNSStringType;
1202  }
1203
1204  void setObjCNSStringType(QualType T) {
1205    ObjCNSStringType = T;
1206  }
1207
1208  /// \brief Retrieve the type that \c id has been defined to, which may be
1209  /// different from the built-in \c id if \c id has been typedef'd.
1210  QualType getObjCIdRedefinitionType() const {
1211    if (ObjCIdRedefinitionType.isNull())
1212      return getObjCIdType();
1213    return ObjCIdRedefinitionType;
1214  }
1215
1216  /// \brief Set the user-written type that redefines \c id.
1217  void setObjCIdRedefinitionType(QualType RedefType) {
1218    ObjCIdRedefinitionType = RedefType;
1219  }
1220
1221  /// \brief Retrieve the type that \c Class has been defined to, which may be
1222  /// different from the built-in \c Class if \c Class has been typedef'd.
1223  QualType getObjCClassRedefinitionType() const {
1224    if (ObjCClassRedefinitionType.isNull())
1225      return getObjCClassType();
1226    return ObjCClassRedefinitionType;
1227  }
1228
1229  /// \brief Set the user-written type that redefines 'SEL'.
1230  void setObjCClassRedefinitionType(QualType RedefType) {
1231    ObjCClassRedefinitionType = RedefType;
1232  }
1233
1234  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1235  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1236  QualType getObjCSelRedefinitionType() const {
1237    if (ObjCSelRedefinitionType.isNull())
1238      return getObjCSelType();
1239    return ObjCSelRedefinitionType;
1240  }
1241
1242
1243  /// \brief Set the user-written type that redefines 'SEL'.
1244  void setObjCSelRedefinitionType(QualType RedefType) {
1245    ObjCSelRedefinitionType = RedefType;
1246  }
1247
1248  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1249  /// otherwise, returns a NULL type;
1250  QualType getObjCInstanceType() {
1251    return getTypeDeclType(getObjCInstanceTypeDecl());
1252  }
1253
1254  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1255  /// "instancetype" type.
1256  TypedefDecl *getObjCInstanceTypeDecl();
1257
1258  /// \brief Set the type for the C FILE type.
1259  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1260
1261  /// \brief Retrieve the C FILE type.
1262  QualType getFILEType() const {
1263    if (FILEDecl)
1264      return getTypeDeclType(FILEDecl);
1265    return QualType();
1266  }
1267
1268  /// \brief Set the type for the C jmp_buf type.
1269  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1270    this->jmp_bufDecl = jmp_bufDecl;
1271  }
1272
1273  /// \brief Retrieve the C jmp_buf type.
1274  QualType getjmp_bufType() const {
1275    if (jmp_bufDecl)
1276      return getTypeDeclType(jmp_bufDecl);
1277    return QualType();
1278  }
1279
1280  /// \brief Set the type for the C sigjmp_buf type.
1281  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1282    this->sigjmp_bufDecl = sigjmp_bufDecl;
1283  }
1284
1285  /// \brief Retrieve the C sigjmp_buf type.
1286  QualType getsigjmp_bufType() const {
1287    if (sigjmp_bufDecl)
1288      return getTypeDeclType(sigjmp_bufDecl);
1289    return QualType();
1290  }
1291
1292  /// \brief Set the type for the C ucontext_t type.
1293  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1294    this->ucontext_tDecl = ucontext_tDecl;
1295  }
1296
1297  /// \brief Retrieve the C ucontext_t type.
1298  QualType getucontext_tType() const {
1299    if (ucontext_tDecl)
1300      return getTypeDeclType(ucontext_tDecl);
1301    return QualType();
1302  }
1303
1304  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1305  QualType getLogicalOperationType() const {
1306    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1307  }
1308
1309  /// \brief Emit the Objective-CC type encoding for the given type \p T into
1310  /// \p S.
1311  ///
1312  /// If \p Field is specified then record field names are also encoded.
1313  void getObjCEncodingForType(QualType T, std::string &S,
1314                              const FieldDecl *Field=0) const;
1315
1316  void getLegacyIntegralTypeEncoding(QualType &t) const;
1317
1318  /// \brief Put the string version of the type qualifiers \p QT into \p S.
1319  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1320                                       std::string &S) const;
1321
1322  /// \brief Emit the encoded type for the function \p Decl into \p S.
1323  ///
1324  /// This is in the same format as Objective-C method encodings.
1325  ///
1326  /// \returns true if an error occurred (e.g., because one of the parameter
1327  /// types is incomplete), false otherwise.
1328  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1329
1330  /// \brief Emit the encoded type for the method declaration \p Decl into
1331  /// \p S.
1332  ///
1333  /// \returns true if an error occurred (e.g., because one of the parameter
1334  /// types is incomplete), false otherwise.
1335  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1336                                    bool Extended = false)
1337    const;
1338
1339  /// \brief Return the encoded type for this block declaration.
1340  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1341
1342  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1343  /// this method declaration. If non-NULL, Container must be either
1344  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1345  /// only be NULL when getting encodings for protocol properties.
1346  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1347                                      const Decl *Container,
1348                                      std::string &S) const;
1349
1350  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1351                                      ObjCProtocolDecl *rProto) const;
1352
1353  /// \brief Return the size of type \p T for Objective-C encoding purpose,
1354  /// in characters.
1355  CharUnits getObjCEncodingTypeSize(QualType T) const;
1356
1357  /// \brief Retrieve the typedef corresponding to the predefined \c id type
1358  /// in Objective-C.
1359  TypedefDecl *getObjCIdDecl() const;
1360
1361  /// \brief Represents the Objective-CC \c id type.
1362  ///
1363  /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1364  /// pointer type, a pointer to a struct.
1365  QualType getObjCIdType() const {
1366    return getTypeDeclType(getObjCIdDecl());
1367  }
1368
1369  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1370  /// in Objective-C.
1371  TypedefDecl *getObjCSelDecl() const;
1372
1373  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1374  /// 'SEL' type.
1375  QualType getObjCSelType() const {
1376    return getTypeDeclType(getObjCSelDecl());
1377  }
1378
1379  /// \brief Retrieve the typedef declaration corresponding to the predefined
1380  /// Objective-C 'Class' type.
1381  TypedefDecl *getObjCClassDecl() const;
1382
1383  /// \brief Represents the Objective-C \c Class type.
1384  ///
1385  /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1386  /// pointer type, a pointer to a struct.
1387  QualType getObjCClassType() const {
1388    return getTypeDeclType(getObjCClassDecl());
1389  }
1390
1391  /// \brief Retrieve the Objective-C class declaration corresponding to
1392  /// the predefined \c Protocol class.
1393  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1394
1395  /// \brief Retrieve declaration of 'BOOL' typedef
1396  TypedefDecl *getBOOLDecl() const {
1397    return BOOLDecl;
1398  }
1399
1400  /// \brief Save declaration of 'BOOL' typedef
1401  void setBOOLDecl(TypedefDecl *TD) {
1402    BOOLDecl = TD;
1403  }
1404
1405  /// \brief type of 'BOOL' type.
1406  QualType getBOOLType() const {
1407    return getTypeDeclType(getBOOLDecl());
1408  }
1409
1410  /// \brief Retrieve the type of the Objective-C \c Protocol class.
1411  QualType getObjCProtoType() const {
1412    return getObjCInterfaceType(getObjCProtocolDecl());
1413  }
1414
1415  /// \brief Retrieve the C type declaration corresponding to the predefined
1416  /// \c __builtin_va_list type.
1417  TypedefDecl *getBuiltinVaListDecl() const;
1418
1419  /// \brief Retrieve the type of the \c __builtin_va_list type.
1420  QualType getBuiltinVaListType() const {
1421    return getTypeDeclType(getBuiltinVaListDecl());
1422  }
1423
1424  /// \brief Retrieve the C type declaration corresponding to the predefined
1425  /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1426  /// for some targets.
1427  QualType getVaListTagType() const;
1428
1429  /// \brief Return a type with additional \c const, \c volatile, or
1430  /// \c restrict qualifiers.
1431  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1432    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1433  }
1434
1435  /// \brief Un-split a SplitQualType.
1436  QualType getQualifiedType(SplitQualType split) const {
1437    return getQualifiedType(split.Ty, split.Quals);
1438  }
1439
1440  /// \brief Return a type with additional qualifiers.
1441  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1442    if (!Qs.hasNonFastQualifiers())
1443      return T.withFastQualifiers(Qs.getFastQualifiers());
1444    QualifierCollector Qc(Qs);
1445    const Type *Ptr = Qc.strip(T);
1446    return getExtQualType(Ptr, Qc);
1447  }
1448
1449  /// \brief Return a type with additional qualifiers.
1450  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1451    if (!Qs.hasNonFastQualifiers())
1452      return QualType(T, Qs.getFastQualifiers());
1453    return getExtQualType(T, Qs);
1454  }
1455
1456  /// \brief Return a type with the given lifetime qualifier.
1457  ///
1458  /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1459  QualType getLifetimeQualifiedType(QualType type,
1460                                    Qualifiers::ObjCLifetime lifetime) {
1461    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1462    assert(lifetime != Qualifiers::OCL_None);
1463
1464    Qualifiers qs;
1465    qs.addObjCLifetime(lifetime);
1466    return getQualifiedType(type, qs);
1467  }
1468
1469  /// getUnqualifiedObjCPointerType - Returns version of
1470  /// Objective-C pointer type with lifetime qualifier removed.
1471  QualType getUnqualifiedObjCPointerType(QualType type) const {
1472    if (!type.getTypePtr()->isObjCObjectPointerType() ||
1473        !type.getQualifiers().hasObjCLifetime())
1474      return type;
1475    Qualifiers Qs = type.getQualifiers();
1476    Qs.removeObjCLifetime();
1477    return getQualifiedType(type.getUnqualifiedType(), Qs);
1478  }
1479
1480  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1481                                         SourceLocation NameLoc) const;
1482
1483  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1484                                         UnresolvedSetIterator End) const;
1485
1486  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1487                                        bool TemplateKeyword,
1488                                        TemplateDecl *Template) const;
1489
1490  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1491                                        const IdentifierInfo *Name) const;
1492  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1493                                        OverloadedOperatorKind Operator) const;
1494  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1495                                            TemplateName replacement) const;
1496  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1497                                        const TemplateArgument &ArgPack) const;
1498
1499  enum GetBuiltinTypeError {
1500    GE_None,              ///< No error
1501    GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1502    GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1503    GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1504  };
1505
1506  /// \brief Return the type for the specified builtin.
1507  ///
1508  /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1509  /// arguments to the builtin that are required to be integer constant
1510  /// expressions.
1511  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1512                          unsigned *IntegerConstantArgs = 0) const;
1513
1514private:
1515  CanQualType getFromTargetType(unsigned Type) const;
1516  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1517
1518  //===--------------------------------------------------------------------===//
1519  //                         Type Predicates.
1520  //===--------------------------------------------------------------------===//
1521
1522public:
1523  /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1524  /// collection attributes.
1525  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1526
1527  /// \brief Return true if the given vector types are of the same unqualified
1528  /// type or if they are equivalent to the same GCC vector type.
1529  ///
1530  /// \note This ignores whether they are target-specific (AltiVec or Neon)
1531  /// types.
1532  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1533
1534  /// \brief Return true if this is an \c NSObject object with its \c NSObject
1535  /// attribute set.
1536  static bool isObjCNSObjectType(QualType Ty) {
1537    return Ty->isObjCNSObjectType();
1538  }
1539
1540  //===--------------------------------------------------------------------===//
1541  //                         Type Sizing and Analysis
1542  //===--------------------------------------------------------------------===//
1543
1544  /// \brief Return the APFloat 'semantics' for the specified scalar floating
1545  /// point type.
1546  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1547
1548  /// \brief Get the size and alignment of the specified complete type in bits.
1549  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1550  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1551    return getTypeInfo(T.getTypePtr());
1552  }
1553
1554  /// \brief Return the size of the specified (complete) type \p T, in bits.
1555  uint64_t getTypeSize(QualType T) const {
1556    return getTypeInfo(T).first;
1557  }
1558  uint64_t getTypeSize(const Type *T) const {
1559    return getTypeInfo(T).first;
1560  }
1561
1562  /// \brief Return the size of the character type, in bits.
1563  uint64_t getCharWidth() const {
1564    return getTypeSize(CharTy);
1565  }
1566
1567  /// \brief Convert a size in bits to a size in characters.
1568  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1569
1570  /// \brief Convert a size in characters to a size in bits.
1571  int64_t toBits(CharUnits CharSize) const;
1572
1573  /// \brief Return the size of the specified (complete) type \p T, in
1574  /// characters.
1575  CharUnits getTypeSizeInChars(QualType T) const;
1576  CharUnits getTypeSizeInChars(const Type *T) const;
1577
1578  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1579  /// bits.
1580  unsigned getTypeAlign(QualType T) const {
1581    return getTypeInfo(T).second;
1582  }
1583  unsigned getTypeAlign(const Type *T) const {
1584    return getTypeInfo(T).second;
1585  }
1586
1587  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1588  /// characters.
1589  CharUnits getTypeAlignInChars(QualType T) const;
1590  CharUnits getTypeAlignInChars(const Type *T) const;
1591
1592  // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1593  // type is a record, its data size is returned.
1594  std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1595
1596  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1597  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1598
1599  /// \brief Return the "preferred" alignment of the specified type \p T for
1600  /// the current target, in bits.
1601  ///
1602  /// This can be different than the ABI alignment in cases where it is
1603  /// beneficial for performance to overalign a data type.
1604  unsigned getPreferredTypeAlign(const Type *T) const;
1605
1606  /// \brief Return the alignment in bits that should be given to a
1607  /// global variable with type \p T.
1608  unsigned getAlignOfGlobalVar(QualType T) const;
1609
1610  /// \brief Return the alignment in characters that should be given to a
1611  /// global variable with type \p T.
1612  CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1613
1614  /// \brief Return a conservative estimate of the alignment of the specified
1615  /// decl \p D.
1616  ///
1617  /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1618  /// alignment.
1619  ///
1620  /// If \p RefAsPointee, references are treated like their underlying type
1621  /// (for alignof), else they're treated like pointers (for CodeGen).
1622  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1623
1624  /// \brief Get or compute information about the layout of the specified
1625  /// record (struct/union/class) \p D, which indicates its size and field
1626  /// position information.
1627  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1628
1629  /// \brief Get or compute information about the layout of the specified
1630  /// Objective-C interface.
1631  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1632    const;
1633
1634  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1635                        bool Simple = false) const;
1636
1637  /// \brief Get or compute information about the layout of the specified
1638  /// Objective-C implementation.
1639  ///
1640  /// This may differ from the interface if synthesized ivars are present.
1641  const ASTRecordLayout &
1642  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1643
1644  /// \brief Get our current best idea for the key function of the
1645  /// given record decl, or NULL if there isn't one.
1646  ///
1647  /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1648  ///   ...the first non-pure virtual function that is not inline at the
1649  ///   point of class definition.
1650  ///
1651  /// Other ABIs use the same idea.  However, the ARM C++ ABI ignores
1652  /// virtual functions that are defined 'inline', which means that
1653  /// the result of this computation can change.
1654  const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
1655
1656  /// \brief Observe that the given method cannot be a key function.
1657  /// Checks the key-function cache for the method's class and clears it
1658  /// if matches the given declaration.
1659  ///
1660  /// This is used in ABIs where out-of-line definitions marked
1661  /// inline are not considered to be key functions.
1662  ///
1663  /// \param method should be the declaration from the class definition
1664  void setNonKeyFunction(const CXXMethodDecl *method);
1665
1666  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1667  uint64_t getFieldOffset(const ValueDecl *FD) const;
1668
1669  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1670
1671  MangleContext *createMangleContext();
1672
1673  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1674                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1675
1676  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1677  void CollectInheritedProtocols(const Decl *CDecl,
1678                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1679
1680  //===--------------------------------------------------------------------===//
1681  //                            Type Operators
1682  //===--------------------------------------------------------------------===//
1683
1684  /// \brief Return the canonical (structural) type corresponding to the
1685  /// specified potentially non-canonical type \p T.
1686  ///
1687  /// The non-canonical version of a type may have many "decorated" versions of
1688  /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
1689  /// returned type is guaranteed to be free of any of these, allowing two
1690  /// canonical types to be compared for exact equality with a simple pointer
1691  /// comparison.
1692  CanQualType getCanonicalType(QualType T) const {
1693    return CanQualType::CreateUnsafe(T.getCanonicalType());
1694  }
1695
1696  const Type *getCanonicalType(const Type *T) const {
1697    return T->getCanonicalTypeInternal().getTypePtr();
1698  }
1699
1700  /// \brief Return the canonical parameter type corresponding to the specific
1701  /// potentially non-canonical one.
1702  ///
1703  /// Qualifiers are stripped off, functions are turned into function
1704  /// pointers, and arrays decay one level into pointers.
1705  CanQualType getCanonicalParamType(QualType T) const;
1706
1707  /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1708  bool hasSameType(QualType T1, QualType T2) const {
1709    return getCanonicalType(T1) == getCanonicalType(T2);
1710  }
1711
1712  /// \brief Return this type as a completely-unqualified array type,
1713  /// capturing the qualifiers in \p Quals.
1714  ///
1715  /// This will remove the minimal amount of sugaring from the types, similar
1716  /// to the behavior of QualType::getUnqualifiedType().
1717  ///
1718  /// \param T is the qualified type, which may be an ArrayType
1719  ///
1720  /// \param Quals will receive the full set of qualifiers that were
1721  /// applied to the array.
1722  ///
1723  /// \returns if this is an array type, the completely unqualified array type
1724  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1725  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1726
1727  /// \brief Determine whether the given types are equivalent after
1728  /// cvr-qualifiers have been removed.
1729  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1730    return getCanonicalType(T1).getTypePtr() ==
1731           getCanonicalType(T2).getTypePtr();
1732  }
1733
1734  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1735
1736  /// \brief Retrieves the "canonical" nested name specifier for a
1737  /// given nested name specifier.
1738  ///
1739  /// The canonical nested name specifier is a nested name specifier
1740  /// that uniquely identifies a type or namespace within the type
1741  /// system. For example, given:
1742  ///
1743  /// \code
1744  /// namespace N {
1745  ///   struct S {
1746  ///     template<typename T> struct X { typename T* type; };
1747  ///   };
1748  /// }
1749  ///
1750  /// template<typename T> struct Y {
1751  ///   typename N::S::X<T>::type member;
1752  /// };
1753  /// \endcode
1754  ///
1755  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1756  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1757  /// by declarations in the type system and the canonical type for
1758  /// the template type parameter 'T' is template-param-0-0.
1759  NestedNameSpecifier *
1760  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1761
1762  /// \brief Retrieves the default calling convention to use for
1763  /// C++ instance methods.
1764  CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1765
1766  /// \brief Retrieves the canonical representation of the given
1767  /// calling convention.
1768  CallingConv getCanonicalCallConv(CallingConv CC) const;
1769
1770  /// \brief Determines whether two calling conventions name the same
1771  /// calling convention.
1772  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1773    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1774  }
1775
1776  /// \brief Retrieves the "canonical" template name that refers to a
1777  /// given template.
1778  ///
1779  /// The canonical template name is the simplest expression that can
1780  /// be used to refer to a given template. For most templates, this
1781  /// expression is just the template declaration itself. For example,
1782  /// the template std::vector can be referred to via a variety of
1783  /// names---std::vector, \::std::vector, vector (if vector is in
1784  /// scope), etc.---but all of these names map down to the same
1785  /// TemplateDecl, which is used to form the canonical template name.
1786  ///
1787  /// Dependent template names are more interesting. Here, the
1788  /// template name could be something like T::template apply or
1789  /// std::allocator<T>::template rebind, where the nested name
1790  /// specifier itself is dependent. In this case, the canonical
1791  /// template name uses the shortest form of the dependent
1792  /// nested-name-specifier, which itself contains all canonical
1793  /// types, values, and templates.
1794  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1795
1796  /// \brief Determine whether the given template names refer to the same
1797  /// template.
1798  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1799
1800  /// \brief Retrieve the "canonical" template argument.
1801  ///
1802  /// The canonical template argument is the simplest template argument
1803  /// (which may be a type, value, expression, or declaration) that
1804  /// expresses the value of the argument.
1805  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1806    const;
1807
1808  /// Type Query functions.  If the type is an instance of the specified class,
1809  /// return the Type pointer for the underlying maximally pretty type.  This
1810  /// is a member of ASTContext because this may need to do some amount of
1811  /// canonicalization, e.g. to move type qualifiers into the element type.
1812  const ArrayType *getAsArrayType(QualType T) const;
1813  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1814    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1815  }
1816  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1817    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1818  }
1819  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1820    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1821  }
1822  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1823    const {
1824    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1825  }
1826
1827  /// \brief Return the innermost element type of an array type.
1828  ///
1829  /// For example, will return "int" for int[m][n]
1830  QualType getBaseElementType(const ArrayType *VAT) const;
1831
1832  /// \brief Return the innermost element type of a type (which needn't
1833  /// actually be an array type).
1834  QualType getBaseElementType(QualType QT) const;
1835
1836  /// \brief Return number of constant array elements.
1837  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1838
1839  /// \brief Perform adjustment on the parameter type of a function.
1840  ///
1841  /// This routine adjusts the given parameter type @p T to the actual
1842  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1843  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1844  QualType getAdjustedParameterType(QualType T) const;
1845
1846  /// \brief Retrieve the parameter type as adjusted for use in the signature
1847  /// of a function, decaying array and function types and removing top-level
1848  /// cv-qualifiers.
1849  QualType getSignatureParameterType(QualType T) const;
1850
1851  /// \brief Return the properly qualified result of decaying the specified
1852  /// array type to a pointer.
1853  ///
1854  /// This operation is non-trivial when handling typedefs etc.  The canonical
1855  /// type of \p T must be an array type, this returns a pointer to a properly
1856  /// qualified element of the array.
1857  ///
1858  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1859  QualType getArrayDecayedType(QualType T) const;
1860
1861  /// \brief Return the type that \p PromotableType will promote to: C99
1862  /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1863  QualType getPromotedIntegerType(QualType PromotableType) const;
1864
1865  /// \brief Recurses in pointer/array types until it finds an Objective-C
1866  /// retainable type and returns its ownership.
1867  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1868
1869  /// \brief Whether this is a promotable bitfield reference according
1870  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1871  ///
1872  /// \returns the type this bit-field will promote to, or NULL if no
1873  /// promotion occurs.
1874  QualType isPromotableBitField(Expr *E) const;
1875
1876  /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1877  ///
1878  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1879  /// \p LHS < \p RHS, return -1.
1880  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1881
1882  /// \brief Compare the rank of the two specified floating point types,
1883  /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1884  ///
1885  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1886  /// \p LHS < \p RHS, return -1.
1887  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1888
1889  /// \brief Return a real floating point or a complex type (based on
1890  /// \p typeDomain/\p typeSize).
1891  ///
1892  /// \param typeDomain a real floating point or complex type.
1893  /// \param typeSize a real floating point or complex type.
1894  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1895                                             QualType typeDomain) const;
1896
1897  unsigned getTargetAddressSpace(QualType T) const {
1898    return getTargetAddressSpace(T.getQualifiers());
1899  }
1900
1901  unsigned getTargetAddressSpace(Qualifiers Q) const {
1902    return getTargetAddressSpace(Q.getAddressSpace());
1903  }
1904
1905  unsigned getTargetAddressSpace(unsigned AS) const {
1906    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1907      return AS;
1908    else
1909      return (*AddrSpaceMap)[AS - LangAS::Offset];
1910  }
1911
1912private:
1913  // Helper for integer ordering
1914  unsigned getIntegerRank(const Type *T) const;
1915
1916public:
1917
1918  //===--------------------------------------------------------------------===//
1919  //                    Type Compatibility Predicates
1920  //===--------------------------------------------------------------------===//
1921
1922  /// Compatibility predicates used to check assignment expressions.
1923  bool typesAreCompatible(QualType T1, QualType T2,
1924                          bool CompareUnqualified = false); // C99 6.2.7p1
1925
1926  bool propertyTypesAreCompatible(QualType, QualType);
1927  bool typesAreBlockPointerCompatible(QualType, QualType);
1928
1929  bool isObjCIdType(QualType T) const {
1930    return T == getObjCIdType();
1931  }
1932  bool isObjCClassType(QualType T) const {
1933    return T == getObjCClassType();
1934  }
1935  bool isObjCSelType(QualType T) const {
1936    return T == getObjCSelType();
1937  }
1938  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1939  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1940                                         bool ForCompare);
1941
1942  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1943
1944  // Check the safety of assignment from LHS to RHS
1945  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1946                               const ObjCObjectPointerType *RHSOPT);
1947  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1948                               const ObjCObjectType *RHS);
1949  bool canAssignObjCInterfacesInBlockPointer(
1950                                          const ObjCObjectPointerType *LHSOPT,
1951                                          const ObjCObjectPointerType *RHSOPT,
1952                                          bool BlockReturnType);
1953  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1954  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1955                                   const ObjCObjectPointerType *RHSOPT);
1956  bool canBindObjCObjectType(QualType To, QualType From);
1957
1958  // Functions for calculating composite types
1959  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1960                      bool Unqualified = false, bool BlockReturnType = false);
1961  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1962                              bool Unqualified = false);
1963  QualType mergeFunctionArgumentTypes(QualType, QualType,
1964                                      bool OfBlockPointer=false,
1965                                      bool Unqualified = false);
1966  QualType mergeTransparentUnionType(QualType, QualType,
1967                                     bool OfBlockPointer=false,
1968                                     bool Unqualified = false);
1969
1970  QualType mergeObjCGCQualifiers(QualType, QualType);
1971
1972  bool FunctionTypesMatchOnNSConsumedAttrs(
1973         const FunctionProtoType *FromFunctionType,
1974         const FunctionProtoType *ToFunctionType);
1975
1976  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1977    ObjCLayouts[CD] = 0;
1978  }
1979
1980  //===--------------------------------------------------------------------===//
1981  //                    Integer Predicates
1982  //===--------------------------------------------------------------------===//
1983
1984  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1985  // of bits in an integer type excluding any padding bits.
1986  unsigned getIntWidth(QualType T) const;
1987
1988  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1989  // unsigned integer type.  This method takes a signed type, and returns the
1990  // corresponding unsigned integer type.
1991  QualType getCorrespondingUnsignedType(QualType T) const;
1992
1993  //===--------------------------------------------------------------------===//
1994  //                    Type Iterators.
1995  //===--------------------------------------------------------------------===//
1996
1997  typedef SmallVectorImpl<Type *>::iterator       type_iterator;
1998  typedef SmallVectorImpl<Type *>::const_iterator const_type_iterator;
1999
2000  type_iterator types_begin() { return Types.begin(); }
2001  type_iterator types_end() { return Types.end(); }
2002  const_type_iterator types_begin() const { return Types.begin(); }
2003  const_type_iterator types_end() const { return Types.end(); }
2004
2005  //===--------------------------------------------------------------------===//
2006  //                    Integer Values
2007  //===--------------------------------------------------------------------===//
2008
2009  /// \brief Make an APSInt of the appropriate width and signedness for the
2010  /// given \p Value and integer \p Type.
2011  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2012    llvm::APSInt Res(getIntWidth(Type),
2013                     !Type->isSignedIntegerOrEnumerationType());
2014    Res = Value;
2015    return Res;
2016  }
2017
2018  bool isSentinelNullExpr(const Expr *E);
2019
2020  /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2021  /// none exists.
2022  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2023  /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2024  /// none exists.
2025  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
2026
2027  /// \brief Return true if there is at least one \@implementation in the TU.
2028  bool AnyObjCImplementation() {
2029    return !ObjCImpls.empty();
2030  }
2031
2032  /// \brief Set the implementation of ObjCInterfaceDecl.
2033  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2034                             ObjCImplementationDecl *ImplD);
2035  /// \brief Set the implementation of ObjCCategoryDecl.
2036  void setObjCImplementation(ObjCCategoryDecl *CatD,
2037                             ObjCCategoryImplDecl *ImplD);
2038
2039  /// \brief Get the duplicate declaration of a ObjCMethod in the same
2040  /// interface, or null if none exists.
2041  const ObjCMethodDecl *getObjCMethodRedeclaration(
2042                                               const ObjCMethodDecl *MD) const {
2043    return ObjCMethodRedecls.lookup(MD);
2044  }
2045
2046  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2047                                  const ObjCMethodDecl *Redecl) {
2048    assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2049    ObjCMethodRedecls[MD] = Redecl;
2050  }
2051
2052  /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2053  /// an Objective-C method/property/ivar etc. that is part of an interface,
2054  /// otherwise returns null.
2055  const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2056
2057  /// \brief Set the copy inialization expression of a block var decl.
2058  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2059  /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2060  /// NULL if none exists.
2061  Expr *getBlockVarCopyInits(const VarDecl* VD);
2062
2063  /// \brief Allocate an uninitialized TypeSourceInfo.
2064  ///
2065  /// The caller should initialize the memory held by TypeSourceInfo using
2066  /// the TypeLoc wrappers.
2067  ///
2068  /// \param T the type that will be the basis for type source info. This type
2069  /// should refer to how the declarator was written in source code, not to
2070  /// what type semantic analysis resolved the declarator to.
2071  ///
2072  /// \param Size the size of the type info to create, or 0 if the size
2073  /// should be calculated based on the type.
2074  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2075
2076  /// \brief Allocate a TypeSourceInfo where all locations have been
2077  /// initialized to a given location, which defaults to the empty
2078  /// location.
2079  TypeSourceInfo *
2080  getTrivialTypeSourceInfo(QualType T,
2081                           SourceLocation Loc = SourceLocation()) const;
2082
2083  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
2084
2085  /// \brief Add a deallocation callback that will be invoked when the
2086  /// ASTContext is destroyed.
2087  ///
2088  /// \param Callback A callback function that will be invoked on destruction.
2089  ///
2090  /// \param Data Pointer data that will be provided to the callback function
2091  /// when it is called.
2092  void AddDeallocation(void (*Callback)(void*), void *Data);
2093
2094  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
2095  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2096
2097  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2098  /// lazily, only when used; this is only relevant for function or file scoped
2099  /// var definitions.
2100  ///
2101  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2102  /// it is not used.
2103  bool DeclMustBeEmitted(const Decl *D);
2104
2105  void addUnnamedTag(const TagDecl *Tag);
2106  int getUnnamedTagManglingNumber(const TagDecl *Tag) const;
2107
2108  /// \brief Retrieve the lambda mangling number for a lambda expression.
2109  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
2110
2111  /// \brief Used by ParmVarDecl to store on the side the
2112  /// index of the parameter when it exceeds the size of the normal bitfield.
2113  void setParameterIndex(const ParmVarDecl *D, unsigned index);
2114
2115  /// \brief Used by ParmVarDecl to retrieve on the side the
2116  /// index of the parameter when it exceeds the size of the normal bitfield.
2117  unsigned getParameterIndex(const ParmVarDecl *D) const;
2118
2119  //===--------------------------------------------------------------------===//
2120  //                    Statistics
2121  //===--------------------------------------------------------------------===//
2122
2123  /// \brief The number of implicitly-declared default constructors.
2124  static unsigned NumImplicitDefaultConstructors;
2125
2126  /// \brief The number of implicitly-declared default constructors for
2127  /// which declarations were built.
2128  static unsigned NumImplicitDefaultConstructorsDeclared;
2129
2130  /// \brief The number of implicitly-declared copy constructors.
2131  static unsigned NumImplicitCopyConstructors;
2132
2133  /// \brief The number of implicitly-declared copy constructors for
2134  /// which declarations were built.
2135  static unsigned NumImplicitCopyConstructorsDeclared;
2136
2137  /// \brief The number of implicitly-declared move constructors.
2138  static unsigned NumImplicitMoveConstructors;
2139
2140  /// \brief The number of implicitly-declared move constructors for
2141  /// which declarations were built.
2142  static unsigned NumImplicitMoveConstructorsDeclared;
2143
2144  /// \brief The number of implicitly-declared copy assignment operators.
2145  static unsigned NumImplicitCopyAssignmentOperators;
2146
2147  /// \brief The number of implicitly-declared copy assignment operators for
2148  /// which declarations were built.
2149  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2150
2151  /// \brief The number of implicitly-declared move assignment operators.
2152  static unsigned NumImplicitMoveAssignmentOperators;
2153
2154  /// \brief The number of implicitly-declared move assignment operators for
2155  /// which declarations were built.
2156  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2157
2158  /// \brief The number of implicitly-declared destructors.
2159  static unsigned NumImplicitDestructors;
2160
2161  /// \brief The number of implicitly-declared destructors for which
2162  /// declarations were built.
2163  static unsigned NumImplicitDestructorsDeclared;
2164
2165private:
2166  ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2167  void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2168
2169public:
2170  /// \brief Initialize built-in types.
2171  ///
2172  /// This routine may only be invoked once for a given ASTContext object.
2173  /// It is normally invoked by the ASTContext constructor. However, the
2174  /// constructor can be asked to delay initialization, which places the burden
2175  /// of calling this function on the user of that object.
2176  ///
2177  /// \param Target The target
2178  void InitBuiltinTypes(const TargetInfo &Target);
2179
2180private:
2181  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2182
2183  // Return the Objective-C type encoding for a given type.
2184  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2185                                  bool ExpandPointedToStructures,
2186                                  bool ExpandStructures,
2187                                  const FieldDecl *Field,
2188                                  bool OutermostType = false,
2189                                  bool EncodingProperty = false,
2190                                  bool StructField = false,
2191                                  bool EncodeBlockParameters = false,
2192                                  bool EncodeClassNames = false,
2193                                  bool EncodePointerToObjCTypedef = false) const;
2194
2195  // Adds the encoding of the structure's members.
2196  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2197                                       const FieldDecl *Field,
2198                                       bool includeVBases = true) const;
2199
2200  // Adds the encoding of a method parameter or return type.
2201  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2202                                         QualType T, std::string& S,
2203                                         bool Extended) const;
2204
2205  const ASTRecordLayout &
2206  getObjCLayout(const ObjCInterfaceDecl *D,
2207                const ObjCImplementationDecl *Impl) const;
2208
2209private:
2210  /// \brief A set of deallocations that should be performed when the
2211  /// ASTContext is destroyed.
2212  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2213
2214  // FIXME: This currently contains the set of StoredDeclMaps used
2215  // by DeclContext objects.  This probably should not be in ASTContext,
2216  // but we include it here so that ASTContext can quickly deallocate them.
2217  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2218
2219  /// \brief A counter used to uniquely identify "blocks".
2220  mutable unsigned int UniqueBlockByRefTypeID;
2221
2222  friend class DeclContext;
2223  friend class DeclarationNameTable;
2224  void ReleaseDeclContextMaps();
2225
2226  /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
2227  /// parents as defined by the \c RecursiveASTVisitor.
2228  ///
2229  /// Note that the relationship described here is purely in terms of AST
2230  /// traversal - there are other relationships (for example declaration context)
2231  /// in the AST that are better modeled by special matchers.
2232  ///
2233  /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
2234  class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
2235  public:
2236    /// \brief Builds and returns the translation unit's parent map.
2237    ///
2238    ///  The caller takes ownership of the returned \c ParentMap.
2239    static ParentMap *buildMap(TranslationUnitDecl &TU) {
2240      ParentMapASTVisitor Visitor(new ParentMap);
2241      Visitor.TraverseDecl(&TU);
2242      return Visitor.Parents;
2243    }
2244
2245  private:
2246    typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
2247
2248    ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {
2249    }
2250
2251    bool shouldVisitTemplateInstantiations() const {
2252      return true;
2253    }
2254    bool shouldVisitImplicitCode() const {
2255      return true;
2256    }
2257    // Disables data recursion. We intercept Traverse* methods in the RAV, which
2258    // are not triggered during data recursion.
2259    bool shouldUseDataRecursionFor(clang::Stmt *S) const {
2260      return false;
2261    }
2262
2263    template <typename T>
2264    bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
2265      if (Node == NULL)
2266        return true;
2267      if (ParentStack.size() > 0)
2268        // FIXME: Currently we add the same parent multiple times, for example
2269        // when we visit all subexpressions of template instantiations; this is
2270        // suboptimal, bug benign: the only way to visit those is with
2271        // hasAncestor / hasParent, and those do not create new matches.
2272        // The plan is to enable DynTypedNode to be storable in a map or hash
2273        // map. The main problem there is to implement hash functions /
2274        // comparison operators for all types that DynTypedNode supports that
2275        // do not have pointer identity.
2276        (*Parents)[Node].push_back(ParentStack.back());
2277      ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
2278      bool Result = (this ->* traverse) (Node);
2279      ParentStack.pop_back();
2280      return Result;
2281    }
2282
2283    bool TraverseDecl(Decl *DeclNode) {
2284      return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
2285    }
2286
2287    bool TraverseStmt(Stmt *StmtNode) {
2288      return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
2289    }
2290
2291    ParentMap *Parents;
2292    llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
2293
2294    friend class RecursiveASTVisitor<ParentMapASTVisitor>;
2295  };
2296
2297  llvm::OwningPtr<ParentMap> AllParents;
2298};
2299
2300/// \brief Utility function for constructing a nullary selector.
2301static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2302  IdentifierInfo* II = &Ctx.Idents.get(name);
2303  return Ctx.Selectors.getSelector(0, &II);
2304}
2305
2306/// \brief Utility function for constructing an unary selector.
2307static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2308  IdentifierInfo* II = &Ctx.Idents.get(name);
2309  return Ctx.Selectors.getSelector(1, &II);
2310}
2311
2312}  // end namespace clang
2313
2314// operator new and delete aren't allowed inside namespaces.
2315
2316/// @brief Placement new for using the ASTContext's allocator.
2317///
2318/// This placement form of operator new uses the ASTContext's allocator for
2319/// obtaining memory.
2320///
2321/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2322/// here need to also be made there.
2323///
2324/// We intentionally avoid using a nothrow specification here so that the calls
2325/// to this operator will not perform a null check on the result -- the
2326/// underlying allocator never returns null pointers.
2327///
2328/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2329/// @code
2330/// // Default alignment (8)
2331/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2332/// // Specific alignment
2333/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2334/// @endcode
2335/// Please note that you cannot use delete on the pointer; it must be
2336/// deallocated using an explicit destructor call followed by
2337/// @c Context.Deallocate(Ptr).
2338///
2339/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2340/// @param C The ASTContext that provides the allocator.
2341/// @param Alignment The alignment of the allocated memory (if the underlying
2342///                  allocator supports it).
2343/// @return The allocated memory. Could be NULL.
2344inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2345                          size_t Alignment) {
2346  return C.Allocate(Bytes, Alignment);
2347}
2348/// @brief Placement delete companion to the new above.
2349///
2350/// This operator is just a companion to the new above. There is no way of
2351/// invoking it directly; see the new operator for more details. This operator
2352/// is called implicitly by the compiler if a placement new expression using
2353/// the ASTContext throws in the object constructor.
2354inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2355  C.Deallocate(Ptr);
2356}
2357
2358/// This placement form of operator new[] uses the ASTContext's allocator for
2359/// obtaining memory.
2360///
2361/// We intentionally avoid using a nothrow specification here so that the calls
2362/// to this operator will not perform a null check on the result -- the
2363/// underlying allocator never returns null pointers.
2364///
2365/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2366/// @code
2367/// // Default alignment (8)
2368/// char *data = new (Context) char[10];
2369/// // Specific alignment
2370/// char *data = new (Context, 4) char[10];
2371/// @endcode
2372/// Please note that you cannot use delete on the pointer; it must be
2373/// deallocated using an explicit destructor call followed by
2374/// @c Context.Deallocate(Ptr).
2375///
2376/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2377/// @param C The ASTContext that provides the allocator.
2378/// @param Alignment The alignment of the allocated memory (if the underlying
2379///                  allocator supports it).
2380/// @return The allocated memory. Could be NULL.
2381inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2382                            size_t Alignment = 8) {
2383  return C.Allocate(Bytes, Alignment);
2384}
2385
2386/// @brief Placement delete[] companion to the new[] above.
2387///
2388/// This operator is just a companion to the new[] above. There is no way of
2389/// invoking it directly; see the new[] operator for more details. This operator
2390/// is called implicitly by the compiler if a placement new[] expression using
2391/// the ASTContext throws in the object constructor.
2392inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2393  C.Deallocate(Ptr);
2394}
2395
2396#endif
2397