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