1 //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the clang::ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15 #define LLVM_CLANG_AST_ASTCONTEXT_H
17 #include "clang/AST/ASTContextAllocate.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/RawCommentList.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/AttrKinds.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/Linkage.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/SanitizerBlacklist.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/Basic/XRayLists.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/IntrusiveRefCntPtr.h"
48 #include "llvm/ADT/MapVector.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/PointerIntPair.h"
52 #include "llvm/ADT/PointerUnion.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringMap.h"
55 #include "llvm/ADT/StringRef.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Support/AlignOf.h"
60 #include "llvm/Support/Allocator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/Compiler.h"
69 #include <type_traits>
76 template <typename T, unsigned N> class SmallPtrSet;
84 class ASTMutationListener;
85 class ASTRecordLayout;
88 class BuiltinTemplateDecl;
92 class CXXConstructorDecl;
95 class DiagnosticsEngine;
96 class ParentMapContext;
98 class DynTypedNodeList;
100 class FixedPointSemantics;
103 class MangleNumberingContext;
104 class MaterializeTemporaryExpr;
105 class MemberSpecializationInfo;
107 struct MSGuidDeclParts;
108 class ObjCCategoryDecl;
109 class ObjCCategoryImplDecl;
110 class ObjCContainerDecl;
112 class ObjCImplementationDecl;
113 class ObjCInterfaceDecl;
115 class ObjCMethodDecl;
116 class ObjCPropertyDecl;
117 class ObjCPropertyImplDecl;
118 class ObjCProtocolDecl;
119 class ObjCTypeParamDecl;
121 struct ParsedTargetAttr;
124 class StoredDeclsMap;
128 class TemplateParameterList;
129 class TemplateTemplateParmDecl;
130 class TemplateTypeParmDecl;
131 class UnresolvedSetIterator;
132 class UsingShadowDecl;
133 class VarTemplateDecl;
134 class VTableContextBase;
135 struct BlockVarCopyInit;
141 } // namespace Builtin
143 enum BuiltinTemplateKind : int;
144 enum OpenCLTypeKind : uint8_t;
150 } // namespace comments
156 } // namespace interp
158 namespace serialization {
159 template <class> class AbstractTypeReader;
160 } // namespace serialization
165 bool AlignIsRequired : 1;
167 TypeInfo() : AlignIsRequired(false) {}
168 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
169 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
172 /// Holds long-lived AST nodes (such as types and decls) that can be
173 /// referred to throughout the semantic analysis of a file.
174 class ASTContext : public RefCountedBase<ASTContext> {
175 friend class NestedNameSpecifier;
177 mutable SmallVector<Type *, 0> Types;
178 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
179 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
180 mutable llvm::FoldingSet<PointerType> PointerTypes;
181 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
182 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
183 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
184 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
185 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
186 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
188 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
189 mutable std::vector<VariableArrayType*> VariableArrayTypes;
190 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
191 mutable llvm::FoldingSet<DependentSizedExtVectorType>
192 DependentSizedExtVectorTypes;
193 mutable llvm::FoldingSet<DependentAddressSpaceType>
194 DependentAddressSpaceTypes;
195 mutable llvm::FoldingSet<VectorType> VectorTypes;
196 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
197 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
198 mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
199 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
200 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
202 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
203 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
204 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
205 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
206 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
207 SubstTemplateTypeParmTypes;
208 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
209 SubstTemplateTypeParmPackTypes;
210 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
211 TemplateSpecializationTypes;
212 mutable llvm::FoldingSet<ParenType> ParenTypes;
213 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
214 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
215 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
217 DependentTemplateSpecializationTypes;
218 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
219 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
220 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
221 mutable llvm::FoldingSet<DependentUnaryTransformType>
222 DependentUnaryTransformTypes;
223 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
224 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
225 DeducedTemplateSpecializationTypes;
226 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
227 llvm::FoldingSet<AttributedType> AttributedTypes;
228 mutable llvm::FoldingSet<PipeType> PipeTypes;
229 mutable llvm::FoldingSet<ExtIntType> ExtIntTypes;
230 mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes;
232 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
233 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
234 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
235 SubstTemplateTemplateParms;
236 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
238 SubstTemplateTemplateParmPacks;
240 /// The set of nested name specifiers.
242 /// This set is managed by the NestedNameSpecifier class.
243 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
244 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
246 /// A cache mapping from RecordDecls to ASTRecordLayouts.
248 /// This is lazily created. This is intentionally not serialized.
249 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
251 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
254 /// A cache from types to size and alignment information.
255 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
256 mutable TypeInfoMap MemoizedTypeInfo;
258 /// A cache from types to unadjusted alignment information. Only ARM and
259 /// AArch64 targets need this information, keeping it separate prevents
260 /// imposing overhead on TypeInfo size.
261 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
262 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
264 /// A cache mapping from CXXRecordDecls to key functions.
265 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
267 /// Mapping from ObjCContainers to their ObjCImplementations.
268 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
270 /// Mapping from ObjCMethod to its duplicate declaration in the same
272 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
274 /// Mapping from __block VarDecls to BlockVarCopyInit.
275 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
277 /// Mapping from GUIDs to the corresponding MSGuidDecl.
278 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
280 /// Used to cleanups APValues stored in the AST.
281 mutable llvm::SmallVector<APValue *, 0> APValueCleanups;
283 /// A cache mapping a string value to a StringLiteral object with the same
286 /// This is lazily created. This is intentionally not serialized.
287 mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
289 /// Representation of a "canonical" template template parameter that
290 /// is used in canonical template names.
291 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
292 TemplateTemplateParmDecl *Parm;
295 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
298 TemplateTemplateParmDecl *getParam() const { return Parm; }
300 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
301 Profile(ID, C, Parm);
304 static void Profile(llvm::FoldingSetNodeID &ID,
306 TemplateTemplateParmDecl *Parm);
308 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
310 CanonTemplateTemplateParms;
312 TemplateTemplateParmDecl *
313 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
315 /// The typedef for the __int128_t type.
316 mutable TypedefDecl *Int128Decl = nullptr;
318 /// The typedef for the __uint128_t type.
319 mutable TypedefDecl *UInt128Decl = nullptr;
321 /// The typedef for the target specific predefined
322 /// __builtin_va_list type.
323 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
325 /// The typedef for the predefined \c __builtin_ms_va_list type.
326 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
328 /// The typedef for the predefined \c id type.
329 mutable TypedefDecl *ObjCIdDecl = nullptr;
331 /// The typedef for the predefined \c SEL type.
332 mutable TypedefDecl *ObjCSelDecl = nullptr;
334 /// The typedef for the predefined \c Class type.
335 mutable TypedefDecl *ObjCClassDecl = nullptr;
337 /// The typedef for the predefined \c Protocol class in Objective-C.
338 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
340 /// The typedef for the predefined 'BOOL' type.
341 mutable TypedefDecl *BOOLDecl = nullptr;
343 // Typedefs which may be provided defining the structure of Objective-C
345 QualType ObjCIdRedefinitionType;
346 QualType ObjCClassRedefinitionType;
347 QualType ObjCSelRedefinitionType;
349 /// The identifier 'bool'.
350 mutable IdentifierInfo *BoolName = nullptr;
352 /// The identifier 'NSObject'.
353 mutable IdentifierInfo *NSObjectName = nullptr;
355 /// The identifier 'NSCopying'.
356 IdentifierInfo *NSCopyingName = nullptr;
358 /// The identifier '__make_integer_seq'.
359 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
361 /// The identifier '__type_pack_element'.
362 mutable IdentifierInfo *TypePackElementName = nullptr;
364 QualType ObjCConstantStringType;
365 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
366 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
368 mutable QualType ObjCSuperType;
370 QualType ObjCNSStringType;
372 /// The typedef declaration for the Objective-C "instancetype" type.
373 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
375 /// The type for the C FILE type.
376 TypeDecl *FILEDecl = nullptr;
378 /// The type for the C jmp_buf type.
379 TypeDecl *jmp_bufDecl = nullptr;
381 /// The type for the C sigjmp_buf type.
382 TypeDecl *sigjmp_bufDecl = nullptr;
384 /// The type for the C ucontext_t type.
385 TypeDecl *ucontext_tDecl = nullptr;
387 /// Type for the Block descriptor for Blocks CodeGen.
389 /// Since this is only used for generation of debug info, it is not
391 mutable RecordDecl *BlockDescriptorType = nullptr;
393 /// Type for the Block descriptor for Blocks CodeGen.
395 /// Since this is only used for generation of debug info, it is not
397 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
399 /// Declaration for the CUDA cudaConfigureCall function.
400 FunctionDecl *cudaConfigureCallDecl = nullptr;
402 /// Keeps track of all declaration attributes.
404 /// Since so few decls have attrs, we keep them in a hash map instead of
405 /// wasting space in the Decl class.
406 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
408 /// A mapping from non-redeclarable declarations in modules that were
409 /// merged with other declarations to the canonical declaration that they were
411 llvm::DenseMap<Decl*, Decl*> MergedDecls;
413 /// A mapping from a defining declaration to a list of modules (other
414 /// than the owning module of the declaration) that contain merged
415 /// definitions of that entity.
416 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
418 /// Initializers for a module, in order. Each Decl will be either
419 /// something that has a semantic effect on startup (such as a variable with
420 /// a non-constant initializer), or an ImportDecl (which recursively triggers
421 /// initialization of another module).
422 struct PerModuleInitializers {
423 llvm::SmallVector<Decl*, 4> Initializers;
424 llvm::SmallVector<uint32_t, 4> LazyInitializers;
426 void resolve(ASTContext &Ctx);
428 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
430 ASTContext &this_() { return *this; }
433 /// A type synonym for the TemplateOrInstantiation mapping.
434 using TemplateOrSpecializationInfo =
435 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
438 friend class ASTDeclReader;
439 friend class ASTReader;
440 friend class ASTWriter;
441 template <class> friend class serialization::AbstractTypeReader;
442 friend class CXXRecordDecl;
444 /// A mapping to contain the template or declaration that
445 /// a variable declaration describes or was instantiated from,
448 /// For non-templates, this value will be NULL. For variable
449 /// declarations that describe a variable template, this will be a
450 /// pointer to a VarTemplateDecl. For static data members
451 /// of class template specializations, this will be the
452 /// MemberSpecializationInfo referring to the member variable that was
453 /// instantiated or specialized. Thus, the mapping will keep track of
454 /// the static data member templates from which static data members of
455 /// class template specializations were instantiated.
457 /// Given the following example:
460 /// template<typename T>
465 /// template<typename T>
466 /// T X<T>::value = T(17);
468 /// int *x = &X<int>::value;
471 /// This mapping will contain an entry that maps from the VarDecl for
472 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
473 /// class template X) and will be marked TSK_ImplicitInstantiation.
474 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
475 TemplateOrInstantiation;
477 /// Keeps track of the declaration from which a using declaration was
478 /// created during instantiation.
480 /// The source and target declarations are always a UsingDecl, an
481 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
485 /// template<typename T>
490 /// template<typename T>
491 /// struct B : A<T> {
495 /// template struct B<int>;
498 /// This mapping will contain an entry that maps from the UsingDecl in
499 /// B<int> to the UnresolvedUsingDecl in B<T>.
500 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
502 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
503 InstantiatedFromUsingShadowDecl;
505 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
507 /// Mapping that stores the methods overridden by a given C++
510 /// Since most C++ member functions aren't virtual and therefore
511 /// don't override anything, we store the overridden functions in
512 /// this map on the side rather than within the CXXMethodDecl structure.
513 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
514 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
516 /// Mapping from each declaration context to its corresponding
517 /// mangling numbering context (used for constructs like lambdas which
518 /// need to be consistently numbered for the mangler).
519 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
520 MangleNumberingContexts;
521 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
522 ExtraMangleNumberingContexts;
524 /// Side-table of mangling numbers for declarations which rarely
525 /// need them (like static local vars).
526 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
527 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
529 /// Mapping that stores parameterIndex values for ParmVarDecls when
530 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
531 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
532 ParameterIndexTable ParamIndices;
534 ImportDecl *FirstLocalImport = nullptr;
535 ImportDecl *LastLocalImport = nullptr;
537 TranslationUnitDecl *TUDecl;
538 mutable ExternCContextDecl *ExternCContext = nullptr;
539 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
540 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
542 /// The associated SourceManager object.
543 SourceManager &SourceMgr;
545 /// The language options used to create the AST associated with
546 /// this ASTContext object.
547 LangOptions &LangOpts;
549 /// Blacklist object that is used by sanitizers to decide which
550 /// entities should not be instrumented.
551 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
553 /// Function filtering mechanism to determine whether a given function
554 /// should be imbued with the XRay "always" or "never" attributes.
555 std::unique_ptr<XRayFunctionFilter> XRayFilter;
557 /// The allocator used to create AST objects.
559 /// AST objects are never destructed; rather, all memory associated with the
560 /// AST objects will be released when the ASTContext itself is destroyed.
561 mutable llvm::BumpPtrAllocator BumpAlloc;
563 /// Allocator for partial diagnostics.
564 PartialDiagnostic::StorageAllocator DiagAllocator;
566 /// The current C++ ABI.
567 std::unique_ptr<CXXABI> ABI;
568 CXXABI *createCXXABI(const TargetInfo &T);
570 /// The logical -> physical address space map.
571 const LangASMap *AddrSpaceMap = nullptr;
573 /// Address space map mangling must be used with language specific
574 /// address spaces (e.g. OpenCL/CUDA)
575 bool AddrSpaceMapMangling;
577 const TargetInfo *Target = nullptr;
578 const TargetInfo *AuxTarget = nullptr;
579 clang::PrintingPolicy PrintingPolicy;
580 std::unique_ptr<interp::Context> InterpContext;
581 std::unique_ptr<ParentMapContext> ParentMapCtx;
584 IdentifierTable &Idents;
585 SelectorTable &Selectors;
586 Builtin::Context &BuiltinInfo;
587 mutable DeclarationNameTable DeclarationNames;
588 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
589 ASTMutationListener *Listener = nullptr;
591 /// Returns the clang bytecode interpreter context.
592 interp::Context &getInterpContext();
594 /// Returns the dynamic AST node parent map context.
595 ParentMapContext &getParentMapContext();
597 // A traversal scope limits the parts of the AST visible to certain analyses.
598 // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and
599 // getParents() will only observe reachable parent edges.
601 // The scope is defined by a set of "top-level" declarations.
602 // Initially, it is the entire TU: {getTranslationUnitDecl()}.
603 // Changing the scope clears the parent cache, which is expensive to rebuild.
604 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
605 void setTraversalScope(const std::vector<Decl *> &);
607 /// Forwards to get node parents from the ParentMapContext. New callers should
608 /// use ParentMapContext::getParents() directly.
609 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
611 const clang::PrintingPolicy &getPrintingPolicy() const {
612 return PrintingPolicy;
615 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
616 PrintingPolicy = Policy;
619 SourceManager& getSourceManager() { return SourceMgr; }
620 const SourceManager& getSourceManager() const { return SourceMgr; }
622 llvm::BumpPtrAllocator &getAllocator() const {
626 void *Allocate(size_t Size, unsigned Align = 8) const {
627 return BumpAlloc.Allocate(Size, Align);
629 template <typename T> T *Allocate(size_t Num = 1) const {
630 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
632 void Deallocate(void *Ptr) const {}
634 /// Return the total amount of physical memory allocated for representing
635 /// AST nodes and type information.
636 size_t getASTAllocatedMemory() const {
637 return BumpAlloc.getTotalMemory();
640 /// Return the total memory used for various side tables.
641 size_t getSideTableAllocatedMemory() const;
643 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
644 return DiagAllocator;
647 const TargetInfo &getTargetInfo() const { return *Target; }
648 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
650 /// getIntTypeForBitwidth -
651 /// sets integer QualTy according to specified details:
652 /// bitwidth, signed/unsigned.
653 /// Returns empty type if there is no appropriate target types.
654 QualType getIntTypeForBitwidth(unsigned DestWidth,
655 unsigned Signed) const;
657 /// getRealTypeForBitwidth -
658 /// sets floating point QualTy according to specified bitwidth.
659 /// Returns empty type if there is no appropriate target types.
660 QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const;
662 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
664 const LangOptions& getLangOpts() const { return LangOpts; }
666 const SanitizerBlacklist &getSanitizerBlacklist() const {
670 const XRayFunctionFilter &getXRayFilter() const {
674 DiagnosticsEngine &getDiagnostics() const;
676 FullSourceLoc getFullLoc(SourceLocation Loc) const {
677 return FullSourceLoc(Loc,SourceMgr);
680 /// All comments in this translation unit.
681 RawCommentList Comments;
683 /// True if comments are already loaded from ExternalASTSource.
684 mutable bool CommentsLoaded = false;
686 /// Mapping from declaration to directly attached comment.
688 /// Raw comments are owned by Comments list. This mapping is populated
690 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
692 /// Mapping from canonical declaration to the first redeclaration in chain
693 /// that has a comment attached.
695 /// Raw comments are owned by Comments list. This mapping is populated
697 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
699 /// Keeps track of redeclaration chains that don't have any comment attached.
700 /// Mapping from canonical declaration to redeclaration chain that has no
701 /// comments attached to any redeclaration. Specifically it's mapping to
702 /// the last redeclaration we've checked.
704 /// Shall not contain declarations that have comments attached to any
705 /// redeclaration in their chain.
706 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
708 /// Mapping from declarations to parsed comments attached to any
710 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
712 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
713 /// and removes the redeclaration chain from the set of commentless chains.
715 /// Don't do anything if a comment has already been attached to \p OriginalD
716 /// or its redeclaration chain.
717 void cacheRawCommentForDecl(const Decl &OriginalD,
718 const RawComment &Comment) const;
720 /// \returns searches \p CommentsInFile for doc comment for \p D.
722 /// \p RepresentativeLocForDecl is used as a location for searching doc
723 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
724 /// same file where \p RepresentativeLocForDecl is.
725 RawComment *getRawCommentForDeclNoCacheImpl(
726 const Decl *D, const SourceLocation RepresentativeLocForDecl,
727 const std::map<unsigned, RawComment *> &CommentsInFile) const;
729 /// Return the documentation comment attached to a given declaration,
730 /// without looking into cache.
731 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
734 void addComment(const RawComment &RC);
736 /// Return the documentation comment attached to a given declaration.
737 /// Returns nullptr if no comment is attached.
739 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
740 /// had the comment, if the comment we found comes from a redeclaration.
742 getRawCommentForAnyRedecl(const Decl *D,
743 const Decl **OriginalDecl = nullptr) const;
745 /// Searches existing comments for doc comments that should be attached to \p
746 /// Decls. If any doc comment is found, it is parsed.
748 /// Requirement: All \p Decls are in the same file.
750 /// If the last comment in the file is already attached we assume
751 /// there are not comments left to be attached to \p Decls.
752 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
753 const Preprocessor *PP);
755 /// Return parsed documentation comment attached to a given declaration.
756 /// Returns nullptr if no comment is attached.
758 /// \param PP the Preprocessor used with this TU. Could be nullptr if
759 /// preprocessor is not available.
760 comments::FullComment *getCommentForDecl(const Decl *D,
761 const Preprocessor *PP) const;
763 /// Return parsed documentation comment attached to a given declaration.
764 /// Returns nullptr if no comment is attached. Does not look at any
765 /// redeclarations of the declaration.
766 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
768 comments::FullComment *cloneFullComment(comments::FullComment *FC,
769 const Decl *D) const;
772 mutable comments::CommandTraits CommentCommandTraits;
774 /// Iterator that visits import declarations.
775 class import_iterator {
776 ImportDecl *Import = nullptr;
779 using value_type = ImportDecl *;
780 using reference = ImportDecl *;
781 using pointer = ImportDecl *;
782 using difference_type = int;
783 using iterator_category = std::forward_iterator_tag;
785 import_iterator() = default;
786 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
788 reference operator*() const { return Import; }
789 pointer operator->() const { return Import; }
791 import_iterator &operator++() {
792 Import = ASTContext::getNextLocalImport(Import);
796 import_iterator operator++(int) {
797 import_iterator Other(*this);
802 friend bool operator==(import_iterator X, import_iterator Y) {
803 return X.Import == Y.Import;
806 friend bool operator!=(import_iterator X, import_iterator Y) {
807 return X.Import != Y.Import;
812 comments::CommandTraits &getCommentCommandTraits() const {
813 return CommentCommandTraits;
816 /// Retrieve the attributes for the given declaration.
817 AttrVec& getDeclAttrs(const Decl *D);
819 /// Erase the attributes corresponding to the given declaration.
820 void eraseDeclAttrs(const Decl *D);
822 /// If this variable is an instantiated static data member of a
823 /// class template specialization, returns the templated static data member
824 /// from which it was instantiated.
826 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
829 TemplateOrSpecializationInfo
830 getTemplateOrSpecializationInfo(const VarDecl *Var);
832 /// Note that the static data member \p Inst is an instantiation of
833 /// the static data member template \p Tmpl of a class template.
834 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
835 TemplateSpecializationKind TSK,
836 SourceLocation PointOfInstantiation = SourceLocation());
838 void setTemplateOrSpecializationInfo(VarDecl *Inst,
839 TemplateOrSpecializationInfo TSI);
841 /// If the given using decl \p Inst is an instantiation of a
842 /// (possibly unresolved) using decl from a template instantiation,
844 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
846 /// Remember that the using decl \p Inst is an instantiation
847 /// of the using decl \p Pattern of a class template.
848 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
850 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
851 UsingShadowDecl *Pattern);
852 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
854 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
856 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
858 // Access to the set of methods overridden by the given C++ method.
859 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
860 overridden_cxx_method_iterator
861 overridden_methods_begin(const CXXMethodDecl *Method) const;
863 overridden_cxx_method_iterator
864 overridden_methods_end(const CXXMethodDecl *Method) const;
866 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
868 using overridden_method_range =
869 llvm::iterator_range<overridden_cxx_method_iterator>;
871 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
873 /// Note that the given C++ \p Method overrides the given \p
874 /// Overridden method.
875 void addOverriddenMethod(const CXXMethodDecl *Method,
876 const CXXMethodDecl *Overridden);
878 /// Return C++ or ObjC overridden methods for the given \p Method.
880 /// An ObjC method is considered to override any method in the class's
881 /// base classes, its protocols, or its categories' protocols, that has
882 /// the same selector and is of the same kind (class or instance).
883 /// A method in an implementation is not considered as overriding the same
884 /// method in the interface or its categories.
885 void getOverriddenMethods(
886 const NamedDecl *Method,
887 SmallVectorImpl<const NamedDecl *> &Overridden) const;
889 /// Notify the AST context that a new import declaration has been
890 /// parsed or implicitly created within this translation unit.
891 void addedLocalImportDecl(ImportDecl *Import);
893 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
894 return Import->getNextLocalImport();
897 using import_range = llvm::iterator_range<import_iterator>;
899 import_range local_imports() const {
900 return import_range(import_iterator(FirstLocalImport), import_iterator());
903 Decl *getPrimaryMergedDecl(Decl *D) {
904 Decl *Result = MergedDecls.lookup(D);
905 return Result ? Result : D;
907 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
908 MergedDecls[D] = Primary;
911 /// Note that the definition \p ND has been merged into module \p M,
912 /// and should be visible whenever \p M is visible.
913 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
914 bool NotifyListeners = true);
916 /// Clean up the merged definition list. Call this if you might have
917 /// added duplicates into the list.
918 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
920 /// Get the additional modules in which the definition \p Def has
922 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
924 /// Add a declaration to the list of declarations that are initialized
925 /// for a module. This will typically be a global variable (with internal
926 /// linkage) that runs module initializers, such as the iostream initializer,
927 /// or an ImportDecl nominating another module that has initializers.
928 void addModuleInitializer(Module *M, Decl *Init);
930 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
932 /// Get the initializations to perform when importing a module, if any.
933 ArrayRef<Decl*> getModuleInitializers(Module *M);
935 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
937 ExternCContextDecl *getExternCContextDecl() const;
938 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
939 BuiltinTemplateDecl *getTypePackElementDecl() const;
945 CanQualType WCharTy; // [C++ 3.9.1p5].
946 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
947 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
948 CanQualType Char8Ty; // [C++20 proposal]
949 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
950 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
951 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
952 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
953 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
954 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
955 CanQualType ShortAccumTy, AccumTy,
956 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
957 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
958 CanQualType ShortFractTy, FractTy, LongFractTy;
959 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
960 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
961 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
962 SatUnsignedLongAccumTy;
963 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
964 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
965 SatUnsignedLongFractTy;
966 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
967 CanQualType BFloat16Ty;
968 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
969 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
970 CanQualType Float128ComplexTy;
971 CanQualType VoidPtrTy, NullPtrTy;
972 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
973 CanQualType BuiltinFnTy;
974 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
975 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
976 CanQualType ObjCBuiltinBoolTy;
977 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
978 CanQualType SingletonId;
979 #include "clang/Basic/OpenCLImageTypes.def"
980 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
981 CanQualType OCLQueueTy, OCLReserveIDTy;
982 CanQualType IncompleteMatrixIdxTy;
983 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
984 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
986 #include "clang/Basic/OpenCLExtensionTypes.def"
987 #define SVE_TYPE(Name, Id, SingletonId) \
988 CanQualType SingletonId;
989 #include "clang/Basic/AArch64SVEACLETypes.def"
991 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
992 mutable QualType AutoDeductTy; // Deduction against 'auto'.
993 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
995 // Decl used to help define __builtin_va_list for some targets.
996 // The decl is built when constructing 'BuiltinVaListDecl'.
997 mutable Decl *VaListTagDecl = nullptr;
999 // Implicitly-declared type 'struct _GUID'.
1000 mutable TagDecl *MSGuidTagDecl = nullptr;
1002 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1003 SelectorTable &sels, Builtin::Context &builtins);
1004 ASTContext(const ASTContext &) = delete;
1005 ASTContext &operator=(const ASTContext &) = delete;
1008 /// Attach an external AST source to the AST context.
1010 /// The external AST source provides the ability to load parts of
1011 /// the abstract syntax tree as needed from some external storage,
1012 /// e.g., a precompiled header.
1013 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1015 /// Retrieve a pointer to the external AST source associated
1016 /// with this AST context, if any.
1017 ExternalASTSource *getExternalSource() const {
1018 return ExternalSource.get();
1021 /// Attach an AST mutation listener to the AST context.
1023 /// The AST mutation listener provides the ability to track modifications to
1024 /// the abstract syntax tree entities committed after they were initially
1026 void setASTMutationListener(ASTMutationListener *Listener) {
1027 this->Listener = Listener;
1030 /// Retrieve a pointer to the AST mutation listener associated
1031 /// with this AST context, if any.
1032 ASTMutationListener *getASTMutationListener() const { return Listener; }
1034 void PrintStats() const;
1035 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1037 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1038 const IdentifierInfo *II) const;
1040 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1042 RecordDecl *buildImplicitRecord(StringRef Name,
1043 RecordDecl::TagKind TK = TTK_Struct) const;
1045 /// Create a new implicit TU-level typedef declaration.
1046 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1048 /// Retrieve the declaration for the 128-bit signed integer type.
1049 TypedefDecl *getInt128Decl() const;
1051 /// Retrieve the declaration for the 128-bit unsigned integer type.
1052 TypedefDecl *getUInt128Decl() const;
1054 //===--------------------------------------------------------------------===//
1055 // Type Constructors
1056 //===--------------------------------------------------------------------===//
1059 /// Return a type with extended qualifiers.
1060 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1062 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1064 QualType getPipeType(QualType T, bool ReadOnly) const;
1067 /// Return the uniqued reference to the type for an address space
1068 /// qualified type with the specified type and address space.
1070 /// The resulting type has a union of the qualifiers from T and the address
1071 /// space. If T already has an address space specifier, it is silently
1073 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1075 /// Remove any existing address space on the type and returns the type
1076 /// with qualifiers intact (or that's the idea anyway)
1078 /// The return type should be T with all prior qualifiers minus the address
1080 QualType removeAddrSpaceQualType(QualType T) const;
1082 /// Apply Objective-C protocol qualifiers to the given type.
1083 /// \param allowOnPointerType specifies if we can apply protocol
1084 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1085 /// constructing the canonical type of a Objective-C type parameter.
1086 QualType applyObjCProtocolQualifiers(QualType type,
1087 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1088 bool allowOnPointerType = false) const;
1090 /// Return the uniqued reference to the type for an Objective-C
1091 /// gc-qualified type.
1093 /// The resulting type has a union of the qualifiers from T and the gc
1095 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1097 /// Remove the existing address space on the type if it is a pointer size
1098 /// address space and return the type with qualifiers intact.
1099 QualType removePtrSizeAddrSpace(QualType T) const;
1101 /// Return the uniqued reference to the type for a \c restrict
1104 /// The resulting type has a union of the qualifiers from \p T and
1106 QualType getRestrictType(QualType T) const {
1107 return T.withFastQualifiers(Qualifiers::Restrict);
1110 /// Return the uniqued reference to the type for a \c volatile
1113 /// The resulting type has a union of the qualifiers from \p T and
1115 QualType getVolatileType(QualType T) const {
1116 return T.withFastQualifiers(Qualifiers::Volatile);
1119 /// Return the uniqued reference to the type for a \c const
1122 /// The resulting type has a union of the qualifiers from \p T and \c const.
1124 /// It can be reasonably expected that this will always be equivalent to
1125 /// calling T.withConst().
1126 QualType getConstType(QualType T) const { return T.withConst(); }
1128 /// Change the ExtInfo on a function type.
1129 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1130 FunctionType::ExtInfo EInfo);
1132 /// Adjust the given function result type.
1133 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1135 /// Change the result type of a function type once it is deduced.
1136 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1138 /// Get a function type and produce the equivalent function type with the
1139 /// specified exception specification. Type sugar that can be present on a
1140 /// declaration of a function with an exception specification is permitted
1141 /// and preserved. Other type sugar (for instance, typedefs) is not.
1142 QualType getFunctionTypeWithExceptionSpec(
1143 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1145 /// Determine whether two function types are the same, ignoring
1146 /// exception specifications in cases where they're part of the type.
1147 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1149 /// Change the exception specification on a function once it is
1150 /// delay-parsed, instantiated, or computed.
1151 void adjustExceptionSpec(FunctionDecl *FD,
1152 const FunctionProtoType::ExceptionSpecInfo &ESI,
1153 bool AsWritten = false);
1155 /// Get a function type and produce the equivalent function type where
1156 /// pointer size address spaces in the return type and parameter tyeps are
1157 /// replaced with the default address space.
1158 QualType getFunctionTypeWithoutPtrSizes(QualType T);
1160 /// Determine whether two function types are the same, ignoring pointer sizes
1161 /// in the return type and parameter types.
1162 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1164 /// Return the uniqued reference to the type for a complex
1165 /// number with the specified element type.
1166 QualType getComplexType(QualType T) const;
1167 CanQualType getComplexType(CanQualType T) const {
1168 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1171 /// Return the uniqued reference to the type for a pointer to
1172 /// the specified type.
1173 QualType getPointerType(QualType T) const;
1174 CanQualType getPointerType(CanQualType T) const {
1175 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1178 /// Return the uniqued reference to a type adjusted from the original
1179 /// type to a new type.
1180 QualType getAdjustedType(QualType Orig, QualType New) const;
1181 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1182 return CanQualType::CreateUnsafe(
1183 getAdjustedType((QualType)Orig, (QualType)New));
1186 /// Return the uniqued reference to the decayed version of the given
1187 /// type. Can only be called on array and function types which decay to
1189 QualType getDecayedType(QualType T) const;
1190 CanQualType getDecayedType(CanQualType T) const {
1191 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1194 /// Return the uniqued reference to the atomic type for the specified
1196 QualType getAtomicType(QualType T) const;
1198 /// Return the uniqued reference to the type for a block of the
1200 QualType getBlockPointerType(QualType T) const;
1202 /// Gets the struct used to keep track of the descriptor for pointer to
1204 QualType getBlockDescriptorType() const;
1206 /// Return a read_only pipe type for the specified type.
1207 QualType getReadPipeType(QualType T) const;
1209 /// Return a write_only pipe type for the specified type.
1210 QualType getWritePipeType(QualType T) const;
1212 /// Return an extended integer type with the specified signedness and bit
1214 QualType getExtIntType(bool Unsigned, unsigned NumBits) const;
1216 /// Return a dependent extended integer type with the specified signedness and
1218 QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const;
1220 /// Gets the struct used to keep track of the extended descriptor for
1221 /// pointer to blocks.
1222 QualType getBlockDescriptorExtendedType() const;
1224 /// Map an AST Type to an OpenCLTypeKind enum value.
1225 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1227 /// Get address space for OpenCL type.
1228 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1230 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1231 cudaConfigureCallDecl = FD;
1234 FunctionDecl *getcudaConfigureCallDecl() {
1235 return cudaConfigureCallDecl;
1238 /// Returns true iff we need copy/dispose helpers for the given type.
1239 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1241 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1242 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1243 /// byref variable has extended lifetime.
1244 bool getByrefLifetime(QualType Ty,
1245 Qualifiers::ObjCLifetime &Lifetime,
1246 bool &HasByrefExtendedLayout) const;
1248 /// Return the uniqued reference to the type for an lvalue reference
1249 /// to the specified type.
1250 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1253 /// Return the uniqued reference to the type for an rvalue reference
1254 /// to the specified type.
1255 QualType getRValueReferenceType(QualType T) const;
1257 /// Return the uniqued reference to the type for a member pointer to
1258 /// the specified type in the specified class.
1260 /// The class \p Cls is a \c Type because it could be a dependent name.
1261 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1263 /// Return a non-unique reference to the type for a variable array of
1264 /// the specified element type.
1265 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1266 ArrayType::ArraySizeModifier ASM,
1267 unsigned IndexTypeQuals,
1268 SourceRange Brackets) const;
1270 /// Return a non-unique reference to the type for a dependently-sized
1271 /// array of the specified element type.
1273 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1275 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1276 ArrayType::ArraySizeModifier ASM,
1277 unsigned IndexTypeQuals,
1278 SourceRange Brackets) const;
1280 /// Return a unique reference to the type for an incomplete array of
1281 /// the specified element type.
1282 QualType getIncompleteArrayType(QualType EltTy,
1283 ArrayType::ArraySizeModifier ASM,
1284 unsigned IndexTypeQuals) const;
1286 /// Return the unique reference to the type for a constant array of
1287 /// the specified element type.
1288 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1289 const Expr *SizeExpr,
1290 ArrayType::ArraySizeModifier ASM,
1291 unsigned IndexTypeQuals) const;
1293 /// Return a type for a constant array for a string literal of the
1294 /// specified element type and length.
1295 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1297 /// Returns a vla type where known sizes are replaced with [*].
1298 QualType getVariableArrayDecayedType(QualType Ty) const;
1300 /// Return the unique reference to a scalable vector type of the specified
1301 /// element type and scalable number of elements.
1303 /// \pre \p EltTy must be a built-in type.
1304 QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const;
1306 /// Return the unique reference to a vector type of the specified
1307 /// element type and size.
1309 /// \pre \p VectorType must be a built-in type.
1310 QualType getVectorType(QualType VectorType, unsigned NumElts,
1311 VectorType::VectorKind VecKind) const;
1312 /// Return the unique reference to the type for a dependently sized vector of
1313 /// the specified element type.
1314 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1315 SourceLocation AttrLoc,
1316 VectorType::VectorKind VecKind) const;
1318 /// Return the unique reference to an extended vector type
1319 /// of the specified element type and size.
1321 /// \pre \p VectorType must be a built-in type.
1322 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1324 /// \pre Return a non-unique reference to the type for a dependently-sized
1325 /// vector of the specified element type.
1327 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1329 QualType getDependentSizedExtVectorType(QualType VectorType,
1331 SourceLocation AttrLoc) const;
1333 /// Return the unique reference to the matrix type of the specified element
1336 /// \pre \p ElementType must be a valid matrix element type (see
1337 /// MatrixType::isValidElementType).
1338 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1339 unsigned NumColumns) const;
1341 /// Return the unique reference to the matrix type of the specified element
1343 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1345 SourceLocation AttrLoc) const;
1347 QualType getDependentAddressSpaceType(QualType PointeeType,
1348 Expr *AddrSpaceExpr,
1349 SourceLocation AttrLoc) const;
1351 /// Return a K&R style C function type like 'int()'.
1352 QualType getFunctionNoProtoType(QualType ResultTy,
1353 const FunctionType::ExtInfo &Info) const;
1355 QualType getFunctionNoProtoType(QualType ResultTy) const {
1356 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1359 /// Return a normal function type with a typed argument list.
1360 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1361 const FunctionProtoType::ExtProtoInfo &EPI) const {
1362 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1365 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1368 /// Return a normal function type with a typed argument list.
1369 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1370 const FunctionProtoType::ExtProtoInfo &EPI,
1371 bool OnlyWantCanonical) const;
1374 /// Return the unique reference to the type for the specified type
1376 QualType getTypeDeclType(const TypeDecl *Decl,
1377 const TypeDecl *PrevDecl = nullptr) const {
1378 assert(Decl && "Passed null for Decl param");
1379 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1382 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1383 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1384 return QualType(PrevDecl->TypeForDecl, 0);
1387 return getTypeDeclTypeSlow(Decl);
1390 /// Return the unique reference to the type for the specified
1391 /// typedef-name decl.
1392 QualType getTypedefType(const TypedefNameDecl *Decl,
1393 QualType Canon = QualType()) const;
1395 QualType getRecordType(const RecordDecl *Decl) const;
1397 QualType getEnumType(const EnumDecl *Decl) const;
1399 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1401 QualType getAttributedType(attr::Kind attrKind,
1402 QualType modifiedType,
1403 QualType equivalentType);
1405 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1406 QualType Replacement) const;
1407 QualType getSubstTemplateTypeParmPackType(
1408 const TemplateTypeParmType *Replaced,
1409 const TemplateArgument &ArgPack);
1412 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1414 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1416 QualType getTemplateSpecializationType(TemplateName T,
1417 ArrayRef<TemplateArgument> Args,
1418 QualType Canon = QualType()) const;
1421 getCanonicalTemplateSpecializationType(TemplateName T,
1422 ArrayRef<TemplateArgument> Args) const;
1424 QualType getTemplateSpecializationType(TemplateName T,
1425 const TemplateArgumentListInfo &Args,
1426 QualType Canon = QualType()) const;
1429 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1430 const TemplateArgumentListInfo &Args,
1431 QualType Canon = QualType()) const;
1433 QualType getParenType(QualType NamedType) const;
1435 QualType getMacroQualifiedType(QualType UnderlyingTy,
1436 const IdentifierInfo *MacroII) const;
1438 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1439 NestedNameSpecifier *NNS, QualType NamedType,
1440 TagDecl *OwnedTagDecl = nullptr) const;
1441 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1442 NestedNameSpecifier *NNS,
1443 const IdentifierInfo *Name,
1444 QualType Canon = QualType()) const;
1446 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1447 NestedNameSpecifier *NNS,
1448 const IdentifierInfo *Name,
1449 const TemplateArgumentListInfo &Args) const;
1450 QualType getDependentTemplateSpecializationType(
1451 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1452 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1454 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1456 /// Get a template argument list with one argument per template parameter
1457 /// in a template parameter list, such as for the injected class name of
1458 /// a class template.
1459 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1460 SmallVectorImpl<TemplateArgument> &Args);
1462 QualType getPackExpansionType(QualType Pattern,
1463 Optional<unsigned> NumExpansions);
1465 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1466 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1468 /// Legacy interface: cannot provide type arguments or __kindof.
1469 QualType getObjCObjectType(QualType Base,
1470 ObjCProtocolDecl * const *Protocols,
1471 unsigned NumProtocols) const;
1473 QualType getObjCObjectType(QualType Base,
1474 ArrayRef<QualType> typeArgs,
1475 ArrayRef<ObjCProtocolDecl *> protocols,
1476 bool isKindOf) const;
1478 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1479 ArrayRef<ObjCProtocolDecl *> protocols) const;
1480 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1481 ObjCTypeParamDecl *New) const;
1483 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1485 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1486 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1488 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1489 ObjCInterfaceDecl *IDecl);
1491 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1492 QualType getObjCObjectPointerType(QualType OIT) const;
1495 QualType getTypeOfExprType(Expr *e) const;
1496 QualType getTypeOfType(QualType t) const;
1499 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1501 /// Unary type transforms
1502 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1503 UnaryTransformType::UTTKind UKind) const;
1505 /// C++11 deduced auto type.
1506 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1507 bool IsDependent, bool IsPack = false,
1508 ConceptDecl *TypeConstraintConcept = nullptr,
1509 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1511 /// C++11 deduction pattern for 'auto' type.
1512 QualType getAutoDeductType() const;
1514 /// C++11 deduction pattern for 'auto &&' type.
1515 QualType getAutoRRefDeductType() const;
1517 /// C++17 deduced class template specialization type.
1518 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1519 QualType DeducedType,
1520 bool IsDependent) const;
1522 /// Return the unique reference to the type for the specified TagDecl
1523 /// (struct/union/class/enum) decl.
1524 QualType getTagDeclType(const TagDecl *Decl) const;
1526 /// Return the unique type for "size_t" (C99 7.17), defined in
1529 /// The sizeof operator requires this (C99 6.5.3.4p4).
1530 CanQualType getSizeType() const;
1532 /// Return the unique signed counterpart of
1533 /// the integer type corresponding to size_t.
1534 CanQualType getSignedSizeType() const;
1536 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1538 CanQualType getIntMaxType() const;
1540 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1542 CanQualType getUIntMaxType() const;
1544 /// Return the unique wchar_t type available in C++ (and available as
1545 /// __wchar_t as a Microsoft extension).
1546 QualType getWCharType() const { return WCharTy; }
1548 /// Return the type of wide characters. In C++, this returns the
1549 /// unique wchar_t type. In C99, this returns a type compatible with the type
1550 /// defined in <stddef.h> as defined by the target.
1551 QualType getWideCharType() const { return WideCharTy; }
1553 /// Return the type of "signed wchar_t".
1555 /// Used when in C++, as a GCC extension.
1556 QualType getSignedWCharType() const;
1558 /// Return the type of "unsigned wchar_t".
1560 /// Used when in C++, as a GCC extension.
1561 QualType getUnsignedWCharType() const;
1563 /// In C99, this returns a type compatible with the type
1564 /// defined in <stddef.h> as defined by the target.
1565 QualType getWIntType() const { return WIntTy; }
1567 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1568 /// as defined by the target.
1569 QualType getIntPtrType() const;
1571 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1572 /// as defined by the target.
1573 QualType getUIntPtrType() const;
1575 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1576 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1577 QualType getPointerDiffType() const;
1579 /// Return the unique unsigned counterpart of "ptrdiff_t"
1580 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1581 /// in the definition of %tu format specifier.
1582 QualType getUnsignedPointerDiffType() const;
1584 /// Return the unique type for "pid_t" defined in
1585 /// <sys/types.h>. We need this to compute the correct type for vfork().
1586 QualType getProcessIDType() const;
1588 /// Return the C structure type used to represent constant CFStrings.
1589 QualType getCFConstantStringType() const;
1591 /// Returns the C struct type for objc_super
1592 QualType getObjCSuperType() const;
1593 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1595 /// Get the structure type used to representation CFStrings, or NULL
1596 /// if it hasn't yet been built.
1597 QualType getRawCFConstantStringType() const {
1598 if (CFConstantStringTypeDecl)
1599 return getTypedefType(CFConstantStringTypeDecl);
1602 void setCFConstantStringType(QualType T);
1603 TypedefDecl *getCFConstantStringDecl() const;
1604 RecordDecl *getCFConstantStringTagDecl() const;
1606 // This setter/getter represents the ObjC type for an NSConstantString.
1607 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1608 QualType getObjCConstantStringInterface() const {
1609 return ObjCConstantStringType;
1612 QualType getObjCNSStringType() const {
1613 return ObjCNSStringType;
1616 void setObjCNSStringType(QualType T) {
1617 ObjCNSStringType = T;
1620 /// Retrieve the type that \c id has been defined to, which may be
1621 /// different from the built-in \c id if \c id has been typedef'd.
1622 QualType getObjCIdRedefinitionType() const {
1623 if (ObjCIdRedefinitionType.isNull())
1624 return getObjCIdType();
1625 return ObjCIdRedefinitionType;
1628 /// Set the user-written type that redefines \c id.
1629 void setObjCIdRedefinitionType(QualType RedefType) {
1630 ObjCIdRedefinitionType = RedefType;
1633 /// Retrieve the type that \c Class has been defined to, which may be
1634 /// different from the built-in \c Class if \c Class has been typedef'd.
1635 QualType getObjCClassRedefinitionType() const {
1636 if (ObjCClassRedefinitionType.isNull())
1637 return getObjCClassType();
1638 return ObjCClassRedefinitionType;
1641 /// Set the user-written type that redefines 'SEL'.
1642 void setObjCClassRedefinitionType(QualType RedefType) {
1643 ObjCClassRedefinitionType = RedefType;
1646 /// Retrieve the type that 'SEL' has been defined to, which may be
1647 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1648 QualType getObjCSelRedefinitionType() const {
1649 if (ObjCSelRedefinitionType.isNull())
1650 return getObjCSelType();
1651 return ObjCSelRedefinitionType;
1654 /// Set the user-written type that redefines 'SEL'.
1655 void setObjCSelRedefinitionType(QualType RedefType) {
1656 ObjCSelRedefinitionType = RedefType;
1659 /// Retrieve the identifier 'NSObject'.
1660 IdentifierInfo *getNSObjectName() const {
1661 if (!NSObjectName) {
1662 NSObjectName = &Idents.get("NSObject");
1665 return NSObjectName;
1668 /// Retrieve the identifier 'NSCopying'.
1669 IdentifierInfo *getNSCopyingName() {
1670 if (!NSCopyingName) {
1671 NSCopyingName = &Idents.get("NSCopying");
1674 return NSCopyingName;
1677 CanQualType getNSUIntegerType() const;
1679 CanQualType getNSIntegerType() const;
1681 /// Retrieve the identifier 'bool'.
1682 IdentifierInfo *getBoolName() const {
1684 BoolName = &Idents.get("bool");
1688 IdentifierInfo *getMakeIntegerSeqName() const {
1689 if (!MakeIntegerSeqName)
1690 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1691 return MakeIntegerSeqName;
1694 IdentifierInfo *getTypePackElementName() const {
1695 if (!TypePackElementName)
1696 TypePackElementName = &Idents.get("__type_pack_element");
1697 return TypePackElementName;
1700 /// Retrieve the Objective-C "instancetype" type, if already known;
1701 /// otherwise, returns a NULL type;
1702 QualType getObjCInstanceType() {
1703 return getTypeDeclType(getObjCInstanceTypeDecl());
1706 /// Retrieve the typedef declaration corresponding to the Objective-C
1707 /// "instancetype" type.
1708 TypedefDecl *getObjCInstanceTypeDecl();
1710 /// Set the type for the C FILE type.
1711 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1713 /// Retrieve the C FILE type.
1714 QualType getFILEType() const {
1716 return getTypeDeclType(FILEDecl);
1720 /// Set the type for the C jmp_buf type.
1721 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1722 this->jmp_bufDecl = jmp_bufDecl;
1725 /// Retrieve the C jmp_buf type.
1726 QualType getjmp_bufType() const {
1728 return getTypeDeclType(jmp_bufDecl);
1732 /// Set the type for the C sigjmp_buf type.
1733 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1734 this->sigjmp_bufDecl = sigjmp_bufDecl;
1737 /// Retrieve the C sigjmp_buf type.
1738 QualType getsigjmp_bufType() const {
1740 return getTypeDeclType(sigjmp_bufDecl);
1744 /// Set the type for the C ucontext_t type.
1745 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1746 this->ucontext_tDecl = ucontext_tDecl;
1749 /// Retrieve the C ucontext_t type.
1750 QualType getucontext_tType() const {
1752 return getTypeDeclType(ucontext_tDecl);
1756 /// The result type of logical operations, '<', '>', '!=', etc.
1757 QualType getLogicalOperationType() const {
1758 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1761 /// Emit the Objective-CC type encoding for the given type \p T into
1764 /// If \p Field is specified then record field names are also encoded.
1765 void getObjCEncodingForType(QualType T, std::string &S,
1766 const FieldDecl *Field=nullptr,
1767 QualType *NotEncodedT=nullptr) const;
1769 /// Emit the Objective-C property type encoding for the given
1770 /// type \p T into \p S.
1771 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1773 void getLegacyIntegralTypeEncoding(QualType &t) const;
1775 /// Put the string version of the type qualifiers \p QT into \p S.
1776 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1777 std::string &S) const;
1779 /// Emit the encoded type for the function \p Decl into \p S.
1781 /// This is in the same format as Objective-C method encodings.
1783 /// \returns true if an error occurred (e.g., because one of the parameter
1784 /// types is incomplete), false otherwise.
1785 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1787 /// Emit the encoded type for the method declaration \p Decl into
1789 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1790 bool Extended = false) const;
1792 /// Return the encoded type for this block declaration.
1793 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1795 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1796 /// this method declaration. If non-NULL, Container must be either
1797 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1798 /// only be NULL when getting encodings for protocol properties.
1799 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1800 const Decl *Container) const;
1802 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1803 ObjCProtocolDecl *rProto) const;
1805 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1806 const ObjCPropertyDecl *PD,
1807 const Decl *Container) const;
1809 /// Return the size of type \p T for Objective-C encoding purpose,
1811 CharUnits getObjCEncodingTypeSize(QualType T) const;
1813 /// Retrieve the typedef corresponding to the predefined \c id type
1815 TypedefDecl *getObjCIdDecl() const;
1817 /// Represents the Objective-CC \c id type.
1819 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1820 /// pointer type, a pointer to a struct.
1821 QualType getObjCIdType() const {
1822 return getTypeDeclType(getObjCIdDecl());
1825 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1827 TypedefDecl *getObjCSelDecl() const;
1829 /// Retrieve the type that corresponds to the predefined Objective-C
1831 QualType getObjCSelType() const {
1832 return getTypeDeclType(getObjCSelDecl());
1835 /// Retrieve the typedef declaration corresponding to the predefined
1836 /// Objective-C 'Class' type.
1837 TypedefDecl *getObjCClassDecl() const;
1839 /// Represents the Objective-C \c Class type.
1841 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1842 /// pointer type, a pointer to a struct.
1843 QualType getObjCClassType() const {
1844 return getTypeDeclType(getObjCClassDecl());
1847 /// Retrieve the Objective-C class declaration corresponding to
1848 /// the predefined \c Protocol class.
1849 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1851 /// Retrieve declaration of 'BOOL' typedef
1852 TypedefDecl *getBOOLDecl() const {
1856 /// Save declaration of 'BOOL' typedef
1857 void setBOOLDecl(TypedefDecl *TD) {
1861 /// type of 'BOOL' type.
1862 QualType getBOOLType() const {
1863 return getTypeDeclType(getBOOLDecl());
1866 /// Retrieve the type of the Objective-C \c Protocol class.
1867 QualType getObjCProtoType() const {
1868 return getObjCInterfaceType(getObjCProtocolDecl());
1871 /// Retrieve the C type declaration corresponding to the predefined
1872 /// \c __builtin_va_list type.
1873 TypedefDecl *getBuiltinVaListDecl() const;
1875 /// Retrieve the type of the \c __builtin_va_list type.
1876 QualType getBuiltinVaListType() const {
1877 return getTypeDeclType(getBuiltinVaListDecl());
1880 /// Retrieve the C type declaration corresponding to the predefined
1881 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1882 /// for some targets.
1883 Decl *getVaListTagDecl() const;
1885 /// Retrieve the C type declaration corresponding to the predefined
1886 /// \c __builtin_ms_va_list type.
1887 TypedefDecl *getBuiltinMSVaListDecl() const;
1889 /// Retrieve the type of the \c __builtin_ms_va_list type.
1890 QualType getBuiltinMSVaListType() const {
1891 return getTypeDeclType(getBuiltinMSVaListDecl());
1894 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
1895 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
1897 /// Retrieve the implicitly-predeclared 'struct _GUID' type.
1898 QualType getMSGuidType() const {
1899 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
1900 return getTagDeclType(MSGuidTagDecl);
1903 /// Return whether a declaration to a builtin is allowed to be
1904 /// overloaded/redeclared.
1905 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
1907 /// Return a type with additional \c const, \c volatile, or
1908 /// \c restrict qualifiers.
1909 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1910 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1913 /// Un-split a SplitQualType.
1914 QualType getQualifiedType(SplitQualType split) const {
1915 return getQualifiedType(split.Ty, split.Quals);
1918 /// Return a type with additional qualifiers.
1919 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1920 if (!Qs.hasNonFastQualifiers())
1921 return T.withFastQualifiers(Qs.getFastQualifiers());
1922 QualifierCollector Qc(Qs);
1923 const Type *Ptr = Qc.strip(T);
1924 return getExtQualType(Ptr, Qc);
1927 /// Return a type with additional qualifiers.
1928 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1929 if (!Qs.hasNonFastQualifiers())
1930 return QualType(T, Qs.getFastQualifiers());
1931 return getExtQualType(T, Qs);
1934 /// Return a type with the given lifetime qualifier.
1936 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1937 QualType getLifetimeQualifiedType(QualType type,
1938 Qualifiers::ObjCLifetime lifetime) {
1939 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1940 assert(lifetime != Qualifiers::OCL_None);
1943 qs.addObjCLifetime(lifetime);
1944 return getQualifiedType(type, qs);
1947 /// getUnqualifiedObjCPointerType - Returns version of
1948 /// Objective-C pointer type with lifetime qualifier removed.
1949 QualType getUnqualifiedObjCPointerType(QualType type) const {
1950 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1951 !type.getQualifiers().hasObjCLifetime())
1953 Qualifiers Qs = type.getQualifiers();
1954 Qs.removeObjCLifetime();
1955 return getQualifiedType(type.getUnqualifiedType(), Qs);
1958 unsigned char getFixedPointScale(QualType Ty) const;
1959 unsigned char getFixedPointIBits(QualType Ty) const;
1960 FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
1961 APFixedPoint getFixedPointMax(QualType Ty) const;
1962 APFixedPoint getFixedPointMin(QualType Ty) const;
1964 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1965 SourceLocation NameLoc) const;
1967 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1968 UnresolvedSetIterator End) const;
1969 TemplateName getAssumedTemplateName(DeclarationName Name) const;
1971 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1972 bool TemplateKeyword,
1973 TemplateDecl *Template) const;
1975 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1976 const IdentifierInfo *Name) const;
1977 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1978 OverloadedOperatorKind Operator) const;
1979 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1980 TemplateName replacement) const;
1981 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1982 const TemplateArgument &ArgPack) const;
1984 enum GetBuiltinTypeError {
1991 /// Missing a type from <stdio.h>
1994 /// Missing a type from <setjmp.h>
1997 /// Missing a type from <ucontext.h>
2001 /// Return the type for the specified builtin.
2003 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2004 /// arguments to the builtin that are required to be integer constant
2006 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2007 unsigned *IntegerConstantArgs = nullptr) const;
2009 /// Types and expressions required to build C++2a three-way comparisons
2010 /// using operator<=>, including the values return by builtin <=> operators.
2011 ComparisonCategories CompCategories;
2014 CanQualType getFromTargetType(unsigned Type) const;
2015 TypeInfo getTypeInfoImpl(const Type *T) const;
2017 //===--------------------------------------------------------------------===//
2019 //===--------------------------------------------------------------------===//
2022 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2023 /// collection attributes.
2024 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2026 /// Return true if the given vector types are of the same unqualified
2027 /// type or if they are equivalent to the same GCC vector type.
2029 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2031 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2033 /// Return true if the type has been explicitly qualified with ObjC ownership.
2034 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2035 /// some cases the compiler treats these differently.
2036 bool hasDirectOwnershipQualifier(QualType Ty) const;
2038 /// Return true if this is an \c NSObject object with its \c NSObject
2040 static bool isObjCNSObjectType(QualType Ty) {
2041 return Ty->isObjCNSObjectType();
2044 //===--------------------------------------------------------------------===//
2045 // Type Sizing and Analysis
2046 //===--------------------------------------------------------------------===//
2048 /// Return the APFloat 'semantics' for the specified scalar floating
2050 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2052 /// Get the size and alignment of the specified complete type in bits.
2053 TypeInfo getTypeInfo(const Type *T) const;
2054 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2056 /// Get default simd alignment of the specified complete type in bits.
2057 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2059 /// Return the size of the specified (complete) type \p T, in bits.
2060 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2061 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2063 /// Return the size of the character type, in bits.
2064 uint64_t getCharWidth() const {
2065 return getTypeSize(CharTy);
2068 /// Convert a size in bits to a size in characters.
2069 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2071 /// Convert a size in characters to a size in bits.
2072 int64_t toBits(CharUnits CharSize) const;
2074 /// Return the size of the specified (complete) type \p T, in
2076 CharUnits getTypeSizeInChars(QualType T) const;
2077 CharUnits getTypeSizeInChars(const Type *T) const;
2079 Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2080 if (Ty->isIncompleteType() || Ty->isDependentType())
2082 return getTypeSizeInChars(Ty);
2085 Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2086 return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2089 /// Return the ABI-specified alignment of a (complete) type \p T, in
2091 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2092 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2094 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2095 /// before alignment adjustments, in bits.
2097 /// This alignment is curently used only by ARM and AArch64 when passing
2098 /// arguments of a composite type.
2099 unsigned getTypeUnadjustedAlign(QualType T) const {
2100 return getTypeUnadjustedAlign(T.getTypePtr());
2102 unsigned getTypeUnadjustedAlign(const Type *T) const;
2104 /// Return the ABI-specified alignment of a type, in bits, or 0 if
2105 /// the type is incomplete and we cannot determine the alignment (for
2106 /// example, from alignment attributes).
2107 unsigned getTypeAlignIfKnown(QualType T) const;
2109 /// Return the ABI-specified alignment of a (complete) type \p T, in
2111 CharUnits getTypeAlignInChars(QualType T) const;
2112 CharUnits getTypeAlignInChars(const Type *T) const;
2114 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2115 /// in characters, before alignment adjustments. This method does not work on
2116 /// incomplete types.
2117 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2118 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2120 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2121 // type is a record, its data size is returned.
2122 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2124 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2125 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2127 /// Determine if the alignment the type has was required using an
2128 /// alignment attribute.
2129 bool isAlignmentRequired(const Type *T) const;
2130 bool isAlignmentRequired(QualType T) const;
2132 /// Return the "preferred" alignment of the specified type \p T for
2133 /// the current target, in bits.
2135 /// This can be different than the ABI alignment in cases where it is
2136 /// beneficial for performance to overalign a data type.
2137 unsigned getPreferredTypeAlign(const Type *T) const;
2139 /// Return the default alignment for __attribute__((aligned)) on
2140 /// this target, to be used if no alignment value is specified.
2141 unsigned getTargetDefaultAlignForAttributeAligned() const;
2143 /// Return the alignment in bits that should be given to a
2144 /// global variable with type \p T.
2145 unsigned getAlignOfGlobalVar(QualType T) const;
2147 /// Return the alignment in characters that should be given to a
2148 /// global variable with type \p T.
2149 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2151 /// Return a conservative estimate of the alignment of the specified
2154 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2157 /// If \p ForAlignof, references are treated like their underlying type
2158 /// and large arrays don't get any special treatment. If not \p ForAlignof
2159 /// it computes the value expected by CodeGen: references are treated like
2160 /// pointers and large arrays get extra alignment.
2161 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2163 /// Return the alignment (in bytes) of the thrown exception object. This is
2164 /// only meaningful for targets that allocate C++ exceptions in a system
2165 /// runtime, such as those using the Itanium C++ ABI.
2166 CharUnits getExnObjectAlignment() const;
2168 /// Get or compute information about the layout of the specified
2169 /// record (struct/union/class) \p D, which indicates its size and field
2170 /// position information.
2171 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2173 /// Get or compute information about the layout of the specified
2174 /// Objective-C interface.
2175 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2178 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2179 bool Simple = false) const;
2181 /// Get or compute information about the layout of the specified
2182 /// Objective-C implementation.
2184 /// This may differ from the interface if synthesized ivars are present.
2185 const ASTRecordLayout &
2186 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2188 /// Get our current best idea for the key function of the
2189 /// given record decl, or nullptr if there isn't one.
2191 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2192 /// ...the first non-pure virtual function that is not inline at the
2193 /// point of class definition.
2195 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2196 /// virtual functions that are defined 'inline', which means that
2197 /// the result of this computation can change.
2198 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2200 /// Observe that the given method cannot be a key function.
2201 /// Checks the key-function cache for the method's class and clears it
2202 /// if matches the given declaration.
2204 /// This is used in ABIs where out-of-line definitions marked
2205 /// inline are not considered to be key functions.
2207 /// \param method should be the declaration from the class definition
2208 void setNonKeyFunction(const CXXMethodDecl *method);
2210 /// Loading virtual member pointers using the virtual inheritance model
2211 /// always results in an adjustment using the vbtable even if the index is
2214 /// This is usually OK because the first slot in the vbtable points
2215 /// backwards to the top of the MDC. However, the MDC might be reusing a
2216 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2217 /// points to the start of the nv-base which introduced the vbptr and *not*
2218 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2219 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2221 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2222 uint64_t getFieldOffset(const ValueDecl *FD) const;
2224 /// Get the offset of an ObjCIvarDecl in bits.
2225 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2226 const ObjCImplementationDecl *ID,
2227 const ObjCIvarDecl *Ivar) const;
2229 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2231 VTableContextBase *getVTableContext();
2233 /// If \p T is null pointer, assume the target in ASTContext.
2234 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2236 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2237 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2239 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2240 void CollectInheritedProtocols(const Decl *CDecl,
2241 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2243 /// Return true if the specified type has unique object representations
2244 /// according to (C++17 [meta.unary.prop]p9)
2245 bool hasUniqueObjectRepresentations(QualType Ty) const;
2247 //===--------------------------------------------------------------------===//
2249 //===--------------------------------------------------------------------===//
2251 /// Return the canonical (structural) type corresponding to the
2252 /// specified potentially non-canonical type \p T.
2254 /// The non-canonical version of a type may have many "decorated" versions of
2255 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2256 /// returned type is guaranteed to be free of any of these, allowing two
2257 /// canonical types to be compared for exact equality with a simple pointer
2259 CanQualType getCanonicalType(QualType T) const {
2260 return CanQualType::CreateUnsafe(T.getCanonicalType());
2263 const Type *getCanonicalType(const Type *T) const {
2264 return T->getCanonicalTypeInternal().getTypePtr();
2267 /// Return the canonical parameter type corresponding to the specific
2268 /// potentially non-canonical one.
2270 /// Qualifiers are stripped off, functions are turned into function
2271 /// pointers, and arrays decay one level into pointers.
2272 CanQualType getCanonicalParamType(QualType T) const;
2274 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2275 bool hasSameType(QualType T1, QualType T2) const {
2276 return getCanonicalType(T1) == getCanonicalType(T2);
2278 bool hasSameType(const Type *T1, const Type *T2) const {
2279 return getCanonicalType(T1) == getCanonicalType(T2);
2282 /// Return this type as a completely-unqualified array type,
2283 /// capturing the qualifiers in \p Quals.
2285 /// This will remove the minimal amount of sugaring from the types, similar
2286 /// to the behavior of QualType::getUnqualifiedType().
2288 /// \param T is the qualified type, which may be an ArrayType
2290 /// \param Quals will receive the full set of qualifiers that were
2291 /// applied to the array.
2293 /// \returns if this is an array type, the completely unqualified array type
2294 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2295 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2297 /// Determine whether the given types are equivalent after
2298 /// cvr-qualifiers have been removed.
2299 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2300 return getCanonicalType(T1).getTypePtr() ==
2301 getCanonicalType(T2).getTypePtr();
2304 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2305 bool IsParam) const {
2306 auto SubTnullability = SubT->getNullability(*this);
2307 auto SuperTnullability = SuperT->getNullability(*this);
2308 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2309 // Neither has nullability; return true
2310 if (!SubTnullability)
2312 // Both have nullability qualifier.
2313 if (*SubTnullability == *SuperTnullability ||
2314 *SubTnullability == NullabilityKind::Unspecified ||
2315 *SuperTnullability == NullabilityKind::Unspecified)
2319 // Ok for the superclass method parameter to be "nonnull" and the subclass
2320 // method parameter to be "nullable"
2321 return (*SuperTnullability == NullabilityKind::NonNull &&
2322 *SubTnullability == NullabilityKind::Nullable);
2325 // For the return type, it's okay for the superclass method to specify
2326 // "nullable" and the subclass method specify "nonnull"
2327 return (*SuperTnullability == NullabilityKind::Nullable &&
2328 *SubTnullability == NullabilityKind::NonNull);
2334 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2335 const ObjCMethodDecl *MethodImp);
2337 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2338 bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2340 /// Determine if two types are similar, according to the C++ rules. That is,
2341 /// determine if they are the same other than qualifiers on the initial
2342 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2343 /// pointer) types and their element types.
2345 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2346 /// those qualifiers are also ignored in the 'similarity' check.
2347 bool hasSimilarType(QualType T1, QualType T2);
2349 /// Determine if two types are similar, ignoring only CVR qualifiers.
2350 bool hasCvrSimilarType(QualType T1, QualType T2);
2352 /// Retrieves the "canonical" nested name specifier for a
2353 /// given nested name specifier.
2355 /// The canonical nested name specifier is a nested name specifier
2356 /// that uniquely identifies a type or namespace within the type
2357 /// system. For example, given:
2362 /// template<typename T> struct X { typename T* type; };
2366 /// template<typename T> struct Y {
2367 /// typename N::S::X<T>::type member;
2371 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2372 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2373 /// by declarations in the type system and the canonical type for
2374 /// the template type parameter 'T' is template-param-0-0.
2375 NestedNameSpecifier *
2376 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2378 /// Retrieves the default calling convention for the current target.
2379 CallingConv getDefaultCallingConvention(bool IsVariadic,
2381 bool IsBuiltin = false) const;
2383 /// Retrieves the "canonical" template name that refers to a
2386 /// The canonical template name is the simplest expression that can
2387 /// be used to refer to a given template. For most templates, this
2388 /// expression is just the template declaration itself. For example,
2389 /// the template std::vector can be referred to via a variety of
2390 /// names---std::vector, \::std::vector, vector (if vector is in
2391 /// scope), etc.---but all of these names map down to the same
2392 /// TemplateDecl, which is used to form the canonical template name.
2394 /// Dependent template names are more interesting. Here, the
2395 /// template name could be something like T::template apply or
2396 /// std::allocator<T>::template rebind, where the nested name
2397 /// specifier itself is dependent. In this case, the canonical
2398 /// template name uses the shortest form of the dependent
2399 /// nested-name-specifier, which itself contains all canonical
2400 /// types, values, and templates.
2401 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2403 /// Determine whether the given template names refer to the same
2405 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2407 /// Retrieve the "canonical" template argument.
2409 /// The canonical template argument is the simplest template argument
2410 /// (which may be a type, value, expression, or declaration) that
2411 /// expresses the value of the argument.
2412 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2415 /// Type Query functions. If the type is an instance of the specified class,
2416 /// return the Type pointer for the underlying maximally pretty type. This
2417 /// is a member of ASTContext because this may need to do some amount of
2418 /// canonicalization, e.g. to move type qualifiers into the element type.
2419 const ArrayType *getAsArrayType(QualType T) const;
2420 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2421 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2423 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2424 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2426 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2427 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2429 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2431 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2434 /// Return the innermost element type of an array type.
2436 /// For example, will return "int" for int[m][n]
2437 QualType getBaseElementType(const ArrayType *VAT) const;
2439 /// Return the innermost element type of a type (which needn't
2440 /// actually be an array type).
2441 QualType getBaseElementType(QualType QT) const;
2443 /// Return number of constant array elements.
2444 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2446 /// Perform adjustment on the parameter type of a function.
2448 /// This routine adjusts the given parameter type @p T to the actual
2449 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2450 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2451 QualType getAdjustedParameterType(QualType T) const;
2453 /// Retrieve the parameter type as adjusted for use in the signature
2454 /// of a function, decaying array and function types and removing top-level
2456 QualType getSignatureParameterType(QualType T) const;
2458 QualType getExceptionObjectType(QualType T) const;
2460 /// Return the properly qualified result of decaying the specified
2461 /// array type to a pointer.
2463 /// This operation is non-trivial when handling typedefs etc. The canonical
2464 /// type of \p T must be an array type, this returns a pointer to a properly
2465 /// qualified element of the array.
2467 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2468 QualType getArrayDecayedType(QualType T) const;
2470 /// Return the type that \p PromotableType will promote to: C99
2471 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2472 QualType getPromotedIntegerType(QualType PromotableType) const;
2474 /// Recurses in pointer/array types until it finds an Objective-C
2475 /// retainable type and returns its ownership.
2476 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2478 /// Whether this is a promotable bitfield reference according
2479 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2481 /// \returns the type this bit-field will promote to, or NULL if no
2482 /// promotion occurs.
2483 QualType isPromotableBitField(Expr *E) const;
2485 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2487 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2488 /// \p LHS < \p RHS, return -1.
2489 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2491 /// Compare the rank of the two specified floating point types,
2492 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2494 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2495 /// \p LHS < \p RHS, return -1.
2496 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2498 /// Compare the rank of two floating point types as above, but compare equal
2499 /// if both types have the same floating-point semantics on the target (i.e.
2500 /// long double and double on AArch64 will return 0).
2501 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2503 /// Return a real floating point or a complex type (based on
2504 /// \p typeDomain/\p typeSize).
2506 /// \param typeDomain a real floating point or complex type.
2507 /// \param typeSize a real floating point or complex type.
2508 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2509 QualType typeDomain) const;
2511 unsigned getTargetAddressSpace(QualType T) const {
2512 return getTargetAddressSpace(T.getQualifiers());
2515 unsigned getTargetAddressSpace(Qualifiers Q) const {
2516 return getTargetAddressSpace(Q.getAddressSpace());
2519 unsigned getTargetAddressSpace(LangAS AS) const;
2521 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2523 /// Get target-dependent integer value for null pointer which is used for
2524 /// constant folding.
2525 uint64_t getTargetNullPointerValue(QualType QT) const;
2527 bool addressSpaceMapManglingFor(LangAS AS) const {
2528 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2532 // Helper for integer ordering
2533 unsigned getIntegerRank(const Type *T) const;
2536 //===--------------------------------------------------------------------===//
2537 // Type Compatibility Predicates
2538 //===--------------------------------------------------------------------===//
2540 /// Compatibility predicates used to check assignment expressions.
2541 bool typesAreCompatible(QualType T1, QualType T2,
2542 bool CompareUnqualified = false); // C99 6.2.7p1
2544 bool propertyTypesAreCompatible(QualType, QualType);
2545 bool typesAreBlockPointerCompatible(QualType, QualType);
2547 bool isObjCIdType(QualType T) const {
2548 return T == getObjCIdType();
2551 bool isObjCClassType(QualType T) const {
2552 return T == getObjCClassType();
2555 bool isObjCSelType(QualType T) const {
2556 return T == getObjCSelType();
2559 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2560 const ObjCObjectPointerType *RHS,
2563 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2564 const ObjCObjectPointerType *RHS);
2566 // Check the safety of assignment from LHS to RHS
2567 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2568 const ObjCObjectPointerType *RHSOPT);
2569 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2570 const ObjCObjectType *RHS);
2571 bool canAssignObjCInterfacesInBlockPointer(
2572 const ObjCObjectPointerType *LHSOPT,
2573 const ObjCObjectPointerType *RHSOPT,
2574 bool BlockReturnType);
2575 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2576 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2577 const ObjCObjectPointerType *RHSOPT);
2578 bool canBindObjCObjectType(QualType To, QualType From);
2580 // Functions for calculating composite types
2581 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2582 bool Unqualified = false, bool BlockReturnType = false);
2583 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2584 bool Unqualified = false, bool AllowCXX = false);
2585 QualType mergeFunctionParameterTypes(QualType, QualType,
2586 bool OfBlockPointer = false,
2587 bool Unqualified = false);
2588 QualType mergeTransparentUnionType(QualType, QualType,
2589 bool OfBlockPointer=false,
2590 bool Unqualified = false);
2592 QualType mergeObjCGCQualifiers(QualType, QualType);
2594 /// This function merges the ExtParameterInfo lists of two functions. It
2595 /// returns true if the lists are compatible. The merged list is returned in
2598 /// \param FirstFnType The type of the first function.
2600 /// \param SecondFnType The type of the second function.
2602 /// \param CanUseFirst This flag is set to true if the first function's
2603 /// ExtParameterInfo list can be used as the composite list of
2604 /// ExtParameterInfo.
2606 /// \param CanUseSecond This flag is set to true if the second function's
2607 /// ExtParameterInfo list can be used as the composite list of
2608 /// ExtParameterInfo.
2610 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2611 /// empty if none of the flags are set.
2613 bool mergeExtParameterInfo(
2614 const FunctionProtoType *FirstFnType,
2615 const FunctionProtoType *SecondFnType,
2616 bool &CanUseFirst, bool &CanUseSecond,
2617 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2619 void ResetObjCLayout(const ObjCContainerDecl *CD);
2621 //===--------------------------------------------------------------------===//
2622 // Integer Predicates
2623 //===--------------------------------------------------------------------===//
2625 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2626 // of bits in an integer type excluding any padding bits.
2627 unsigned getIntWidth(QualType T) const;
2629 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2630 // unsigned integer type. This method takes a signed type, and returns the
2631 // corresponding unsigned integer type.
2632 // With the introduction of fixed point types in ISO N1169, this method also
2633 // accepts fixed point types and returns the corresponding unsigned type for
2634 // a given fixed point type.
2635 QualType getCorrespondingUnsignedType(QualType T) const;
2637 // Per ISO N1169, this method accepts fixed point types and returns the
2638 // corresponding saturated type for a given fixed point type.
2639 QualType getCorrespondingSaturatedType(QualType Ty) const;
2641 // This method accepts fixed point types and returns the corresponding signed
2642 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
2643 // fixed point types because there are unsigned integer types like bool and
2644 // char8_t that don't have signed equivalents.
2645 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
2647 //===--------------------------------------------------------------------===//
2649 //===--------------------------------------------------------------------===//
2651 /// Make an APSInt of the appropriate width and signedness for the
2652 /// given \p Value and integer \p Type.
2653 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2654 // If Type is a signed integer type larger than 64 bits, we need to be sure
2655 // to sign extend Res appropriately.
2656 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2658 unsigned Width = getIntWidth(Type);
2659 if (Width != Res.getBitWidth())
2660 return Res.extOrTrunc(Width);
2664 bool isSentinelNullExpr(const Expr *E);
2666 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2668 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2670 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2672 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2674 /// Return true if there is at least one \@implementation in the TU.
2675 bool AnyObjCImplementation() {
2676 return !ObjCImpls.empty();
2679 /// Set the implementation of ObjCInterfaceDecl.
2680 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2681 ObjCImplementationDecl *ImplD);
2683 /// Set the implementation of ObjCCategoryDecl.
2684 void setObjCImplementation(ObjCCategoryDecl *CatD,
2685 ObjCCategoryImplDecl *ImplD);
2687 /// Get the duplicate declaration of a ObjCMethod in the same
2688 /// interface, or null if none exists.
2689 const ObjCMethodDecl *
2690 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2692 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2693 const ObjCMethodDecl *Redecl);
2695 /// Returns the Objective-C interface that \p ND belongs to if it is
2696 /// an Objective-C method/property/ivar etc. that is part of an interface,
2697 /// otherwise returns null.
2698 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2700 /// Set the copy initialization expression of a block var decl. \p CanThrow
2701 /// indicates whether the copy expression can throw or not.
2702 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2704 /// Get the copy initialization expression of the VarDecl \p VD, or
2705 /// nullptr if none exists.
2706 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2708 /// Allocate an uninitialized TypeSourceInfo.
2710 /// The caller should initialize the memory held by TypeSourceInfo using
2711 /// the TypeLoc wrappers.
2713 /// \param T the type that will be the basis for type source info. This type
2714 /// should refer to how the declarator was written in source code, not to
2715 /// what type semantic analysis resolved the declarator to.
2717 /// \param Size the size of the type info to create, or 0 if the size
2718 /// should be calculated based on the type.
2719 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2721 /// Allocate a TypeSourceInfo where all locations have been
2722 /// initialized to a given location, which defaults to the empty
2725 getTrivialTypeSourceInfo(QualType T,
2726 SourceLocation Loc = SourceLocation()) const;
2728 /// Add a deallocation callback that will be invoked when the
2729 /// ASTContext is destroyed.
2731 /// \param Callback A callback function that will be invoked on destruction.
2733 /// \param Data Pointer data that will be provided to the callback function
2734 /// when it is called.
2735 void AddDeallocation(void (*Callback)(void *), void *Data) const;
2737 /// If T isn't trivially destructible, calls AddDeallocation to register it
2738 /// for destruction.
2739 template <typename T> void addDestruction(T *Ptr) const {
2740 if (!std::is_trivially_destructible<T>::value) {
2741 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2742 AddDeallocation(DestroyPtr, Ptr);
2746 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2747 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2749 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2750 /// lazily, only when used; this is only relevant for function or file scoped
2751 /// var definitions.
2753 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2755 bool DeclMustBeEmitted(const Decl *D);
2757 /// Visits all versions of a multiversioned function with the passed
2759 void forEachMultiversionedFunctionVersion(
2760 const FunctionDecl *FD,
2761 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2763 const CXXConstructorDecl *
2764 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2766 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2767 CXXConstructorDecl *CD);
2769 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2771 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2773 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2775 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2777 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2778 unsigned getManglingNumber(const NamedDecl *ND) const;
2780 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2781 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2783 /// Retrieve the context for computing mangling numbers in the given
2785 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2786 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
2787 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
2790 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2792 /// Used by ParmVarDecl to store on the side the
2793 /// index of the parameter when it exceeds the size of the normal bitfield.
2794 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2796 /// Used by ParmVarDecl to retrieve on the side the
2797 /// index of the parameter when it exceeds the size of the normal bitfield.
2798 unsigned getParameterIndex(const ParmVarDecl *D) const;
2800 /// Return a string representing the human readable name for the specified
2801 /// function declaration or file name. Used by SourceLocExpr and
2802 /// PredefinedExpr to cache evaluated results.
2803 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
2805 /// Return a declaration for the global GUID object representing the given
2807 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
2809 /// Parses the target attributes passed in, and returns only the ones that are
2810 /// valid feature names.
2811 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
2813 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2814 const FunctionDecl *) const;
2815 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
2816 GlobalDecl GD) const;
2818 //===--------------------------------------------------------------------===//
2820 //===--------------------------------------------------------------------===//
2822 /// The number of implicitly-declared default constructors.
2823 unsigned NumImplicitDefaultConstructors = 0;
2825 /// The number of implicitly-declared default constructors for
2826 /// which declarations were built.
2827 unsigned NumImplicitDefaultConstructorsDeclared = 0;
2829 /// The number of implicitly-declared copy constructors.
2830 unsigned NumImplicitCopyConstructors = 0;
2832 /// The number of implicitly-declared copy constructors for
2833 /// which declarations were built.
2834 unsigned NumImplicitCopyConstructorsDeclared = 0;
2836 /// The number of implicitly-declared move constructors.
2837 unsigned NumImplicitMoveConstructors = 0;
2839 /// The number of implicitly-declared move constructors for
2840 /// which declarations were built.
2841 unsigned NumImplicitMoveConstructorsDeclared = 0;
2843 /// The number of implicitly-declared copy assignment operators.
2844 unsigned NumImplicitCopyAssignmentOperators = 0;
2846 /// The number of implicitly-declared copy assignment operators for
2847 /// which declarations were built.
2848 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
2850 /// The number of implicitly-declared move assignment operators.
2851 unsigned NumImplicitMoveAssignmentOperators = 0;
2853 /// The number of implicitly-declared move assignment operators for
2854 /// which declarations were built.
2855 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
2857 /// The number of implicitly-declared destructors.
2858 unsigned NumImplicitDestructors = 0;
2860 /// The number of implicitly-declared destructors for which
2861 /// declarations were built.
2862 unsigned NumImplicitDestructorsDeclared = 0;
2865 /// Initialize built-in types.
2867 /// This routine may only be invoked once for a given ASTContext object.
2868 /// It is normally invoked after ASTContext construction.
2870 /// \param Target The target
2871 void InitBuiltinTypes(const TargetInfo &Target,
2872 const TargetInfo *AuxTarget = nullptr);
2875 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2877 class ObjCEncOptions {
2880 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
2883 ObjCEncOptions() : Bits(0) {}
2884 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
2886 #define OPT_LIST(V) \
2887 V(ExpandPointedToStructures, 0) \
2888 V(ExpandStructures, 1) \
2889 V(IsOutermostType, 2) \
2890 V(EncodingProperty, 3) \
2891 V(IsStructField, 4) \
2892 V(EncodeBlockParameters, 5) \
2893 V(EncodeClassNames, 6) \
2895 #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
2899 #define V(N,I) bool N() const { return Bits & 1 << I; }
2905 LLVM_NODISCARD ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
2906 return Bits & Mask.Bits;
2909 LLVM_NODISCARD ObjCEncOptions forComponentType() const {
2910 ObjCEncOptions Mask = ObjCEncOptions()
2911 .setIsOutermostType()
2912 .setIsStructField();
2913 return Bits & ~Mask.Bits;
2917 // Return the Objective-C type encoding for a given type.
2918 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2919 ObjCEncOptions Options,
2920 const FieldDecl *Field,
2921 QualType *NotEncodedT = nullptr) const;
2923 // Adds the encoding of the structure's members.
2924 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2925 const FieldDecl *Field,
2926 bool includeVBases = true,
2927 QualType *NotEncodedT=nullptr) const;
2930 // Adds the encoding of a method parameter or return type.
2931 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2932 QualType T, std::string& S,
2933 bool Extended) const;
2935 /// Returns true if this is an inline-initialized static data member
2936 /// which is treated as a definition for MSVC compatibility.
2937 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2939 enum class InlineVariableDefinitionKind {
2940 /// Not an inline variable.
2943 /// Weak definition of inline variable.
2946 /// Weak for now, might become strong later in this TU.
2949 /// Strong definition.
2953 /// Determine whether a definition of this inline variable should
2954 /// be treated as a weak or strong definition. For compatibility with
2955 /// C++14 and before, for a constexpr static data member, if there is an
2956 /// out-of-line declaration of the member, we may promote it from weak to
2958 InlineVariableDefinitionKind
2959 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2962 friend class DeclarationNameTable;
2963 friend class DeclContext;
2965 const ASTRecordLayout &
2966 getObjCLayout(const ObjCInterfaceDecl *D,
2967 const ObjCImplementationDecl *Impl) const;
2969 /// A set of deallocations that should be performed when the
2970 /// ASTContext is destroyed.
2971 // FIXME: We really should have a better mechanism in the ASTContext to
2972 // manage running destructors for types which do variable sized allocation
2973 // within the AST. In some places we thread the AST bump pointer allocator
2974 // into the datastructures which avoids this mess during deallocation but is
2975 // wasteful of memory, and here we require a lot of error prone book keeping
2976 // in order to track and run destructors while we're tearing things down.
2977 using DeallocationFunctionsAndArguments =
2978 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2979 mutable DeallocationFunctionsAndArguments Deallocations;
2981 // FIXME: This currently contains the set of StoredDeclMaps used
2982 // by DeclContext objects. This probably should not be in ASTContext,
2983 // but we include it here so that ASTContext can quickly deallocate them.
2984 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2986 std::vector<Decl *> TraversalScope;
2988 std::unique_ptr<VTableContextBase> VTContext;
2990 void ReleaseDeclContextMaps();
2993 enum PragmaSectionFlag : unsigned {
2999 PSF_ZeroInit = 0x10,
3000 PSF_Invalid = 0x80000000U,
3003 struct SectionInfo {
3004 DeclaratorDecl *Decl;
3005 SourceLocation PragmaSectionLocation;
3008 SectionInfo() = default;
3009 SectionInfo(DeclaratorDecl *Decl,
3010 SourceLocation PragmaSectionLocation,
3012 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3013 SectionFlags(SectionFlags) {}
3016 llvm::StringMap<SectionInfo> SectionInfos;
3018 /// Return a new OMPTraitInfo object owned by this context.
3019 OMPTraitInfo &getNewOMPTraitInfo();
3022 /// All OMPTraitInfo objects live in this collection, one per
3023 /// `pragma omp [begin] declare variant` directive.
3024 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3027 /// Insertion operator for diagnostics.
3028 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3029 const ASTContext::SectionInfo &Section);
3031 /// Utility function for constructing a nullary selector.
3032 inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3033 IdentifierInfo* II = &Ctx.Idents.get(name);
3034 return Ctx.Selectors.getSelector(0, &II);
3037 /// Utility function for constructing an unary selector.
3038 inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3039 IdentifierInfo* II = &Ctx.Idents.get(name);
3040 return Ctx.Selectors.getSelector(1, &II);
3043 } // namespace clang
3045 // operator new and delete aren't allowed inside namespaces.
3047 /// Placement new for using the ASTContext's allocator.
3049 /// This placement form of operator new uses the ASTContext's allocator for
3050 /// obtaining memory.
3052 /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3053 /// Any changes here need to also be made there.
3055 /// We intentionally avoid using a nothrow specification here so that the calls
3056 /// to this operator will not perform a null check on the result -- the
3057 /// underlying allocator never returns null pointers.
3059 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3061 /// // Default alignment (8)
3062 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3063 /// // Specific alignment
3064 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3066 /// Memory allocated through this placement new operator does not need to be
3067 /// explicitly freed, as ASTContext will free all of this memory when it gets
3068 /// destroyed. Please note that you cannot use delete on the pointer.
3070 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3071 /// @param C The ASTContext that provides the allocator.
3072 /// @param Alignment The alignment of the allocated memory (if the underlying
3073 /// allocator supports it).
3074 /// @return The allocated memory. Could be nullptr.
3075 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3076 size_t Alignment /* = 8 */) {
3077 return C.Allocate(Bytes, Alignment);
3080 /// Placement delete companion to the new above.
3082 /// This operator is just a companion to the new above. There is no way of
3083 /// invoking it directly; see the new operator for more details. This operator
3084 /// is called implicitly by the compiler if a placement new expression using
3085 /// the ASTContext throws in the object constructor.
3086 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3090 /// This placement form of operator new[] uses the ASTContext's allocator for
3091 /// obtaining memory.
3093 /// We intentionally avoid using a nothrow specification here so that the calls
3094 /// to this operator will not perform a null check on the result -- the
3095 /// underlying allocator never returns null pointers.
3097 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3099 /// // Default alignment (8)
3100 /// char *data = new (Context) char[10];
3101 /// // Specific alignment
3102 /// char *data = new (Context, 4) char[10];
3104 /// Memory allocated through this placement new[] operator does not need to be
3105 /// explicitly freed, as ASTContext will free all of this memory when it gets
3106 /// destroyed. Please note that you cannot use delete on the pointer.
3108 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3109 /// @param C The ASTContext that provides the allocator.
3110 /// @param Alignment The alignment of the allocated memory (if the underlying
3111 /// allocator supports it).
3112 /// @return The allocated memory. Could be nullptr.
3113 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3114 size_t Alignment /* = 8 */) {
3115 return C.Allocate(Bytes, Alignment);
3118 /// Placement delete[] companion to the new[] above.
3120 /// This operator is just a companion to the new[] above. There is no way of
3121 /// invoking it directly; see the new[] operator for more details. This operator
3122 /// is called implicitly by the compiler if a placement new[] expression using
3123 /// the ASTContext throws in the object constructor.
3124 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3128 /// Create the representation of a LazyGenerationalUpdatePtr.
3129 template <typename Owner, typename T,
3130 void (clang::ExternalASTSource::*Update)(Owner)>
3131 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3132 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3133 const clang::ASTContext &Ctx, T Value) {
3134 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3135 // include ASTContext.h. We explicitly instantiate it for all relevant types
3136 // in ASTContext.cpp.
3137 if (auto *Source = Ctx.getExternalSource())
3138 return new (Ctx) LazyData(Source, Value);
3142 #endif // LLVM_CLANG_AST_ASTCONTEXT_H