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