1//===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/AST/ASTFwd.h"
18#include "clang/AST/CanonicalType.h"
19#include "clang/AST/CommentCommandTraits.h"
20#include "clang/AST/ComparisonCategories.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/RawCommentList.h"
26#include "clang/AST/SYCLKernelInfo.h"
27#include "clang/AST/TemplateName.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/FoldingSet.h"
34#include "llvm/ADT/IntrusiveRefCntPtr.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/PointerIntPair.h"
37#include "llvm/ADT/PointerUnion.h"
38#include "llvm/ADT/SetVector.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringMap.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/StringSet.h"
43#include "llvm/ADT/TinyPtrVector.h"
44#include "llvm/Support/TypeSize.h"
45#include <optional>
46
47namespace llvm {
48
49class APFixedPoint;
50class FixedPointSemantics;
51struct fltSemantics;
52template <typename T, unsigned N> class SmallPtrSet;
53
54} // namespace llvm
55
56namespace clang {
57
58class APValue;
59class ASTMutationListener;
60class ASTRecordLayout;
61class AtomicExpr;
62class BlockExpr;
63struct BlockVarCopyInit;
64class BuiltinTemplateDecl;
65class CharUnits;
66class ConceptDecl;
67class CXXABI;
68class CXXConstructorDecl;
69class CXXMethodDecl;
70class CXXRecordDecl;
71class DiagnosticsEngine;
72class DynTypedNodeList;
73class Expr;
74enum class FloatModeKind;
75class GlobalDecl;
76class IdentifierTable;
77class LangOptions;
78class MangleContext;
79class MangleNumberingContext;
80class MemberSpecializationInfo;
81class Module;
82struct MSGuidDeclParts;
83class NestedNameSpecifier;
84class NoSanitizeList;
85class ObjCCategoryDecl;
86class ObjCCategoryImplDecl;
87class ObjCContainerDecl;
88class ObjCImplDecl;
89class ObjCImplementationDecl;
90class ObjCInterfaceDecl;
91class ObjCIvarDecl;
92class ObjCMethodDecl;
93class ObjCPropertyDecl;
94class ObjCPropertyImplDecl;
95class ObjCProtocolDecl;
96class ObjCTypeParamDecl;
97class OMPTraitInfo;
98class ParentMapContext;
99struct ParsedTargetAttr;
100class Preprocessor;
101class ProfileList;
102class StoredDeclsMap;
103class TargetAttr;
104class TargetInfo;
105class TemplateDecl;
106class TemplateParameterList;
107class TemplateTemplateParmDecl;
108class TemplateTypeParmDecl;
109class TypeConstraint;
110class UnresolvedSetIterator;
111class UsingShadowDecl;
112class VarTemplateDecl;
113class VTableContextBase;
114class XRayFunctionFilter;
115
116/// A simple array of base specifiers.
117typedef SmallVector<CXXBaseSpecifier *, 4> CXXCastPath;
118
119namespace Builtin {
120
121class Context;
122
123} // namespace Builtin
124
125enum BuiltinTemplateKind : int;
126enum OpenCLTypeKind : uint8_t;
127
128namespace comments {
129
130class FullComment;
131
132} // namespace comments
133
134namespace interp {
135
136class Context;
137
138} // namespace interp
139
140namespace serialization {
141template <class> class AbstractTypeReader;
142} // namespace serialization
143
144enum class AlignRequirementKind {
145 /// The alignment was not explicit in code.
146 None,
147
148 /// The alignment comes from an alignment attribute on a typedef.
149 RequiredByTypedef,
150
151 /// The alignment comes from an alignment attribute on a record type.
152 RequiredByRecord,
153
154 /// The alignment comes from an alignment attribute on a enum type.
155 RequiredByEnum,
156};
157
158struct TypeInfo {
159 uint64_t Width = 0;
160 unsigned Align = 0;
161 AlignRequirementKind AlignRequirement;
162
163 TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
164 TypeInfo(uint64_t Width, unsigned Align,
165 AlignRequirementKind AlignRequirement)
166 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
167 bool isAlignRequired() {
168 return AlignRequirement != AlignRequirementKind::None;
169 }
170};
171
172struct TypeInfoChars {
173 CharUnits Width;
174 CharUnits Align;
175 AlignRequirementKind AlignRequirement;
176
177 TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
178 TypeInfoChars(CharUnits Width, CharUnits Align,
179 AlignRequirementKind AlignRequirement)
180 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
181 bool isAlignRequired() {
182 return AlignRequirement != AlignRequirementKind::None;
183 }
184};
185
186/// Holds long-lived AST nodes (such as types and decls) that can be
187/// referred to throughout the semantic analysis of a file.
188class ASTContext : public RefCountedBase<ASTContext> {
189 friend class NestedNameSpecifier;
190
191 mutable SmallVector<Type *, 0> Types;
192 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
193 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
194 mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize};
195 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
196 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
197 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
198 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
199 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
200 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
201 ConstantArrayTypes;
202 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
203 mutable std::vector<VariableArrayType*> VariableArrayTypes;
204 mutable llvm::ContextualFoldingSet<DependentSizedArrayType, ASTContext &>
205 DependentSizedArrayTypes;
206 mutable llvm::ContextualFoldingSet<DependentSizedExtVectorType, ASTContext &>
207 DependentSizedExtVectorTypes;
208 mutable llvm::ContextualFoldingSet<DependentAddressSpaceType, ASTContext &>
209 DependentAddressSpaceTypes;
210 mutable llvm::FoldingSet<VectorType> VectorTypes;
211 mutable llvm::ContextualFoldingSet<DependentVectorType, ASTContext &>
212 DependentVectorTypes;
213 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
214 mutable llvm::ContextualFoldingSet<DependentSizedMatrixType, ASTContext &>
215 DependentSizedMatrixTypes;
216 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
217 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
218 FunctionProtoTypes;
219 mutable llvm::ContextualFoldingSet<DependentTypeOfExprType, ASTContext &>
220 DependentTypeOfExprTypes;
221 mutable llvm::ContextualFoldingSet<DependentDecltypeType, ASTContext &>
222 DependentDecltypeTypes;
223
224 mutable llvm::ContextualFoldingSet<PackIndexingType, ASTContext &>
225 DependentPackIndexingTypes;
226
227 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
228 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
229 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
230 SubstTemplateTypeParmTypes;
231 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
232 SubstTemplateTypeParmPackTypes;
233 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
234 TemplateSpecializationTypes;
235 mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
236 mutable llvm::FoldingSet<UsingType> UsingTypes;
237 mutable llvm::FoldingSet<TypedefType> TypedefTypes;
238 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{
239 GeneralTypesLog2InitSize};
240 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
241 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
242 ASTContext&>
243 DependentTemplateSpecializationTypes;
244 mutable llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
245 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
246 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
247 mutable llvm::FoldingSet<UnaryTransformType> UnaryTransformTypes;
248 // An AutoType can have a dependency on another AutoType via its template
249 // arguments. Since both dependent and dependency are on the same set,
250 // we can end up in an infinite recursion when looking for a node if we used
251 // a `FoldingSet`, since both could end up in the same bucket.
252 mutable llvm::DenseMap<llvm::FoldingSetNodeID, AutoType *> AutoTypes;
253 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
254 DeducedTemplateSpecializationTypes;
255 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
256 mutable llvm::FoldingSet<AttributedType> AttributedTypes;
257 mutable llvm::FoldingSet<PipeType> PipeTypes;
258 mutable llvm::FoldingSet<BitIntType> BitIntTypes;
259 mutable llvm::ContextualFoldingSet<DependentBitIntType, ASTContext &>
260 DependentBitIntTypes;
261 mutable llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes;
262 llvm::FoldingSet<HLSLAttributedResourceType> HLSLAttributedResourceTypes;
263 llvm::FoldingSet<HLSLInlineSpirvType> HLSLInlineSpirvTypes;
264
265 mutable llvm::FoldingSet<CountAttributedType> CountAttributedTypes;
266
267 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
268 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
269 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
270 SubstTemplateTemplateParms;
271 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
272 ASTContext&>
273 SubstTemplateTemplateParmPacks;
274 mutable llvm::ContextualFoldingSet<DeducedTemplateStorage, ASTContext &>
275 DeducedTemplates;
276
277 mutable llvm::ContextualFoldingSet<ArrayParameterType, ASTContext &>
278 ArrayParameterTypes;
279
280 /// The set of nested name specifiers.
281 ///
282 /// This set is managed by the NestedNameSpecifier class.
283 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
284 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
285
286 /// A cache mapping from RecordDecls to ASTRecordLayouts.
287 ///
288 /// This is lazily created. This is intentionally not serialized.
289 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
290 ASTRecordLayouts;
291 mutable llvm::DenseMap<const ObjCInterfaceDecl *, const ASTRecordLayout *>
292 ObjCLayouts;
293
294 /// A cache from types to size and alignment information.
295 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
296 mutable TypeInfoMap MemoizedTypeInfo;
297
298 /// A cache from types to unadjusted alignment information. Only ARM and
299 /// AArch64 targets need this information, keeping it separate prevents
300 /// imposing overhead on TypeInfo size.
301 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
302 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
303
304 /// A cache mapping from CXXRecordDecls to key functions.
305 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
306
307 /// Mapping from ObjCContainers to their ObjCImplementations.
308 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
309
310 /// Mapping from ObjCMethod to its duplicate declaration in the same
311 /// interface.
312 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
313
314 /// Mapping from __block VarDecls to BlockVarCopyInit.
315 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
316
317 /// Mapping from GUIDs to the corresponding MSGuidDecl.
318 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
319
320 /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl.
321 mutable llvm::FoldingSet<UnnamedGlobalConstantDecl>
322 UnnamedGlobalConstantDecls;
323
324 /// Mapping from APValues to the corresponding TemplateParamObjects.
325 mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
326
327 /// A cache mapping a string value to a StringLiteral object with the same
328 /// value.
329 ///
330 /// This is lazily created. This is intentionally not serialized.
331 mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
332
333 mutable llvm::DenseSet<const FunctionDecl *> DestroyingOperatorDeletes;
334 mutable llvm::DenseSet<const FunctionDecl *> TypeAwareOperatorNewAndDeletes;
335
336 /// The next string literal "version" to allocate during constant evaluation.
337 /// This is used to distinguish between repeated evaluations of the same
338 /// string literal.
339 ///
340 /// We don't need to serialize this because constants get re-evaluated in the
341 /// current file before they are compared locally.
342 unsigned NextStringLiteralVersion = 0;
343
344 /// MD5 hash of CUID. It is calculated when first used and cached by this
345 /// data member.
346 mutable std::string CUIDHash;
347
348 /// Representation of a "canonical" template template parameter that
349 /// is used in canonical template names.
350 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
351 TemplateTemplateParmDecl *Parm;
352
353 public:
354 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
355 : Parm(Parm) {}
356
357 TemplateTemplateParmDecl *getParam() const { return Parm; }
358
359 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
360 Profile(ID, C, Parm);
361 }
362
363 static void Profile(llvm::FoldingSetNodeID &ID,
364 const ASTContext &C,
365 TemplateTemplateParmDecl *Parm);
366 };
367 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
368 const ASTContext&>
369 CanonTemplateTemplateParms;
370
371 /// The typedef for the __int128_t type.
372 mutable TypedefDecl *Int128Decl = nullptr;
373
374 /// The typedef for the __uint128_t type.
375 mutable TypedefDecl *UInt128Decl = nullptr;
376
377 /// The typedef for the target specific predefined
378 /// __builtin_va_list type.
379 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
380
381 /// The typedef for the predefined \c __builtin_ms_va_list type.
382 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
383
384 /// The typedef for the predefined \c id type.
385 mutable TypedefDecl *ObjCIdDecl = nullptr;
386
387 /// The typedef for the predefined \c SEL type.
388 mutable TypedefDecl *ObjCSelDecl = nullptr;
389
390 /// The typedef for the predefined \c Class type.
391 mutable TypedefDecl *ObjCClassDecl = nullptr;
392
393 /// The typedef for the predefined \c Protocol class in Objective-C.
394 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
395
396 /// The typedef for the predefined 'BOOL' type.
397 mutable TypedefDecl *BOOLDecl = nullptr;
398
399 // Typedefs which may be provided defining the structure of Objective-C
400 // pseudo-builtins
401 QualType ObjCIdRedefinitionType;
402 QualType ObjCClassRedefinitionType;
403 QualType ObjCSelRedefinitionType;
404
405 /// The identifier 'bool'.
406 mutable IdentifierInfo *BoolName = nullptr;
407
408 /// The identifier 'NSObject'.
409 mutable IdentifierInfo *NSObjectName = nullptr;
410
411 /// The identifier 'NSCopying'.
412 IdentifierInfo *NSCopyingName = nullptr;
413
414#define BuiltinTemplate(BTName) mutable IdentifierInfo *Name##BTName = nullptr;
415#include "clang/Basic/BuiltinTemplates.inc"
416
417 QualType ObjCConstantStringType;
418 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
419 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
420
421 mutable QualType ObjCSuperType;
422
423 QualType ObjCNSStringType;
424
425 /// The typedef declaration for the Objective-C "instancetype" type.
426 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
427
428 /// The type for the C FILE type.
429 TypeDecl *FILEDecl = nullptr;
430
431 /// The type for the C jmp_buf type.
432 TypeDecl *jmp_bufDecl = nullptr;
433
434 /// The type for the C sigjmp_buf type.
435 TypeDecl *sigjmp_bufDecl = nullptr;
436
437 /// The type for the C ucontext_t type.
438 TypeDecl *ucontext_tDecl = nullptr;
439
440 /// Type for the Block descriptor for Blocks CodeGen.
441 ///
442 /// Since this is only used for generation of debug info, it is not
443 /// serialized.
444 mutable RecordDecl *BlockDescriptorType = nullptr;
445
446 /// Type for the Block descriptor for Blocks CodeGen.
447 ///
448 /// Since this is only used for generation of debug info, it is not
449 /// serialized.
450 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
451
452 /// Declaration for the CUDA cudaConfigureCall function.
453 FunctionDecl *cudaConfigureCallDecl = nullptr;
454
455 /// Keeps track of all declaration attributes.
456 ///
457 /// Since so few decls have attrs, we keep them in a hash map instead of
458 /// wasting space in the Decl class.
459 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
460
461 /// A mapping from non-redeclarable declarations in modules that were
462 /// merged with other declarations to the canonical declaration that they were
463 /// merged into.
464 llvm::DenseMap<Decl*, Decl*> MergedDecls;
465
466 /// A mapping from a defining declaration to a list of modules (other
467 /// than the owning module of the declaration) that contain merged
468 /// definitions of that entity.
469 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
470
471 /// Initializers for a module, in order. Each Decl will be either
472 /// something that has a semantic effect on startup (such as a variable with
473 /// a non-constant initializer), or an ImportDecl (which recursively triggers
474 /// initialization of another module).
475 struct PerModuleInitializers {
476 llvm::SmallVector<Decl*, 4> Initializers;
477 llvm::SmallVector<GlobalDeclID, 4> LazyInitializers;
478
479 void resolve(ASTContext &Ctx);
480 };
481 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
482
483 /// This is the top-level (C++20) Named module we are building.
484 Module *CurrentCXXNamedModule = nullptr;
485
486 /// Help structures to decide whether two `const Module *` belongs
487 /// to the same conceptual module to avoid the expensive to string comparison
488 /// if possible.
489 ///
490 /// Not serialized intentionally.
491 llvm::StringMap<const Module *> PrimaryModuleNameMap;
492 llvm::DenseMap<const Module *, const Module *> SameModuleLookupSet;
493
494 static constexpr unsigned ConstantArrayTypesLog2InitSize = 8;
495 static constexpr unsigned GeneralTypesLog2InitSize = 9;
496 static constexpr unsigned FunctionProtoTypesLog2InitSize = 12;
497
498 /// A mapping from an ObjC class to its subclasses.
499 llvm::DenseMap<const ObjCInterfaceDecl *,
500 SmallVector<const ObjCInterfaceDecl *, 4>>
501 ObjCSubClasses;
502
503 ASTContext &this_() { return *this; }
504
505public:
506 /// A type synonym for the TemplateOrInstantiation mapping.
507 using TemplateOrSpecializationInfo =
508 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
509
510private:
511 friend class ASTDeclReader;
512 friend class ASTReader;
513 friend class ASTWriter;
514 template <class> friend class serialization::AbstractTypeReader;
515 friend class CXXRecordDecl;
516 friend class IncrementalParser;
517
518 /// A mapping to contain the template or declaration that
519 /// a variable declaration describes or was instantiated from,
520 /// respectively.
521 ///
522 /// For non-templates, this value will be NULL. For variable
523 /// declarations that describe a variable template, this will be a
524 /// pointer to a VarTemplateDecl. For static data members
525 /// of class template specializations, this will be the
526 /// MemberSpecializationInfo referring to the member variable that was
527 /// instantiated or specialized. Thus, the mapping will keep track of
528 /// the static data member templates from which static data members of
529 /// class template specializations were instantiated.
530 ///
531 /// Given the following example:
532 ///
533 /// \code
534 /// template<typename T>
535 /// struct X {
536 /// static T value;
537 /// };
538 ///
539 /// template<typename T>
540 /// T X<T>::value = T(17);
541 ///
542 /// int *x = &X<int>::value;
543 /// \endcode
544 ///
545 /// This mapping will contain an entry that maps from the VarDecl for
546 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
547 /// class template X) and will be marked TSK_ImplicitInstantiation.
548 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
549 TemplateOrInstantiation;
550
551 /// Keeps track of the declaration from which a using declaration was
552 /// created during instantiation.
553 ///
554 /// The source and target declarations are always a UsingDecl, an
555 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
556 ///
557 /// For example:
558 /// \code
559 /// template<typename T>
560 /// struct A {
561 /// void f();
562 /// };
563 ///
564 /// template<typename T>
565 /// struct B : A<T> {
566 /// using A<T>::f;
567 /// };
568 ///
569 /// template struct B<int>;
570 /// \endcode
571 ///
572 /// This mapping will contain an entry that maps from the UsingDecl in
573 /// B<int> to the UnresolvedUsingDecl in B<T>.
574 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
575
576 /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
577 /// from the instantiated using-enum to the templated decl from whence it
578 /// came.
579 /// Note that using-enum-declarations cannot be dependent and
580 /// thus will never be instantiated from an "unresolved"
581 /// version thereof (as with using-declarations), so each mapping is from
582 /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
583 llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
584 InstantiatedFromUsingEnumDecl;
585
586 /// Similarly maps instantiated UsingShadowDecls to their origin.
587 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
588 InstantiatedFromUsingShadowDecl;
589
590 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
591
592 /// Mapping that stores the methods overridden by a given C++
593 /// member function.
594 ///
595 /// Since most C++ member functions aren't virtual and therefore
596 /// don't override anything, we store the overridden functions in
597 /// this map on the side rather than within the CXXMethodDecl structure.
598 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
599 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
600
601 /// Mapping from each declaration context to its corresponding
602 /// mangling numbering context (used for constructs like lambdas which
603 /// need to be consistently numbered for the mangler).
604 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
605 MangleNumberingContexts;
606 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
607 ExtraMangleNumberingContexts;
608
609 /// Side-table of mangling numbers for declarations which rarely
610 /// need them (like static local vars).
611 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
612 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
613 /// Mapping the associated device lambda mangling number if present.
614 mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
615 DeviceLambdaManglingNumbers;
616
617 /// Mapping that stores parameterIndex values for ParmVarDecls when
618 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
619 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
620 ParameterIndexTable ParamIndices;
621
622public:
623 struct CXXRecordDeclRelocationInfo {
624 unsigned IsRelocatable;
625 unsigned IsReplaceable;
626 };
627 std::optional<CXXRecordDeclRelocationInfo>
628 getRelocationInfoForCXXRecord(const CXXRecordDecl *) const;
629 void setRelocationInfoForCXXRecord(const CXXRecordDecl *,
630 CXXRecordDeclRelocationInfo);
631
632private:
633 llvm::DenseMap<const CXXRecordDecl *, CXXRecordDeclRelocationInfo>
634 RelocatableClasses;
635
636 ImportDecl *FirstLocalImport = nullptr;
637 ImportDecl *LastLocalImport = nullptr;
638
639 TranslationUnitDecl *TUDecl = nullptr;
640 mutable ExternCContextDecl *ExternCContext = nullptr;
641
642#define BuiltinTemplate(BTName) \
643 mutable BuiltinTemplateDecl *Decl##BTName = nullptr;
644#include "clang/Basic/BuiltinTemplates.inc"
645
646 /// The associated SourceManager object.
647 SourceManager &SourceMgr;
648
649 /// The language options used to create the AST associated with
650 /// this ASTContext object.
651 LangOptions &LangOpts;
652
653 /// NoSanitizeList object that is used by sanitizers to decide which
654 /// entities should not be instrumented.
655 std::unique_ptr<NoSanitizeList> NoSanitizeL;
656
657 /// Function filtering mechanism to determine whether a given function
658 /// should be imbued with the XRay "always" or "never" attributes.
659 std::unique_ptr<XRayFunctionFilter> XRayFilter;
660
661 /// ProfileList object that is used by the profile instrumentation
662 /// to decide which entities should be instrumented.
663 std::unique_ptr<ProfileList> ProfList;
664
665 /// The allocator used to create AST objects.
666 ///
667 /// AST objects are never destructed; rather, all memory associated with the
668 /// AST objects will be released when the ASTContext itself is destroyed.
669 mutable llvm::BumpPtrAllocator BumpAlloc;
670
671 /// Allocator for partial diagnostics.
672 PartialDiagnostic::DiagStorageAllocator DiagAllocator;
673
674 /// The current C++ ABI.
675 std::unique_ptr<CXXABI> ABI;
676 CXXABI *createCXXABI(const TargetInfo &T);
677
678 /// Address space map mangling must be used with language specific
679 /// address spaces (e.g. OpenCL/CUDA)
680 bool AddrSpaceMapMangling;
681
682 /// For performance, track whether any function effects are in use.
683 mutable bool AnyFunctionEffects = false;
684
685 const TargetInfo *Target = nullptr;
686 const TargetInfo *AuxTarget = nullptr;
687 clang::PrintingPolicy PrintingPolicy;
688 std::unique_ptr<interp::Context> InterpContext;
689 std::unique_ptr<ParentMapContext> ParentMapCtx;
690
691 /// Keeps track of the deallocated DeclListNodes for future reuse.
692 DeclListNode *ListNodeFreeList = nullptr;
693
694public:
695 IdentifierTable &Idents;
696 SelectorTable &Selectors;
697 Builtin::Context &BuiltinInfo;
698 const TranslationUnitKind TUKind;
699 mutable DeclarationNameTable DeclarationNames;
700 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
701 ASTMutationListener *Listener = nullptr;
702
703 /// Returns the clang bytecode interpreter context.
704 interp::Context &getInterpContext();
705
706 struct CUDAConstantEvalContext {
707 /// Do not allow wrong-sided variables in constant expressions.
708 bool NoWrongSidedVars = false;
709 } CUDAConstantEvalCtx;
710 struct CUDAConstantEvalContextRAII {
711 ASTContext &Ctx;
712 CUDAConstantEvalContext SavedCtx;
713 CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars)
714 : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) {
715 Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars;
716 }
717 ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; }
718 };
719
720 /// Returns the dynamic AST node parent map context.
721 ParentMapContext &getParentMapContext();
722
723 // A traversal scope limits the parts of the AST visible to certain analyses.
724 // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
725 // getParents() will only observe reachable parent edges.
726 //
727 // The scope is defined by a set of "top-level" declarations which will be
728 // visible under the TranslationUnitDecl.
729 // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
730 //
731 // After setTraversalScope({foo, bar}), the exposed AST looks like:
732 // TranslationUnitDecl
733 // - foo
734 // - ...
735 // - bar
736 // - ...
737 // All other siblings of foo and bar are pruned from the tree.
738 // (However they are still accessible via TranslationUnitDecl->decls())
739 //
740 // Changing the scope clears the parent cache, which is expensive to rebuild.
741 ArrayRef<Decl *> getTraversalScope() const { return TraversalScope; }
742 void setTraversalScope(const std::vector<Decl *> &);
743
744 /// Forwards to get node parents from the ParentMapContext. New callers should
745 /// use ParentMapContext::getParents() directly.
746 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
747
748 const clang::PrintingPolicy &getPrintingPolicy() const {
749 return PrintingPolicy;
750 }
751
752 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
753 PrintingPolicy = Policy;
754 }
755
756 SourceManager& getSourceManager() { return SourceMgr; }
757 const SourceManager& getSourceManager() const { return SourceMgr; }
758
759 // Cleans up some of the data structures. This allows us to do cleanup
760 // normally done in the destructor earlier. Renders much of the ASTContext
761 // unusable, mostly the actual AST nodes, so should be called when we no
762 // longer need access to the AST.
763 void cleanup();
764
765 llvm::BumpPtrAllocator &getAllocator() const {
766 return BumpAlloc;
767 }
768
769 void *Allocate(size_t Size, unsigned Align = 8) const {
770 return BumpAlloc.Allocate(Size, Alignment: Align);
771 }
772 template <typename T> T *Allocate(size_t Num = 1) const {
773 return static_cast<T *>(Allocate(Size: Num * sizeof(T), Align: alignof(T)));
774 }
775 void Deallocate(void *Ptr) const {}
776
777 llvm::StringRef backupStr(llvm::StringRef S) const {
778 char *Buf = new (*this) char[S.size()];
779 std::copy(S.begin(), S.end(), Buf);
780 return llvm::StringRef(Buf, S.size());
781 }
782
783 /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
784 /// pool.
785 DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
786 if (DeclListNode *Alloc = ListNodeFreeList) {
787 ListNodeFreeList = dyn_cast_if_present<DeclListNode *>(Alloc->Rest);
788 Alloc->D = ND;
789 Alloc->Rest = nullptr;
790 return Alloc;
791 }
792 return new (*this) DeclListNode(ND);
793 }
794 /// Deallocates a \c DeclListNode by returning it to the \c ListNodeFreeList
795 /// pool.
796 void DeallocateDeclListNode(DeclListNode *N) {
797 N->Rest = ListNodeFreeList;
798 ListNodeFreeList = N;
799 }
800
801 /// Return the total amount of physical memory allocated for representing
802 /// AST nodes and type information.
803 size_t getASTAllocatedMemory() const {
804 return BumpAlloc.getTotalMemory();
805 }
806
807 /// Return the total memory used for various side tables.
808 size_t getSideTableAllocatedMemory() const;
809
810 PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
811 return DiagAllocator;
812 }
813
814 const TargetInfo &getTargetInfo() const { return *Target; }
815 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
816
817 const QualType GetHigherPrecisionFPType(QualType ElementType) const {
818 const auto *CurrentBT = cast<BuiltinType>(ElementType);
819 switch (CurrentBT->getKind()) {
820 case BuiltinType::Kind::Half:
821 case BuiltinType::Kind::Float16:
822 return FloatTy;
823 case BuiltinType::Kind::Float:
824 case BuiltinType::Kind::BFloat16:
825 return DoubleTy;
826 case BuiltinType::Kind::Double:
827 return LongDoubleTy;
828 default:
829 return ElementType;
830 }
831 return ElementType;
832 }
833
834 /// getIntTypeForBitwidth -
835 /// sets integer QualTy according to specified details:
836 /// bitwidth, signed/unsigned.
837 /// Returns empty type if there is no appropriate target types.
838 QualType getIntTypeForBitwidth(unsigned DestWidth,
839 unsigned Signed) const;
840
841 /// getRealTypeForBitwidth -
842 /// sets floating point QualTy according to specified bitwidth.
843 /// Returns empty type if there is no appropriate target types.
844 QualType getRealTypeForBitwidth(unsigned DestWidth,
845 FloatModeKind ExplicitType) const;
846
847 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
848
849 const LangOptions& getLangOpts() const { return LangOpts; }
850
851 // If this condition is false, typo correction must be performed eagerly
852 // rather than delayed in many places, as it makes use of dependent types.
853 // the condition is false for clang's C-only codepath, as it doesn't support
854 // dependent types yet.
855 bool isDependenceAllowed() const {
856 return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
857 }
858
859 const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
860
861 bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
862 const QualType &Ty) const;
863
864 const XRayFunctionFilter &getXRayFilter() const {
865 return *XRayFilter;
866 }
867
868 const ProfileList &getProfileList() const { return *ProfList; }
869
870 DiagnosticsEngine &getDiagnostics() const;
871
872 FullSourceLoc getFullLoc(SourceLocation Loc) const {
873 return FullSourceLoc(Loc,SourceMgr);
874 }
875
876 /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
877 /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
878 /// the default ABI set by the target.
879 TargetCXXABI::Kind getCXXABIKind() const;
880
881 /// All comments in this translation unit.
882 RawCommentList Comments;
883
884 /// True if comments are already loaded from ExternalASTSource.
885 mutable bool CommentsLoaded = false;
886
887 /// Mapping from declaration to directly attached comment.
888 ///
889 /// Raw comments are owned by Comments list. This mapping is populated
890 /// lazily.
891 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
892
893 /// Mapping from canonical declaration to the first redeclaration in chain
894 /// that has a comment attached.
895 ///
896 /// Raw comments are owned by Comments list. This mapping is populated
897 /// lazily.
898 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
899
900 /// Keeps track of redeclaration chains that don't have any comment attached.
901 /// Mapping from canonical declaration to redeclaration chain that has no
902 /// comments attached to any redeclaration. Specifically it's mapping to
903 /// the last redeclaration we've checked.
904 ///
905 /// Shall not contain declarations that have comments attached to any
906 /// redeclaration in their chain.
907 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
908
909 /// Mapping from declarations to parsed comments attached to any
910 /// redeclaration.
911 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
912
913 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
914 /// and removes the redeclaration chain from the set of commentless chains.
915 ///
916 /// Don't do anything if a comment has already been attached to \p OriginalD
917 /// or its redeclaration chain.
918 void cacheRawCommentForDecl(const Decl &OriginalD,
919 const RawComment &Comment) const;
920
921 /// \returns searches \p CommentsInFile for doc comment for \p D.
922 ///
923 /// \p RepresentativeLocForDecl is used as a location for searching doc
924 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
925 /// same file where \p RepresentativeLocForDecl is.
926 RawComment *getRawCommentForDeclNoCacheImpl(
927 const Decl *D, const SourceLocation RepresentativeLocForDecl,
928 const std::map<unsigned, RawComment *> &CommentsInFile) const;
929
930 /// Return the documentation comment attached to a given declaration,
931 /// without looking into cache.
932 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
933
934public:
935 void addComment(const RawComment &RC);
936
937 /// Return the documentation comment attached to a given declaration.
938 /// Returns nullptr if no comment is attached.
939 ///
940 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
941 /// had the comment, if the comment we found comes from a redeclaration.
942 const RawComment *
943 getRawCommentForAnyRedecl(const Decl *D,
944 const Decl **OriginalDecl = nullptr) const;
945
946 /// Searches existing comments for doc comments that should be attached to \p
947 /// Decls. If any doc comment is found, it is parsed.
948 ///
949 /// Requirement: All \p Decls are in the same file.
950 ///
951 /// If the last comment in the file is already attached we assume
952 /// there are not comments left to be attached to \p Decls.
953 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
954 const Preprocessor *PP);
955
956 /// Return parsed documentation comment attached to a given declaration.
957 /// Returns nullptr if no comment is attached.
958 ///
959 /// \param PP the Preprocessor used with this TU. Could be nullptr if
960 /// preprocessor is not available.
961 comments::FullComment *getCommentForDecl(const Decl *D,
962 const Preprocessor *PP) const;
963
964 /// Return parsed documentation comment attached to a given declaration.
965 /// Returns nullptr if no comment is attached. Does not look at any
966 /// redeclarations of the declaration.
967 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
968
969 comments::FullComment *cloneFullComment(comments::FullComment *FC,
970 const Decl *D) const;
971
972private:
973 mutable comments::CommandTraits CommentCommandTraits;
974
975 /// Iterator that visits import declarations.
976 class import_iterator {
977 ImportDecl *Import = nullptr;
978
979 public:
980 using value_type = ImportDecl *;
981 using reference = ImportDecl *;
982 using pointer = ImportDecl *;
983 using difference_type = int;
984 using iterator_category = std::forward_iterator_tag;
985
986 import_iterator() = default;
987 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
988
989 reference operator*() const { return Import; }
990 pointer operator->() const { return Import; }
991
992 import_iterator &operator++() {
993 Import = ASTContext::getNextLocalImport(Import);
994 return *this;
995 }
996
997 import_iterator operator++(int) {
998 import_iterator Other(*this);
999 ++(*this);
1000 return Other;
1001 }
1002
1003 friend bool operator==(import_iterator X, import_iterator Y) {
1004 return X.Import == Y.Import;
1005 }
1006
1007 friend bool operator!=(import_iterator X, import_iterator Y) {
1008 return X.Import != Y.Import;
1009 }
1010 };
1011
1012public:
1013 comments::CommandTraits &getCommentCommandTraits() const {
1014 return CommentCommandTraits;
1015 }
1016
1017 /// Retrieve the attributes for the given declaration.
1018 AttrVec& getDeclAttrs(const Decl *D);
1019
1020 /// Erase the attributes corresponding to the given declaration.
1021 void eraseDeclAttrs(const Decl *D);
1022
1023 /// If this variable is an instantiated static data member of a
1024 /// class template specialization, returns the templated static data member
1025 /// from which it was instantiated.
1026 // FIXME: Remove ?
1027 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
1028 const VarDecl *Var);
1029
1030 /// Note that the static data member \p Inst is an instantiation of
1031 /// the static data member template \p Tmpl of a class template.
1032 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1033 TemplateSpecializationKind TSK,
1034 SourceLocation PointOfInstantiation = SourceLocation());
1035
1036 TemplateOrSpecializationInfo
1037 getTemplateOrSpecializationInfo(const VarDecl *Var);
1038
1039 void setTemplateOrSpecializationInfo(VarDecl *Inst,
1040 TemplateOrSpecializationInfo TSI);
1041
1042 /// If the given using decl \p Inst is an instantiation of
1043 /// another (possibly unresolved) using decl, return it.
1044 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
1045
1046 /// Remember that the using decl \p Inst is an instantiation
1047 /// of the using decl \p Pattern of a class template.
1048 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
1049
1050 /// If the given using-enum decl \p Inst is an instantiation of
1051 /// another using-enum decl, return it.
1052 UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst);
1053
1054 /// Remember that the using enum decl \p Inst is an instantiation
1055 /// of the using enum decl \p Pattern of a class template.
1056 void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1057 UsingEnumDecl *Pattern);
1058
1059 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
1060 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1061 UsingShadowDecl *Pattern);
1062
1063 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const;
1064
1065 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
1066
1067 // Access to the set of methods overridden by the given C++ method.
1068 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
1069 overridden_cxx_method_iterator
1070 overridden_methods_begin(const CXXMethodDecl *Method) const;
1071
1072 overridden_cxx_method_iterator
1073 overridden_methods_end(const CXXMethodDecl *Method) const;
1074
1075 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
1076
1077 using overridden_method_range =
1078 llvm::iterator_range<overridden_cxx_method_iterator>;
1079
1080 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
1081
1082 /// Note that the given C++ \p Method overrides the given \p
1083 /// Overridden method.
1084 void addOverriddenMethod(const CXXMethodDecl *Method,
1085 const CXXMethodDecl *Overridden);
1086
1087 /// Return C++ or ObjC overridden methods for the given \p Method.
1088 ///
1089 /// An ObjC method is considered to override any method in the class's
1090 /// base classes, its protocols, or its categories' protocols, that has
1091 /// the same selector and is of the same kind (class or instance).
1092 /// A method in an implementation is not considered as overriding the same
1093 /// method in the interface or its categories.
1094 void getOverriddenMethods(
1095 const NamedDecl *Method,
1096 SmallVectorImpl<const NamedDecl *> &Overridden) const;
1097
1098 /// Notify the AST context that a new import declaration has been
1099 /// parsed or implicitly created within this translation unit.
1100 void addedLocalImportDecl(ImportDecl *Import);
1101
1102 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
1103 return Import->getNextLocalImport();
1104 }
1105
1106 using import_range = llvm::iterator_range<import_iterator>;
1107
1108 import_range local_imports() const {
1109 return import_range(import_iterator(FirstLocalImport), import_iterator());
1110 }
1111
1112 Decl *getPrimaryMergedDecl(Decl *D) {
1113 Decl *Result = MergedDecls.lookup(D);
1114 return Result ? Result : D;
1115 }
1116 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
1117 MergedDecls[D] = Primary;
1118 }
1119
1120 /// Note that the definition \p ND has been merged into module \p M,
1121 /// and should be visible whenever \p M is visible.
1122 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1123 bool NotifyListeners = true);
1124
1125 /// Clean up the merged definition list. Call this if you might have
1126 /// added duplicates into the list.
1127 void deduplicateMergedDefinitionsFor(NamedDecl *ND);
1128
1129 /// Get the additional modules in which the definition \p Def has
1130 /// been merged.
1131 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
1132
1133 /// Add a declaration to the list of declarations that are initialized
1134 /// for a module. This will typically be a global variable (with internal
1135 /// linkage) that runs module initializers, such as the iostream initializer,
1136 /// or an ImportDecl nominating another module that has initializers.
1137 void addModuleInitializer(Module *M, Decl *Init);
1138
1139 void addLazyModuleInitializers(Module *M, ArrayRef<GlobalDeclID> IDs);
1140
1141 /// Get the initializations to perform when importing a module, if any.
1142 ArrayRef<Decl*> getModuleInitializers(Module *M);
1143
1144 /// Set the (C++20) module we are building.
1145 void setCurrentNamedModule(Module *M);
1146
1147 /// Get module under construction, nullptr if this is not a C++20 module.
1148 Module *getCurrentNamedModule() const { return CurrentCXXNamedModule; }
1149
1150 /// If the two module \p M1 and \p M2 are in the same module.
1151 ///
1152 /// FIXME: The signature may be confusing since `clang::Module` means to
1153 /// a module fragment or a module unit but not a C++20 module.
1154 bool isInSameModule(const Module *M1, const Module *M2);
1155
1156 TranslationUnitDecl *getTranslationUnitDecl() const {
1157 return TUDecl->getMostRecentDecl();
1158 }
1159 void addTranslationUnitDecl() {
1160 assert(!TUDecl || TUKind == TU_Incremental);
1161 TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(C&: *this);
1162 if (TraversalScope.empty() || TraversalScope.back() == TUDecl)
1163 TraversalScope = {NewTUDecl};
1164 if (TUDecl)
1165 NewTUDecl->setPreviousDecl(TUDecl);
1166 TUDecl = NewTUDecl;
1167 }
1168
1169 ExternCContextDecl *getExternCContextDecl() const;
1170
1171#define BuiltinTemplate(BTName) BuiltinTemplateDecl *get##BTName##Decl() const;
1172#include "clang/Basic/BuiltinTemplates.inc"
1173
1174 // Builtin Types.
1175 CanQualType VoidTy;
1176 CanQualType BoolTy;
1177 CanQualType CharTy;
1178 CanQualType WCharTy; // [C++ 3.9.1p5].
1179 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1180 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1181 CanQualType Char8Ty; // [C++20 proposal]
1182 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1183 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1184 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1185 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1186 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1187 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
1188 CanQualType ShortAccumTy, AccumTy,
1189 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1190 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1191 CanQualType ShortFractTy, FractTy, LongFractTy;
1192 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1193 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1194 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1195 SatUnsignedLongAccumTy;
1196 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1197 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1198 SatUnsignedLongFractTy;
1199 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1200 CanQualType BFloat16Ty;
1201 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1202 CanQualType VoidPtrTy, NullPtrTy;
1203 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
1204 UnknownAnyTy;
1205 CanQualType BuiltinFnTy;
1206 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1207 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1208 CanQualType ObjCBuiltinBoolTy;
1209#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1210 CanQualType SingletonId;
1211#include "clang/Basic/OpenCLImageTypes.def"
1212 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1213 CanQualType OCLQueueTy, OCLReserveIDTy;
1214 CanQualType IncompleteMatrixIdxTy;
1215 CanQualType ArraySectionTy;
1216 CanQualType OMPArrayShapingTy, OMPIteratorTy;
1217#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1218 CanQualType Id##Ty;
1219#include "clang/Basic/OpenCLExtensionTypes.def"
1220#define SVE_TYPE(Name, Id, SingletonId) \
1221 CanQualType SingletonId;
1222#include "clang/Basic/AArch64ACLETypes.def"
1223#define PPC_VECTOR_TYPE(Name, Id, Size) \
1224 CanQualType Id##Ty;
1225#include "clang/Basic/PPCTypes.def"
1226#define RVV_TYPE(Name, Id, SingletonId) \
1227 CanQualType SingletonId;
1228#include "clang/Basic/RISCVVTypes.def"
1229#define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
1230#include "clang/Basic/WebAssemblyReferenceTypes.def"
1231#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1232 CanQualType SingletonId;
1233#include "clang/Basic/AMDGPUTypes.def"
1234#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
1235#include "clang/Basic/HLSLIntangibleTypes.def"
1236
1237 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1238 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1239 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1240
1241 // Decl used to help define __builtin_va_list for some targets.
1242 // The decl is built when constructing 'BuiltinVaListDecl'.
1243 mutable Decl *VaListTagDecl = nullptr;
1244
1245 // Implicitly-declared type 'struct _GUID'.
1246 mutable TagDecl *MSGuidTagDecl = nullptr;
1247
1248 /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
1249 /// This does not include extern shared variables used by device host
1250 /// functions as addresses of shared variables are per warp, therefore
1251 /// cannot be accessed by host code.
1252 llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost;
1253
1254 /// Keep track of CUDA/HIP external kernels or device variables ODR-used by
1255 /// host code. SetVector is used to maintain the order.
1256 llvm::SetVector<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost;
1257
1258 /// Keep track of CUDA/HIP implicit host device functions used on device side
1259 /// in device compilation.
1260 llvm::DenseSet<const FunctionDecl *> CUDAImplicitHostDeviceFunUsedByDevice;
1261
1262 /// Map of SYCL kernels indexed by the unique type used to name the kernel.
1263 /// Entries are not serialized but are recreated on deserialization of a
1264 /// sycl_kernel_entry_point attributed function declaration.
1265 llvm::DenseMap<CanQualType, SYCLKernelInfo> SYCLKernels;
1266
1267 /// For capturing lambdas with an explicit object parameter whose type is
1268 /// derived from the lambda type, we need to perform derived-to-base
1269 /// conversion so we can access the captures; the cast paths for that
1270 /// are stored here.
1271 llvm::DenseMap<const CXXMethodDecl *, CXXCastPath> LambdaCastPaths;
1272
1273 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1274 SelectorTable &sels, Builtin::Context &builtins,
1275 TranslationUnitKind TUKind);
1276 ASTContext(const ASTContext &) = delete;
1277 ASTContext &operator=(const ASTContext &) = delete;
1278 ~ASTContext();
1279
1280 /// Attach an external AST source to the AST context.
1281 ///
1282 /// The external AST source provides the ability to load parts of
1283 /// the abstract syntax tree as needed from some external storage,
1284 /// e.g., a precompiled header.
1285 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1286
1287 /// Retrieve a pointer to the external AST source associated
1288 /// with this AST context, if any.
1289 ExternalASTSource *getExternalSource() const {
1290 return ExternalSource.get();
1291 }
1292
1293 /// Attach an AST mutation listener to the AST context.
1294 ///
1295 /// The AST mutation listener provides the ability to track modifications to
1296 /// the abstract syntax tree entities committed after they were initially
1297 /// created.
1298 void setASTMutationListener(ASTMutationListener *Listener) {
1299 this->Listener = Listener;
1300 }
1301
1302 /// Retrieve a pointer to the AST mutation listener associated
1303 /// with this AST context, if any.
1304 ASTMutationListener *getASTMutationListener() const { return Listener; }
1305
1306 void PrintStats() const;
1307 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1308
1309 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1310 const IdentifierInfo *II) const;
1311
1312 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1313 /// declaration.
1314 RecordDecl *buildImplicitRecord(
1315 StringRef Name,
1316 RecordDecl::TagKind TK = RecordDecl::TagKind::Struct) const;
1317
1318 /// Create a new implicit TU-level typedef declaration.
1319 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1320
1321 /// Retrieve the declaration for the 128-bit signed integer type.
1322 TypedefDecl *getInt128Decl() const;
1323
1324 /// Retrieve the declaration for the 128-bit unsigned integer type.
1325 TypedefDecl *getUInt128Decl() const;
1326
1327 //===--------------------------------------------------------------------===//
1328 // Type Constructors
1329 //===--------------------------------------------------------------------===//
1330
1331private:
1332 /// Return a type with extended qualifiers.
1333 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1334
1335 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1336
1337 QualType getPipeType(QualType T, bool ReadOnly) const;
1338
1339public:
1340 /// Return the uniqued reference to the type for an address space
1341 /// qualified type with the specified type and address space.
1342 ///
1343 /// The resulting type has a union of the qualifiers from T and the address
1344 /// space. If T already has an address space specifier, it is silently
1345 /// replaced.
1346 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1347
1348 /// Remove any existing address space on the type and returns the type
1349 /// with qualifiers intact (or that's the idea anyway)
1350 ///
1351 /// The return type should be T with all prior qualifiers minus the address
1352 /// space.
1353 QualType removeAddrSpaceQualType(QualType T) const;
1354
1355 /// Return the "other" discriminator used for the pointer auth schema used for
1356 /// vtable pointers in instances of the requested type.
1357 uint16_t
1358 getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD);
1359
1360 /// Return the "other" type-specific discriminator for the given type.
1361 uint16_t getPointerAuthTypeDiscriminator(QualType T);
1362
1363 /// Apply Objective-C protocol qualifiers to the given type.
1364 /// \param allowOnPointerType specifies if we can apply protocol
1365 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1366 /// constructing the canonical type of a Objective-C type parameter.
1367 QualType applyObjCProtocolQualifiers(QualType type,
1368 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1369 bool allowOnPointerType = false) const;
1370
1371 /// Return the uniqued reference to the type for an Objective-C
1372 /// gc-qualified type.
1373 ///
1374 /// The resulting type has a union of the qualifiers from T and the gc
1375 /// attribute.
1376 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1377
1378 /// Remove the existing address space on the type if it is a pointer size
1379 /// address space and return the type with qualifiers intact.
1380 QualType removePtrSizeAddrSpace(QualType T) const;
1381
1382 /// Return the uniqued reference to the type for a \c restrict
1383 /// qualified type.
1384 ///
1385 /// The resulting type has a union of the qualifiers from \p T and
1386 /// \c restrict.
1387 QualType getRestrictType(QualType T) const {
1388 return T.withFastQualifiers(TQs: Qualifiers::Restrict);
1389 }
1390
1391 /// Return the uniqued reference to the type for a \c volatile
1392 /// qualified type.
1393 ///
1394 /// The resulting type has a union of the qualifiers from \p T and
1395 /// \c volatile.
1396 QualType getVolatileType(QualType T) const {
1397 return T.withFastQualifiers(TQs: Qualifiers::Volatile);
1398 }
1399
1400 /// Return the uniqued reference to the type for a \c const
1401 /// qualified type.
1402 ///
1403 /// The resulting type has a union of the qualifiers from \p T and \c const.
1404 ///
1405 /// It can be reasonably expected that this will always be equivalent to
1406 /// calling T.withConst().
1407 QualType getConstType(QualType T) const { return T.withConst(); }
1408
1409 /// Rebuild a type, preserving any existing type sugar. For function types,
1410 /// you probably want to just use \c adjustFunctionResultType and friends
1411 /// instead.
1412 QualType adjustType(QualType OldType,
1413 llvm::function_ref<QualType(QualType)> Adjust) const;
1414
1415 /// Change the ExtInfo on a function type.
1416 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1417 FunctionType::ExtInfo EInfo);
1418
1419 /// Change the result type of a function type, preserving sugar such as
1420 /// attributed types.
1421 QualType adjustFunctionResultType(QualType FunctionType,
1422 QualType NewResultType);
1423
1424 /// Adjust the given function result type.
1425 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1426
1427 /// Change the result type of a function type once it is deduced.
1428 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1429
1430 /// Get a function type and produce the equivalent function type with the
1431 /// specified exception specification. Type sugar that can be present on a
1432 /// declaration of a function with an exception specification is permitted
1433 /// and preserved. Other type sugar (for instance, typedefs) is not.
1434 QualType getFunctionTypeWithExceptionSpec(
1435 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const;
1436
1437 /// Determine whether two function types are the same, ignoring
1438 /// exception specifications in cases where they're part of the type.
1439 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const;
1440
1441 /// Change the exception specification on a function once it is
1442 /// delay-parsed, instantiated, or computed.
1443 void adjustExceptionSpec(FunctionDecl *FD,
1444 const FunctionProtoType::ExceptionSpecInfo &ESI,
1445 bool AsWritten = false);
1446
1447 /// Get a function type and produce the equivalent function type where
1448 /// pointer size address spaces in the return type and parameter types are
1449 /// replaced with the default address space.
1450 QualType getFunctionTypeWithoutPtrSizes(QualType T);
1451
1452 /// Determine whether two function types are the same, ignoring pointer sizes
1453 /// in the return type and parameter types.
1454 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1455
1456 /// Get or construct a function type that is equivalent to the input type
1457 /// except that the parameter ABI annotations are stripped.
1458 QualType getFunctionTypeWithoutParamABIs(QualType T) const;
1459
1460 /// Determine if two function types are the same, ignoring parameter ABI
1461 /// annotations.
1462 bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const;
1463
1464 /// Return the uniqued reference to the type for a complex
1465 /// number with the specified element type.
1466 QualType getComplexType(QualType T) const;
1467 CanQualType getComplexType(CanQualType T) const {
1468 return CanQualType::CreateUnsafe(Other: getComplexType(T: (QualType) T));
1469 }
1470
1471 /// Return the uniqued reference to the type for a pointer to
1472 /// the specified type.
1473 QualType getPointerType(QualType T) const;
1474 CanQualType getPointerType(CanQualType T) const {
1475 return CanQualType::CreateUnsafe(Other: getPointerType(T: (QualType) T));
1476 }
1477
1478 QualType
1479 getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes,
1480 bool OrNull,
1481 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const;
1482
1483 /// Return the uniqued reference to a type adjusted from the original
1484 /// type to a new type.
1485 QualType getAdjustedType(QualType Orig, QualType New) const;
1486 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1487 return CanQualType::CreateUnsafe(
1488 Other: getAdjustedType(Orig: (QualType)Orig, New: (QualType)New));
1489 }
1490
1491 /// Return the uniqued reference to the decayed version of the given
1492 /// type. Can only be called on array and function types which decay to
1493 /// pointer types.
1494 QualType getDecayedType(QualType T) const;
1495 CanQualType getDecayedType(CanQualType T) const {
1496 return CanQualType::CreateUnsafe(Other: getDecayedType(T: (QualType) T));
1497 }
1498 /// Return the uniqued reference to a specified decay from the original
1499 /// type to the decayed type.
1500 QualType getDecayedType(QualType Orig, QualType Decayed) const;
1501
1502 /// Return the uniqued reference to a specified array parameter type from the
1503 /// original array type.
1504 QualType getArrayParameterType(QualType Ty) const;
1505
1506 /// Return the uniqued reference to the atomic type for the specified
1507 /// type.
1508 QualType getAtomicType(QualType T) const;
1509
1510 /// Return the uniqued reference to the type for a block of the
1511 /// specified type.
1512 QualType getBlockPointerType(QualType T) const;
1513
1514 /// Gets the struct used to keep track of the descriptor for pointer to
1515 /// blocks.
1516 QualType getBlockDescriptorType() const;
1517
1518 /// Return a read_only pipe type for the specified type.
1519 QualType getReadPipeType(QualType T) const;
1520
1521 /// Return a write_only pipe type for the specified type.
1522 QualType getWritePipeType(QualType T) const;
1523
1524 /// Return a bit-precise integer type with the specified signedness and bit
1525 /// count.
1526 QualType getBitIntType(bool Unsigned, unsigned NumBits) const;
1527
1528 /// Return a dependent bit-precise integer type with the specified signedness
1529 /// and bit count.
1530 QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const;
1531
1532 /// Gets the struct used to keep track of the extended descriptor for
1533 /// pointer to blocks.
1534 QualType getBlockDescriptorExtendedType() const;
1535
1536 /// Map an AST Type to an OpenCLTypeKind enum value.
1537 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1538
1539 /// Get address space for OpenCL type.
1540 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1541
1542 /// Returns default address space based on OpenCL version and enabled features
1543 inline LangAS getDefaultOpenCLPointeeAddrSpace() {
1544 return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic
1545 : LangAS::opencl_private;
1546 }
1547
1548 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1549 cudaConfigureCallDecl = FD;
1550 }
1551
1552 FunctionDecl *getcudaConfigureCallDecl() {
1553 return cudaConfigureCallDecl;
1554 }
1555
1556 /// Returns true iff we need copy/dispose helpers for the given type.
1557 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1558
1559 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1560 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1561 /// byref variable has extended lifetime.
1562 bool getByrefLifetime(QualType Ty,
1563 Qualifiers::ObjCLifetime &Lifetime,
1564 bool &HasByrefExtendedLayout) const;
1565
1566 /// Return the uniqued reference to the type for an lvalue reference
1567 /// to the specified type.
1568 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1569 const;
1570
1571 /// Return the uniqued reference to the type for an rvalue reference
1572 /// to the specified type.
1573 QualType getRValueReferenceType(QualType T) const;
1574
1575 /// Return the uniqued reference to the type for a member pointer to
1576 /// the specified type in the specified nested name.
1577 QualType getMemberPointerType(QualType T, NestedNameSpecifier *Qualifier,
1578 const CXXRecordDecl *Cls) const;
1579
1580 /// Return a non-unique reference to the type for a variable array of
1581 /// the specified element type.
1582 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1583 ArraySizeModifier ASM,
1584 unsigned IndexTypeQuals) const;
1585
1586 /// Return a non-unique reference to the type for a dependently-sized
1587 /// array of the specified element type.
1588 ///
1589 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1590 /// point.
1591 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1592 ArraySizeModifier ASM,
1593 unsigned IndexTypeQuals) const;
1594
1595 /// Return a unique reference to the type for an incomplete array of
1596 /// the specified element type.
1597 QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM,
1598 unsigned IndexTypeQuals) const;
1599
1600 /// Return the unique reference to the type for a constant array of
1601 /// the specified element type.
1602 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1603 const Expr *SizeExpr, ArraySizeModifier ASM,
1604 unsigned IndexTypeQuals) const;
1605
1606 /// Return a type for a constant array for a string literal of the
1607 /// specified element type and length.
1608 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1609
1610 /// Returns a vla type where known sizes are replaced with [*].
1611 QualType getVariableArrayDecayedType(QualType Ty) const;
1612
1613 // Convenience struct to return information about a builtin vector type.
1614 struct BuiltinVectorTypeInfo {
1615 QualType ElementType;
1616 llvm::ElementCount EC;
1617 unsigned NumVectors;
1618 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1619 unsigned NumVectors)
1620 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1621 };
1622
1623 /// Returns the element type, element count and number of vectors
1624 /// (in case of tuple) for a builtin vector type.
1625 BuiltinVectorTypeInfo
1626 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1627
1628 /// Return the unique reference to a scalable vector type of the specified
1629 /// element type and scalable number of elements.
1630 /// For RISC-V, number of fields is also provided when it fetching for
1631 /// tuple type.
1632 ///
1633 /// \pre \p EltTy must be a built-in type.
1634 QualType getScalableVectorType(QualType EltTy, unsigned NumElts,
1635 unsigned NumFields = 1) const;
1636
1637 /// Return a WebAssembly externref type.
1638 QualType getWebAssemblyExternrefType() const;
1639
1640 /// Return the unique reference to a vector type of the specified
1641 /// element type and size.
1642 ///
1643 /// \pre \p VectorType must be a built-in type.
1644 QualType getVectorType(QualType VectorType, unsigned NumElts,
1645 VectorKind VecKind) const;
1646 /// Return the unique reference to the type for a dependently sized vector of
1647 /// the specified element type.
1648 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1649 SourceLocation AttrLoc,
1650 VectorKind VecKind) const;
1651
1652 /// Return the unique reference to an extended vector type
1653 /// of the specified element type and size.
1654 ///
1655 /// \pre \p VectorType must be a built-in type.
1656 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1657
1658 /// \pre Return a non-unique reference to the type for a dependently-sized
1659 /// vector of the specified element type.
1660 ///
1661 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1662 /// point.
1663 QualType getDependentSizedExtVectorType(QualType VectorType,
1664 Expr *SizeExpr,
1665 SourceLocation AttrLoc) const;
1666
1667 /// Return the unique reference to the matrix type of the specified element
1668 /// type and size
1669 ///
1670 /// \pre \p ElementType must be a valid matrix element type (see
1671 /// MatrixType::isValidElementType).
1672 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1673 unsigned NumColumns) const;
1674
1675 /// Return the unique reference to the matrix type of the specified element
1676 /// type and size
1677 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1678 Expr *ColumnExpr,
1679 SourceLocation AttrLoc) const;
1680
1681 QualType getDependentAddressSpaceType(QualType PointeeType,
1682 Expr *AddrSpaceExpr,
1683 SourceLocation AttrLoc) const;
1684
1685 /// Return a K&R style C function type like 'int()'.
1686 QualType getFunctionNoProtoType(QualType ResultTy,
1687 const FunctionType::ExtInfo &Info) const;
1688
1689 QualType getFunctionNoProtoType(QualType ResultTy) const {
1690 return getFunctionNoProtoType(ResultTy, Info: FunctionType::ExtInfo());
1691 }
1692
1693 /// Return a normal function type with a typed argument list.
1694 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1695 const FunctionProtoType::ExtProtoInfo &EPI) const {
1696 return getFunctionTypeInternal(ResultTy, Args: Args, EPI, OnlyWantCanonical: false);
1697 }
1698
1699 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1700
1701private:
1702 /// Return a normal function type with a typed argument list.
1703 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1704 const FunctionProtoType::ExtProtoInfo &EPI,
1705 bool OnlyWantCanonical) const;
1706 QualType
1707 getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword,
1708 bool IsDependent, bool IsPack = false,
1709 ConceptDecl *TypeConstraintConcept = nullptr,
1710 ArrayRef<TemplateArgument> TypeConstraintArgs = {},
1711 bool IsCanon = false) const;
1712
1713public:
1714 /// Return the unique reference to the type for the specified type
1715 /// declaration.
1716 QualType getTypeDeclType(const TypeDecl *Decl,
1717 const TypeDecl *PrevDecl = nullptr) const {
1718 assert(Decl && "Passed null for Decl param");
1719 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1720
1721 if (PrevDecl) {
1722 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
1723 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1724 return QualType(PrevDecl->TypeForDecl, 0);
1725 }
1726
1727 return getTypeDeclTypeSlow(Decl);
1728 }
1729
1730 QualType getUsingType(const UsingShadowDecl *Found,
1731 QualType Underlying) const;
1732
1733 /// Return the unique reference to the type for the specified
1734 /// typedef-name decl.
1735 QualType getTypedefType(const TypedefNameDecl *Decl,
1736 QualType Underlying = QualType()) const;
1737
1738 QualType getRecordType(const RecordDecl *Decl) const;
1739
1740 QualType getEnumType(const EnumDecl *Decl) const;
1741
1742 /// Compute BestType and BestPromotionType for an enum based on the highest
1743 /// number of negative and positive bits of its elements.
1744 /// Returns true if enum width is too large.
1745 bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
1746 unsigned NumPositiveBits, QualType &BestType,
1747 QualType &BestPromotionType);
1748
1749 /// Determine whether the given integral value is representable within
1750 /// the given type T.
1751 bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T);
1752
1753 /// Compute NumNegativeBits and NumPositiveBits for an enum based on
1754 /// the constant values of its enumerators.
1755 template <typename RangeT>
1756 bool computeEnumBits(RangeT EnumConstants, unsigned &NumNegativeBits,
1757 unsigned &NumPositiveBits) {
1758 NumNegativeBits = 0;
1759 NumPositiveBits = 0;
1760 bool MembersRepresentableByInt = true;
1761 for (auto *Elem : EnumConstants) {
1762 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elem);
1763 if (!ECD)
1764 continue; // Already issued a diagnostic.
1765
1766 llvm::APSInt InitVal = ECD->getInitVal();
1767 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
1768 // If the enumerator is zero that should still be counted as a positive
1769 // bit since we need a bit to store the value zero.
1770 unsigned ActiveBits = InitVal.getActiveBits();
1771 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
1772 } else {
1773 NumNegativeBits =
1774 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
1775 }
1776
1777 MembersRepresentableByInt &= isRepresentableIntegerValue(InitVal, IntTy);
1778 }
1779
1780 // If we have an empty set of enumerators we still need one bit.
1781 // From [dcl.enum]p8
1782 // If the enumerator-list is empty, the values of the enumeration are as if
1783 // the enumeration had a single enumerator with value 0
1784 if (!NumPositiveBits && !NumNegativeBits)
1785 NumPositiveBits = 1;
1786
1787 return MembersRepresentableByInt;
1788 }
1789
1790 QualType
1791 getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const;
1792
1793 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1794
1795 QualType getAttributedType(attr::Kind attrKind, QualType modifiedType,
1796 QualType equivalentType,
1797 const Attr *attr = nullptr) const;
1798
1799 QualType getAttributedType(const Attr *attr, QualType modifiedType,
1800 QualType equivalentType) const;
1801
1802 QualType getAttributedType(NullabilityKind nullability, QualType modifiedType,
1803 QualType equivalentType);
1804
1805 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
1806 QualType Wrapped) const;
1807
1808 QualType getHLSLAttributedResourceType(
1809 QualType Wrapped, QualType Contained,
1810 const HLSLAttributedResourceType::Attributes &Attrs);
1811
1812 QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
1813 uint32_t Alignment,
1814 ArrayRef<SpirvOperand> Operands);
1815
1816 QualType getSubstTemplateTypeParmType(QualType Replacement,
1817 Decl *AssociatedDecl, unsigned Index,
1818 UnsignedOrNone PackIndex,
1819 bool Final) const;
1820 QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
1821 unsigned Index, bool Final,
1822 const TemplateArgument &ArgPack);
1823
1824 QualType
1825 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1826 bool ParameterPack,
1827 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1828
1829 QualType getCanonicalTemplateSpecializationType(
1830 TemplateName T, ArrayRef<TemplateArgument> CanonicalArgs) const;
1831
1832 QualType
1833 getTemplateSpecializationType(TemplateName T,
1834 ArrayRef<TemplateArgument> SpecifiedArgs,
1835 ArrayRef<TemplateArgument> CanonicalArgs,
1836 QualType Underlying = QualType()) const;
1837
1838 QualType
1839 getTemplateSpecializationType(TemplateName T,
1840 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
1841 ArrayRef<TemplateArgument> CanonicalArgs,
1842 QualType Canon = QualType()) const;
1843
1844 TypeSourceInfo *getTemplateSpecializationTypeInfo(
1845 TemplateName T, SourceLocation TLoc,
1846 const TemplateArgumentListInfo &SpecifiedArgs,
1847 ArrayRef<TemplateArgument> CanonicalArgs,
1848 QualType Canon = QualType()) const;
1849
1850 QualType getParenType(QualType NamedType) const;
1851
1852 QualType getMacroQualifiedType(QualType UnderlyingTy,
1853 const IdentifierInfo *MacroII) const;
1854
1855 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1856 NestedNameSpecifier *NNS, QualType NamedType,
1857 TagDecl *OwnedTagDecl = nullptr) const;
1858 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1859 NestedNameSpecifier *NNS,
1860 const IdentifierInfo *Name) const;
1861
1862 QualType getDependentTemplateSpecializationType(
1863 ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name,
1864 ArrayRef<TemplateArgumentLoc> Args) const;
1865 QualType getDependentTemplateSpecializationType(
1866 ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name,
1867 ArrayRef<TemplateArgument> Args, bool IsCanonical = false) const;
1868
1869 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const;
1870
1871 /// Form a pack expansion type with the given pattern.
1872 /// \param NumExpansions The number of expansions for the pack, if known.
1873 /// \param ExpectPackInType If \c false, we should not expect \p Pattern to
1874 /// contain an unexpanded pack. This only makes sense if the pack
1875 /// expansion is used in a context where the arity is inferred from
1876 /// elsewhere, such as if the pattern contains a placeholder type or
1877 /// if this is the canonical type of another pack expansion type.
1878 QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions,
1879 bool ExpectPackInType = true) const;
1880
1881 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1882 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1883
1884 /// Legacy interface: cannot provide type arguments or __kindof.
1885 QualType getObjCObjectType(QualType Base,
1886 ObjCProtocolDecl * const *Protocols,
1887 unsigned NumProtocols) const;
1888
1889 QualType getObjCObjectType(QualType Base,
1890 ArrayRef<QualType> typeArgs,
1891 ArrayRef<ObjCProtocolDecl *> protocols,
1892 bool isKindOf) const;
1893
1894 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1895 ArrayRef<ObjCProtocolDecl *> protocols) const;
1896 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1897 ObjCTypeParamDecl *New) const;
1898
1899 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1900
1901 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1902 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1903 /// of protocols.
1904 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1905 ObjCInterfaceDecl *IDecl);
1906
1907 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1908 QualType getObjCObjectPointerType(QualType OIT) const;
1909
1910 /// C23 feature and GCC extension.
1911 QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const;
1912 QualType getTypeOfType(QualType QT, TypeOfKind Kind) const;
1913
1914 QualType getReferenceQualifiedType(const Expr *e) const;
1915
1916 /// C++11 decltype.
1917 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1918
1919 QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr,
1920 bool FullySubstituted = false,
1921 ArrayRef<QualType> Expansions = {},
1922 UnsignedOrNone Index = std::nullopt) const;
1923
1924 /// Unary type transforms
1925 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1926 UnaryTransformType::UTTKind UKind) const;
1927
1928 /// C++11 deduced auto type.
1929 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1930 bool IsDependent, bool IsPack = false,
1931 ConceptDecl *TypeConstraintConcept = nullptr,
1932 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1933
1934 /// C++11 deduction pattern for 'auto' type.
1935 QualType getAutoDeductType() const;
1936
1937 /// C++11 deduction pattern for 'auto &&' type.
1938 QualType getAutoRRefDeductType() const;
1939
1940 /// Remove any type constraints from a template parameter type, for
1941 /// equivalence comparison of template parameters.
1942 QualType getUnconstrainedType(QualType T) const;
1943
1944 /// C++17 deduced class template specialization type.
1945 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1946 QualType DeducedType,
1947 bool IsDependent) const;
1948
1949private:
1950 QualType getDeducedTemplateSpecializationTypeInternal(TemplateName Template,
1951 QualType DeducedType,
1952 bool IsDependent,
1953 QualType Canon) const;
1954
1955public:
1956 /// Return the unique reference to the type for the specified TagDecl
1957 /// (struct/union/class/enum) decl.
1958 QualType getTagDeclType(const TagDecl *Decl) const;
1959
1960 /// Return the unique type for "size_t" (C99 7.17), defined in
1961 /// <stddef.h>.
1962 ///
1963 /// The sizeof operator requires this (C99 6.5.3.4p4).
1964 CanQualType getSizeType() const;
1965
1966 /// Return the unique signed counterpart of
1967 /// the integer type corresponding to size_t.
1968 CanQualType getSignedSizeType() const;
1969
1970 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1971 /// <stdint.h>.
1972 CanQualType getIntMaxType() const;
1973
1974 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1975 /// <stdint.h>.
1976 CanQualType getUIntMaxType() const;
1977
1978 /// Return the unique wchar_t type available in C++ (and available as
1979 /// __wchar_t as a Microsoft extension).
1980 QualType getWCharType() const { return WCharTy; }
1981
1982 /// Return the type of wide characters. In C++, this returns the
1983 /// unique wchar_t type. In C99, this returns a type compatible with the type
1984 /// defined in <stddef.h> as defined by the target.
1985 QualType getWideCharType() const { return WideCharTy; }
1986
1987 /// Return the type of "signed wchar_t".
1988 ///
1989 /// Used when in C++, as a GCC extension.
1990 QualType getSignedWCharType() const;
1991
1992 /// Return the type of "unsigned wchar_t".
1993 ///
1994 /// Used when in C++, as a GCC extension.
1995 QualType getUnsignedWCharType() const;
1996
1997 /// In C99, this returns a type compatible with the type
1998 /// defined in <stddef.h> as defined by the target.
1999 QualType getWIntType() const { return WIntTy; }
2000
2001 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
2002 /// as defined by the target.
2003 QualType getIntPtrType() const;
2004
2005 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
2006 /// as defined by the target.
2007 QualType getUIntPtrType() const;
2008
2009 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
2010 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2011 QualType getPointerDiffType() const;
2012
2013 /// Return the unique unsigned counterpart of "ptrdiff_t"
2014 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
2015 /// in the definition of %tu format specifier.
2016 QualType getUnsignedPointerDiffType() const;
2017
2018 /// Return the unique type for "pid_t" defined in
2019 /// <sys/types.h>. We need this to compute the correct type for vfork().
2020 QualType getProcessIDType() const;
2021
2022 /// Return the C structure type used to represent constant CFStrings.
2023 QualType getCFConstantStringType() const;
2024
2025 /// Returns the C struct type for objc_super
2026 QualType getObjCSuperType() const;
2027 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
2028
2029 /// Get the structure type used to representation CFStrings, or NULL
2030 /// if it hasn't yet been built.
2031 QualType getRawCFConstantStringType() const {
2032 if (CFConstantStringTypeDecl)
2033 return getTypedefType(CFConstantStringTypeDecl);
2034 return QualType();
2035 }
2036 void setCFConstantStringType(QualType T);
2037 TypedefDecl *getCFConstantStringDecl() const;
2038 RecordDecl *getCFConstantStringTagDecl() const;
2039
2040 // This setter/getter represents the ObjC type for an NSConstantString.
2041 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
2042 QualType getObjCConstantStringInterface() const {
2043 return ObjCConstantStringType;
2044 }
2045
2046 QualType getObjCNSStringType() const {
2047 return ObjCNSStringType;
2048 }
2049
2050 void setObjCNSStringType(QualType T) {
2051 ObjCNSStringType = T;
2052 }
2053
2054 /// Retrieve the type that \c id has been defined to, which may be
2055 /// different from the built-in \c id if \c id has been typedef'd.
2056 QualType getObjCIdRedefinitionType() const {
2057 if (ObjCIdRedefinitionType.isNull())
2058 return getObjCIdType();
2059 return ObjCIdRedefinitionType;
2060 }
2061
2062 /// Set the user-written type that redefines \c id.
2063 void setObjCIdRedefinitionType(QualType RedefType) {
2064 ObjCIdRedefinitionType = RedefType;
2065 }
2066
2067 /// Retrieve the type that \c Class has been defined to, which may be
2068 /// different from the built-in \c Class if \c Class has been typedef'd.
2069 QualType getObjCClassRedefinitionType() const {
2070 if (ObjCClassRedefinitionType.isNull())
2071 return getObjCClassType();
2072 return ObjCClassRedefinitionType;
2073 }
2074
2075 /// Set the user-written type that redefines 'SEL'.
2076 void setObjCClassRedefinitionType(QualType RedefType) {
2077 ObjCClassRedefinitionType = RedefType;
2078 }
2079
2080 /// Retrieve the type that 'SEL' has been defined to, which may be
2081 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
2082 QualType getObjCSelRedefinitionType() const {
2083 if (ObjCSelRedefinitionType.isNull())
2084 return getObjCSelType();
2085 return ObjCSelRedefinitionType;
2086 }
2087
2088 /// Set the user-written type that redefines 'SEL'.
2089 void setObjCSelRedefinitionType(QualType RedefType) {
2090 ObjCSelRedefinitionType = RedefType;
2091 }
2092
2093 /// Retrieve the identifier 'NSObject'.
2094 IdentifierInfo *getNSObjectName() const {
2095 if (!NSObjectName) {
2096 NSObjectName = &Idents.get(Name: "NSObject");
2097 }
2098
2099 return NSObjectName;
2100 }
2101
2102 /// Retrieve the identifier 'NSCopying'.
2103 IdentifierInfo *getNSCopyingName() {
2104 if (!NSCopyingName) {
2105 NSCopyingName = &Idents.get(Name: "NSCopying");
2106 }
2107
2108 return NSCopyingName;
2109 }
2110
2111 CanQualType getNSUIntegerType() const;
2112
2113 CanQualType getNSIntegerType() const;
2114
2115 /// Retrieve the identifier 'bool'.
2116 IdentifierInfo *getBoolName() const {
2117 if (!BoolName)
2118 BoolName = &Idents.get(Name: "bool");
2119 return BoolName;
2120 }
2121
2122#define BuiltinTemplate(BTName) \
2123 IdentifierInfo *get##BTName##Name() const { \
2124 if (!Name##BTName) \
2125 Name##BTName = &Idents.get(#BTName); \
2126 return Name##BTName; \
2127 }
2128#include "clang/Basic/BuiltinTemplates.inc"
2129
2130 /// Retrieve the Objective-C "instancetype" type, if already known;
2131 /// otherwise, returns a NULL type;
2132 QualType getObjCInstanceType() {
2133 return getTypeDeclType(getObjCInstanceTypeDecl());
2134 }
2135
2136 /// Retrieve the typedef declaration corresponding to the Objective-C
2137 /// "instancetype" type.
2138 TypedefDecl *getObjCInstanceTypeDecl();
2139
2140 /// Set the type for the C FILE type.
2141 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
2142
2143 /// Retrieve the C FILE type.
2144 QualType getFILEType() const {
2145 if (FILEDecl)
2146 return getTypeDeclType(Decl: FILEDecl);
2147 return QualType();
2148 }
2149
2150 /// Set the type for the C jmp_buf type.
2151 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
2152 this->jmp_bufDecl = jmp_bufDecl;
2153 }
2154
2155 /// Retrieve the C jmp_buf type.
2156 QualType getjmp_bufType() const {
2157 if (jmp_bufDecl)
2158 return getTypeDeclType(Decl: jmp_bufDecl);
2159 return QualType();
2160 }
2161
2162 /// Set the type for the C sigjmp_buf type.
2163 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
2164 this->sigjmp_bufDecl = sigjmp_bufDecl;
2165 }
2166
2167 /// Retrieve the C sigjmp_buf type.
2168 QualType getsigjmp_bufType() const {
2169 if (sigjmp_bufDecl)
2170 return getTypeDeclType(Decl: sigjmp_bufDecl);
2171 return QualType();
2172 }
2173
2174 /// Set the type for the C ucontext_t type.
2175 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
2176 this->ucontext_tDecl = ucontext_tDecl;
2177 }
2178
2179 /// Retrieve the C ucontext_t type.
2180 QualType getucontext_tType() const {
2181 if (ucontext_tDecl)
2182 return getTypeDeclType(Decl: ucontext_tDecl);
2183 return QualType();
2184 }
2185
2186 /// The result type of logical operations, '<', '>', '!=', etc.
2187 QualType getLogicalOperationType() const {
2188 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
2189 }
2190
2191 /// Emit the Objective-CC type encoding for the given type \p T into
2192 /// \p S.
2193 ///
2194 /// If \p Field is specified then record field names are also encoded.
2195 void getObjCEncodingForType(QualType T, std::string &S,
2196 const FieldDecl *Field=nullptr,
2197 QualType *NotEncodedT=nullptr) const;
2198
2199 /// Emit the Objective-C property type encoding for the given
2200 /// type \p T into \p S.
2201 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
2202
2203 void getLegacyIntegralTypeEncoding(QualType &t) const;
2204
2205 /// Put the string version of the type qualifiers \p QT into \p S.
2206 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2207 std::string &S) const;
2208
2209 /// Emit the encoded type for the function \p Decl into \p S.
2210 ///
2211 /// This is in the same format as Objective-C method encodings.
2212 ///
2213 /// \returns true if an error occurred (e.g., because one of the parameter
2214 /// types is incomplete), false otherwise.
2215 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
2216
2217 /// Emit the encoded type for the method declaration \p Decl into
2218 /// \p S.
2219 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2220 bool Extended = false) const;
2221
2222 /// Return the encoded type for this block declaration.
2223 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
2224
2225 /// getObjCEncodingForPropertyDecl - Return the encoded type for
2226 /// this method declaration. If non-NULL, Container must be either
2227 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
2228 /// only be NULL when getting encodings for protocol properties.
2229 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2230 const Decl *Container) const;
2231
2232 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
2233 ObjCProtocolDecl *rProto) const;
2234
2235 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
2236 const ObjCPropertyDecl *PD,
2237 const Decl *Container) const;
2238
2239 /// Return the size of type \p T for Objective-C encoding purpose,
2240 /// in characters.
2241 CharUnits getObjCEncodingTypeSize(QualType T) const;
2242
2243 /// Retrieve the typedef corresponding to the predefined \c id type
2244 /// in Objective-C.
2245 TypedefDecl *getObjCIdDecl() const;
2246
2247 /// Represents the Objective-CC \c id type.
2248 ///
2249 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
2250 /// pointer type, a pointer to a struct.
2251 QualType getObjCIdType() const {
2252 return getTypeDeclType(getObjCIdDecl());
2253 }
2254
2255 /// Retrieve the typedef corresponding to the predefined 'SEL' type
2256 /// in Objective-C.
2257 TypedefDecl *getObjCSelDecl() const;
2258
2259 /// Retrieve the type that corresponds to the predefined Objective-C
2260 /// 'SEL' type.
2261 QualType getObjCSelType() const {
2262 return getTypeDeclType(getObjCSelDecl());
2263 }
2264
2265 /// Retrieve the typedef declaration corresponding to the predefined
2266 /// Objective-C 'Class' type.
2267 TypedefDecl *getObjCClassDecl() const;
2268
2269 /// Represents the Objective-C \c Class type.
2270 ///
2271 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
2272 /// pointer type, a pointer to a struct.
2273 QualType getObjCClassType() const {
2274 return getTypeDeclType(getObjCClassDecl());
2275 }
2276
2277 /// Retrieve the Objective-C class declaration corresponding to
2278 /// the predefined \c Protocol class.
2279 ObjCInterfaceDecl *getObjCProtocolDecl() const;
2280
2281 /// Retrieve declaration of 'BOOL' typedef
2282 TypedefDecl *getBOOLDecl() const {
2283 return BOOLDecl;
2284 }
2285
2286 /// Save declaration of 'BOOL' typedef
2287 void setBOOLDecl(TypedefDecl *TD) {
2288 BOOLDecl = TD;
2289 }
2290
2291 /// type of 'BOOL' type.
2292 QualType getBOOLType() const {
2293 return getTypeDeclType(getBOOLDecl());
2294 }
2295
2296 /// Retrieve the type of the Objective-C \c Protocol class.
2297 QualType getObjCProtoType() const {
2298 return getObjCInterfaceType(Decl: getObjCProtocolDecl());
2299 }
2300
2301 /// Retrieve the C type declaration corresponding to the predefined
2302 /// \c __builtin_va_list type.
2303 TypedefDecl *getBuiltinVaListDecl() const;
2304
2305 /// Retrieve the type of the \c __builtin_va_list type.
2306 QualType getBuiltinVaListType() const {
2307 return getTypeDeclType(getBuiltinVaListDecl());
2308 }
2309
2310 /// Retrieve the C type declaration corresponding to the predefined
2311 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
2312 /// for some targets.
2313 Decl *getVaListTagDecl() const;
2314
2315 /// Retrieve the C type declaration corresponding to the predefined
2316 /// \c __builtin_ms_va_list type.
2317 TypedefDecl *getBuiltinMSVaListDecl() const;
2318
2319 /// Retrieve the type of the \c __builtin_ms_va_list type.
2320 QualType getBuiltinMSVaListType() const {
2321 return getTypeDeclType(getBuiltinMSVaListDecl());
2322 }
2323
2324 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
2325 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
2326
2327 /// Retrieve the implicitly-predeclared 'struct _GUID' type.
2328 QualType getMSGuidType() const {
2329 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
2330 return getTagDeclType(Decl: MSGuidTagDecl);
2331 }
2332
2333 /// Return whether a declaration to a builtin is allowed to be
2334 /// overloaded/redeclared.
2335 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
2336
2337 /// Return a type with additional \c const, \c volatile, or
2338 /// \c restrict qualifiers.
2339 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
2340 return getQualifiedType(T, Qs: Qualifiers::fromCVRMask(CVR));
2341 }
2342
2343 /// Un-split a SplitQualType.
2344 QualType getQualifiedType(SplitQualType split) const {
2345 return getQualifiedType(T: split.Ty, Qs: split.Quals);
2346 }
2347
2348 /// Return a type with additional qualifiers.
2349 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
2350 if (!Qs.hasNonFastQualifiers())
2351 return T.withFastQualifiers(TQs: Qs.getFastQualifiers());
2352 QualifierCollector Qc(Qs);
2353 const Type *Ptr = Qc.strip(type: T);
2354 return getExtQualType(Base: Ptr, Quals: Qc);
2355 }
2356
2357 /// Return a type with additional qualifiers.
2358 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
2359 if (!Qs.hasNonFastQualifiers())
2360 return QualType(T, Qs.getFastQualifiers());
2361 return getExtQualType(Base: T, Quals: Qs);
2362 }
2363
2364 /// Return a type with the given lifetime qualifier.
2365 ///
2366 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
2367 QualType getLifetimeQualifiedType(QualType type,
2368 Qualifiers::ObjCLifetime lifetime) {
2369 assert(type.getObjCLifetime() == Qualifiers::OCL_None);
2370 assert(lifetime != Qualifiers::OCL_None);
2371
2372 Qualifiers qs;
2373 qs.addObjCLifetime(type: lifetime);
2374 return getQualifiedType(T: type, Qs: qs);
2375 }
2376
2377 /// getUnqualifiedObjCPointerType - Returns version of
2378 /// Objective-C pointer type with lifetime qualifier removed.
2379 QualType getUnqualifiedObjCPointerType(QualType type) const {
2380 if (!type.getTypePtr()->isObjCObjectPointerType() ||
2381 !type.getQualifiers().hasObjCLifetime())
2382 return type;
2383 Qualifiers Qs = type.getQualifiers();
2384 Qs.removeObjCLifetime();
2385 return getQualifiedType(T: type.getUnqualifiedType(), Qs);
2386 }
2387
2388 /// \brief Return a type with the given __ptrauth qualifier.
2389 QualType getPointerAuthType(QualType Ty, PointerAuthQualifier PointerAuth) {
2390 assert(!Ty.getPointerAuth());
2391 assert(PointerAuth);
2392
2393 Qualifiers Qs;
2394 Qs.setPointerAuth(PointerAuth);
2395 return getQualifiedType(T: Ty, Qs);
2396 }
2397
2398 unsigned char getFixedPointScale(QualType Ty) const;
2399 unsigned char getFixedPointIBits(QualType Ty) const;
2400 llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
2401 llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
2402 llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
2403
2404 DeclarationNameInfo getNameForTemplate(TemplateName Name,
2405 SourceLocation NameLoc) const;
2406
2407 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
2408 UnresolvedSetIterator End) const;
2409 TemplateName getAssumedTemplateName(DeclarationName Name) const;
2410
2411 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
2412 bool TemplateKeyword,
2413 TemplateName Template) const;
2414 TemplateName
2415 getDependentTemplateName(const DependentTemplateStorage &Name) const;
2416
2417 TemplateName getSubstTemplateTemplateParm(TemplateName replacement,
2418 Decl *AssociatedDecl,
2419 unsigned Index,
2420 UnsignedOrNone PackIndex,
2421 bool Final) const;
2422 TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
2423 Decl *AssociatedDecl,
2424 unsigned Index,
2425 bool Final) const;
2426
2427 /// Represents a TemplateName which had some of its default arguments
2428 /// deduced. This both represents this default argument deduction as sugar,
2429 /// and provides the support for it's equivalences through canonicalization.
2430 /// For example DeducedTemplateNames which have the same set of default
2431 /// arguments are equivalent, and are also equivalent to the underlying
2432 /// template when the deduced template arguments are the same.
2433 TemplateName getDeducedTemplateName(TemplateName Underlying,
2434 DefaultArguments DefaultArgs) const;
2435
2436 enum GetBuiltinTypeError {
2437 /// No error
2438 GE_None,
2439
2440 /// Missing a type
2441 GE_Missing_type,
2442
2443 /// Missing a type from <stdio.h>
2444 GE_Missing_stdio,
2445
2446 /// Missing a type from <setjmp.h>
2447 GE_Missing_setjmp,
2448
2449 /// Missing a type from <ucontext.h>
2450 GE_Missing_ucontext
2451 };
2452
2453 QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
2454 ASTContext::GetBuiltinTypeError &Error,
2455 bool &RequireICE, bool AllowTypeModifiers) const;
2456
2457 /// Return the type for the specified builtin.
2458 ///
2459 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2460 /// arguments to the builtin that are required to be integer constant
2461 /// expressions.
2462 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2463 unsigned *IntegerConstantArgs = nullptr) const;
2464
2465 /// Types and expressions required to build C++2a three-way comparisons
2466 /// using operator<=>, including the values return by builtin <=> operators.
2467 ComparisonCategories CompCategories;
2468
2469private:
2470 CanQualType getFromTargetType(unsigned Type) const;
2471 TypeInfo getTypeInfoImpl(const Type *T) const;
2472
2473 //===--------------------------------------------------------------------===//
2474 // Type Predicates.
2475 //===--------------------------------------------------------------------===//
2476
2477public:
2478 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2479 /// collection attributes.
2480 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2481
2482 /// Return true if the given vector types are of the same unqualified
2483 /// type or if they are equivalent to the same GCC vector type.
2484 ///
2485 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2486 /// types.
2487 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2488
2489 /// Return true if the given types are an SVE builtin and a VectorType that
2490 /// is a fixed-length representation of the SVE builtin for a specific
2491 /// vector-length.
2492 bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
2493
2494 /// Return true if the given vector types are lax-compatible SVE vector types,
2495 /// false otherwise.
2496 bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
2497
2498 /// Return true if the given types are an RISC-V vector builtin type and a
2499 /// VectorType that is a fixed-length representation of the RISC-V vector
2500 /// builtin type for a specific vector-length.
2501 bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2502
2503 /// Return true if the given vector types are lax-compatible RISC-V vector
2504 /// types as defined by -flax-vector-conversions=, which permits implicit
2505 /// conversions between vectors with different number of elements and/or
2506 /// incompatible element types, false otherwise.
2507 bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType);
2508
2509 /// Return true if the type has been explicitly qualified with ObjC ownership.
2510 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2511 /// some cases the compiler treats these differently.
2512 bool hasDirectOwnershipQualifier(QualType Ty) const;
2513
2514 /// Return true if this is an \c NSObject object with its \c NSObject
2515 /// attribute set.
2516 static bool isObjCNSObjectType(QualType Ty) {
2517 return Ty->isObjCNSObjectType();
2518 }
2519
2520 //===--------------------------------------------------------------------===//
2521 // Type Sizing and Analysis
2522 //===--------------------------------------------------------------------===//
2523
2524 /// Return the APFloat 'semantics' for the specified scalar floating
2525 /// point type.
2526 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2527
2528 /// Get the size and alignment of the specified complete type in bits.
2529 TypeInfo getTypeInfo(const Type *T) const;
2530 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T: T.getTypePtr()); }
2531
2532 /// Get default simd alignment of the specified complete type in bits.
2533 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2534
2535 /// Return the size of the specified (complete) type \p T, in bits.
2536 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2537 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2538
2539 /// Return the size of the character type, in bits.
2540 uint64_t getCharWidth() const {
2541 return getTypeSize(CharTy);
2542 }
2543
2544 /// Convert a size in bits to a size in characters.
2545 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2546
2547 /// Convert a size in characters to a size in bits.
2548 int64_t toBits(CharUnits CharSize) const;
2549
2550 /// Return the size of the specified (complete) type \p T, in
2551 /// characters.
2552 CharUnits getTypeSizeInChars(QualType T) const;
2553 CharUnits getTypeSizeInChars(const Type *T) const;
2554
2555 std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2556 if (Ty->isIncompleteType() || Ty->isDependentType())
2557 return std::nullopt;
2558 return getTypeSizeInChars(T: Ty);
2559 }
2560
2561 std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2562 return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2563 }
2564
2565 /// Return the ABI-specified alignment of a (complete) type \p T, in
2566 /// bits.
2567 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2568 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2569
2570 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2571 /// before alignment adjustments, in bits.
2572 ///
2573 /// This alignment is currently used only by ARM and AArch64 when passing
2574 /// arguments of a composite type.
2575 unsigned getTypeUnadjustedAlign(QualType T) const {
2576 return getTypeUnadjustedAlign(T: T.getTypePtr());
2577 }
2578 unsigned getTypeUnadjustedAlign(const Type *T) const;
2579
2580 /// Return the alignment of a type, in bits, or 0 if
2581 /// the type is incomplete and we cannot determine the alignment (for
2582 /// example, from alignment attributes). The returned alignment is the
2583 /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
2584 /// ABI alignment.
2585 unsigned getTypeAlignIfKnown(QualType T,
2586 bool NeedsPreferredAlignment = false) const;
2587
2588 /// Return the ABI-specified alignment of a (complete) type \p T, in
2589 /// characters.
2590 CharUnits getTypeAlignInChars(QualType T) const;
2591 CharUnits getTypeAlignInChars(const Type *T) const;
2592
2593 /// Return the PreferredAlignment of a (complete) type \p T, in
2594 /// characters.
2595 CharUnits getPreferredTypeAlignInChars(QualType T) const {
2596 return toCharUnitsFromBits(BitSize: getPreferredTypeAlign(T));
2597 }
2598
2599 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2600 /// in characters, before alignment adjustments. This method does not work on
2601 /// incomplete types.
2602 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2603 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2604
2605 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2606 // type is a record, its data size is returned.
2607 TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
2608
2609 TypeInfoChars getTypeInfoInChars(const Type *T) const;
2610 TypeInfoChars getTypeInfoInChars(QualType T) const;
2611
2612 /// Determine if the alignment the type has was required using an
2613 /// alignment attribute.
2614 bool isAlignmentRequired(const Type *T) const;
2615 bool isAlignmentRequired(QualType T) const;
2616
2617 /// More type predicates useful for type checking/promotion
2618 bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
2619
2620 /// Return the "preferred" alignment of the specified type \p T for
2621 /// the current target, in bits.
2622 ///
2623 /// This can be different than the ABI alignment in cases where it is
2624 /// beneficial for performance or backwards compatibility preserving to
2625 /// overalign a data type. (Note: despite the name, the preferred alignment
2626 /// is ABI-impacting, and not an optimization.)
2627 unsigned getPreferredTypeAlign(QualType T) const {
2628 return getPreferredTypeAlign(T: T.getTypePtr());
2629 }
2630 unsigned getPreferredTypeAlign(const Type *T) const;
2631
2632 /// Return the default alignment for __attribute__((aligned)) on
2633 /// this target, to be used if no alignment value is specified.
2634 unsigned getTargetDefaultAlignForAttributeAligned() const;
2635
2636 /// Return the alignment in bits that should be given to a
2637 /// global variable with type \p T. If \p VD is non-null it will be
2638 /// considered specifically for the query.
2639 unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
2640
2641 /// Return the alignment in characters that should be given to a
2642 /// global variable with type \p T. If \p VD is non-null it will be
2643 /// considered specifically for the query.
2644 CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
2645
2646 /// Return the minimum alignment as specified by the target. If \p VD is
2647 /// non-null it may be used to identify external or weak variables.
2648 unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const;
2649
2650 /// Return a conservative estimate of the alignment of the specified
2651 /// decl \p D.
2652 ///
2653 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2654 /// alignment.
2655 ///
2656 /// If \p ForAlignof, references are treated like their underlying type
2657 /// and large arrays don't get any special treatment. If not \p ForAlignof
2658 /// it computes the value expected by CodeGen: references are treated like
2659 /// pointers and large arrays get extra alignment.
2660 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2661
2662 /// Return the alignment (in bytes) of the thrown exception object. This is
2663 /// only meaningful for targets that allocate C++ exceptions in a system
2664 /// runtime, such as those using the Itanium C++ ABI.
2665 CharUnits getExnObjectAlignment() const;
2666
2667 /// Get or compute information about the layout of the specified
2668 /// record (struct/union/class) \p D, which indicates its size and field
2669 /// position information.
2670 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2671
2672 /// Get or compute information about the layout of the specified
2673 /// Objective-C interface.
2674 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2675 const;
2676
2677 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2678 bool Simple = false) const;
2679
2680 /// Get our current best idea for the key function of the
2681 /// given record decl, or nullptr if there isn't one.
2682 ///
2683 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2684 /// ...the first non-pure virtual function that is not inline at the
2685 /// point of class definition.
2686 ///
2687 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2688 /// virtual functions that are defined 'inline', which means that
2689 /// the result of this computation can change.
2690 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2691
2692 /// Observe that the given method cannot be a key function.
2693 /// Checks the key-function cache for the method's class and clears it
2694 /// if matches the given declaration.
2695 ///
2696 /// This is used in ABIs where out-of-line definitions marked
2697 /// inline are not considered to be key functions.
2698 ///
2699 /// \param method should be the declaration from the class definition
2700 void setNonKeyFunction(const CXXMethodDecl *method);
2701
2702 /// Loading virtual member pointers using the virtual inheritance model
2703 /// always results in an adjustment using the vbtable even if the index is
2704 /// zero.
2705 ///
2706 /// This is usually OK because the first slot in the vbtable points
2707 /// backwards to the top of the MDC. However, the MDC might be reusing a
2708 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2709 /// points to the start of the nv-base which introduced the vbptr and *not*
2710 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2711 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2712
2713 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2714 uint64_t getFieldOffset(const ValueDecl *FD) const;
2715
2716 /// Get the offset of an ObjCIvarDecl in bits.
2717 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2718 const ObjCIvarDecl *Ivar) const;
2719
2720 /// Find the 'this' offset for the member path in a pointer-to-member
2721 /// APValue.
2722 CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
2723
2724 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2725
2726 VTableContextBase *getVTableContext();
2727
2728 /// If \p T is null pointer, assume the target in ASTContext.
2729 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2730
2731 /// Creates a device mangle context to correctly mangle lambdas in a mixed
2732 /// architecture compile by setting the lambda mangling number source to the
2733 /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo
2734 /// (from the AuxTargetInfo) is a an itanium target.
2735 MangleContext *createDeviceMangleContext(const TargetInfo &T);
2736
2737 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2738 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2739
2740 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2741 void CollectInheritedProtocols(const Decl *CDecl,
2742 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2743
2744 /// Return true if the specified type has unique object representations
2745 /// according to (C++17 [meta.unary.prop]p9)
2746 bool
2747 hasUniqueObjectRepresentations(QualType Ty,
2748 bool CheckIfTriviallyCopyable = true) const;
2749
2750 //===--------------------------------------------------------------------===//
2751 // Type Operators
2752 //===--------------------------------------------------------------------===//
2753
2754 /// Return the canonical (structural) type corresponding to the
2755 /// specified potentially non-canonical type \p T.
2756 ///
2757 /// The non-canonical version of a type may have many "decorated" versions of
2758 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2759 /// returned type is guaranteed to be free of any of these, allowing two
2760 /// canonical types to be compared for exact equality with a simple pointer
2761 /// comparison.
2762 CanQualType getCanonicalType(QualType T) const {
2763 return CanQualType::CreateUnsafe(Other: T.getCanonicalType());
2764 }
2765
2766 const Type *getCanonicalType(const Type *T) const {
2767 return T->getCanonicalTypeInternal().getTypePtr();
2768 }
2769
2770 /// Return the canonical parameter type corresponding to the specific
2771 /// potentially non-canonical one.
2772 ///
2773 /// Qualifiers are stripped off, functions are turned into function
2774 /// pointers, and arrays decay one level into pointers.
2775 CanQualType getCanonicalParamType(QualType T) const;
2776
2777 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2778 bool hasSameType(QualType T1, QualType T2) const {
2779 return getCanonicalType(T: T1) == getCanonicalType(T: T2);
2780 }
2781 bool hasSameType(const Type *T1, const Type *T2) const {
2782 return getCanonicalType(T: T1) == getCanonicalType(T: T2);
2783 }
2784
2785 /// Determine whether the given expressions \p X and \p Y are equivalent.
2786 bool hasSameExpr(const Expr *X, const Expr *Y) const;
2787
2788 /// Return this type as a completely-unqualified array type,
2789 /// capturing the qualifiers in \p Quals.
2790 ///
2791 /// This will remove the minimal amount of sugaring from the types, similar
2792 /// to the behavior of QualType::getUnqualifiedType().
2793 ///
2794 /// \param T is the qualified type, which may be an ArrayType
2795 ///
2796 /// \param Quals will receive the full set of qualifiers that were
2797 /// applied to the array.
2798 ///
2799 /// \returns if this is an array type, the completely unqualified array type
2800 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2801 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const;
2802 QualType getUnqualifiedArrayType(QualType T) const {
2803 Qualifiers Quals;
2804 return getUnqualifiedArrayType(T, Quals);
2805 }
2806
2807 /// Determine whether the given types are equivalent after
2808 /// cvr-qualifiers have been removed.
2809 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2810 return getCanonicalType(T: T1).getTypePtr() ==
2811 getCanonicalType(T: T2).getTypePtr();
2812 }
2813
2814 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2815 bool IsParam) const {
2816 auto SubTnullability = SubT->getNullability();
2817 auto SuperTnullability = SuperT->getNullability();
2818 if (SubTnullability.has_value() == SuperTnullability.has_value()) {
2819 // Neither has nullability; return true
2820 if (!SubTnullability)
2821 return true;
2822 // Both have nullability qualifier.
2823 if (*SubTnullability == *SuperTnullability ||
2824 *SubTnullability == NullabilityKind::Unspecified ||
2825 *SuperTnullability == NullabilityKind::Unspecified)
2826 return true;
2827
2828 if (IsParam) {
2829 // Ok for the superclass method parameter to be "nonnull" and the subclass
2830 // method parameter to be "nullable"
2831 return (*SuperTnullability == NullabilityKind::NonNull &&
2832 *SubTnullability == NullabilityKind::Nullable);
2833 }
2834 // For the return type, it's okay for the superclass method to specify
2835 // "nullable" and the subclass method specify "nonnull"
2836 return (*SuperTnullability == NullabilityKind::Nullable &&
2837 *SubTnullability == NullabilityKind::NonNull);
2838 }
2839 return true;
2840 }
2841
2842 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2843 const ObjCMethodDecl *MethodImp);
2844
2845 bool UnwrapSimilarTypes(QualType &T1, QualType &T2,
2846 bool AllowPiMismatch = true) const;
2847 void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
2848 bool AllowPiMismatch = true) const;
2849
2850 /// Determine if two types are similar, according to the C++ rules. That is,
2851 /// determine if they are the same other than qualifiers on the initial
2852 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2853 /// pointer) types and their element types.
2854 ///
2855 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2856 /// those qualifiers are also ignored in the 'similarity' check.
2857 bool hasSimilarType(QualType T1, QualType T2) const;
2858
2859 /// Determine if two types are similar, ignoring only CVR qualifiers.
2860 bool hasCvrSimilarType(QualType T1, QualType T2);
2861
2862 /// Retrieves the "canonical" nested name specifier for a
2863 /// given nested name specifier.
2864 ///
2865 /// The canonical nested name specifier is a nested name specifier
2866 /// that uniquely identifies a type or namespace within the type
2867 /// system. For example, given:
2868 ///
2869 /// \code
2870 /// namespace N {
2871 /// struct S {
2872 /// template<typename T> struct X { typename T* type; };
2873 /// };
2874 /// }
2875 ///
2876 /// template<typename T> struct Y {
2877 /// typename N::S::X<T>::type member;
2878 /// };
2879 /// \endcode
2880 ///
2881 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2882 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2883 /// by declarations in the type system and the canonical type for
2884 /// the template type parameter 'T' is template-param-0-0.
2885 NestedNameSpecifier *
2886 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2887
2888 /// Retrieves the default calling convention for the current target.
2889 CallingConv getDefaultCallingConvention(bool IsVariadic,
2890 bool IsCXXMethod,
2891 bool IsBuiltin = false) const;
2892
2893 /// Retrieves the "canonical" template name that refers to a
2894 /// given template.
2895 ///
2896 /// The canonical template name is the simplest expression that can
2897 /// be used to refer to a given template. For most templates, this
2898 /// expression is just the template declaration itself. For example,
2899 /// the template std::vector can be referred to via a variety of
2900 /// names---std::vector, \::std::vector, vector (if vector is in
2901 /// scope), etc.---but all of these names map down to the same
2902 /// TemplateDecl, which is used to form the canonical template name.
2903 ///
2904 /// Dependent template names are more interesting. Here, the
2905 /// template name could be something like T::template apply or
2906 /// std::allocator<T>::template rebind, where the nested name
2907 /// specifier itself is dependent. In this case, the canonical
2908 /// template name uses the shortest form of the dependent
2909 /// nested-name-specifier, which itself contains all canonical
2910 /// types, values, and templates.
2911 TemplateName getCanonicalTemplateName(TemplateName Name,
2912 bool IgnoreDeduced = false) const;
2913
2914 /// Determine whether the given template names refer to the same
2915 /// template.
2916 bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y,
2917 bool IgnoreDeduced = false) const;
2918
2919 /// Determine whether the two declarations refer to the same entity.
2920 bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const;
2921
2922 /// Determine whether two template parameter lists are similar enough
2923 /// that they may be used in declarations of the same template.
2924 bool isSameTemplateParameterList(const TemplateParameterList *X,
2925 const TemplateParameterList *Y) const;
2926
2927 /// Determine whether two template parameters are similar enough
2928 /// that they may be used in declarations of the same template.
2929 bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const;
2930
2931 /// Determine whether two 'requires' expressions are similar enough that they
2932 /// may be used in re-declarations.
2933 ///
2934 /// Use of 'requires' isn't mandatory, works with constraints expressed in
2935 /// other ways too.
2936 bool isSameAssociatedConstraint(const AssociatedConstraint &ACX,
2937 const AssociatedConstraint &ACY) const;
2938
2939 /// Determine whether two 'requires' expressions are similar enough that they
2940 /// may be used in re-declarations.
2941 ///
2942 /// Use of 'requires' isn't mandatory, works with constraints expressed in
2943 /// other ways too.
2944 bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const;
2945
2946 /// Determine whether two type contraint are similar enough that they could
2947 /// used in declarations of the same template.
2948 bool isSameTypeConstraint(const TypeConstraint *XTC,
2949 const TypeConstraint *YTC) const;
2950
2951 /// Determine whether two default template arguments are similar enough
2952 /// that they may be used in declarations of the same template.
2953 bool isSameDefaultTemplateArgument(const NamedDecl *X,
2954 const NamedDecl *Y) const;
2955
2956 /// Retrieve the "canonical" template argument.
2957 ///
2958 /// The canonical template argument is the simplest template argument
2959 /// (which may be a type, value, expression, or declaration) that
2960 /// expresses the value of the argument.
2961 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2962 const;
2963
2964 /// Canonicalize the given template argument list.
2965 ///
2966 /// Returns true if any arguments were non-canonical, false otherwise.
2967 bool
2968 canonicalizeTemplateArguments(MutableArrayRef<TemplateArgument> Args) const;
2969
2970 /// Canonicalize the given TemplateTemplateParmDecl.
2971 TemplateTemplateParmDecl *
2972 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
2973
2974 TemplateTemplateParmDecl *findCanonicalTemplateTemplateParmDeclInternal(
2975 TemplateTemplateParmDecl *TTP) const;
2976 TemplateTemplateParmDecl *insertCanonicalTemplateTemplateParmDeclInternal(
2977 TemplateTemplateParmDecl *CanonTTP) const;
2978
2979 /// Determine whether the given template arguments \p Arg1 and \p Arg2 are
2980 /// equivalent.
2981 bool isSameTemplateArgument(const TemplateArgument &Arg1,
2982 const TemplateArgument &Arg2) const;
2983
2984 /// Type Query functions. If the type is an instance of the specified class,
2985 /// return the Type pointer for the underlying maximally pretty type. This
2986 /// is a member of ASTContext because this may need to do some amount of
2987 /// canonicalization, e.g. to move type qualifiers into the element type.
2988 const ArrayType *getAsArrayType(QualType T) const;
2989 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2990 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2991 }
2992 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2993 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2994 }
2995 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2996 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2997 }
2998 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2999 const {
3000 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
3001 }
3002
3003 /// Return the innermost element type of an array type.
3004 ///
3005 /// For example, will return "int" for int[m][n]
3006 QualType getBaseElementType(const ArrayType *VAT) const;
3007
3008 /// Return the innermost element type of a type (which needn't
3009 /// actually be an array type).
3010 QualType getBaseElementType(QualType QT) const;
3011
3012 /// Return number of constant array elements.
3013 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
3014
3015 /// Return number of elements initialized in an ArrayInitLoopExpr.
3016 uint64_t
3017 getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const;
3018
3019 /// Perform adjustment on the parameter type of a function.
3020 ///
3021 /// This routine adjusts the given parameter type @p T to the actual
3022 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
3023 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
3024 QualType getAdjustedParameterType(QualType T) const;
3025
3026 /// Retrieve the parameter type as adjusted for use in the signature
3027 /// of a function, decaying array and function types and removing top-level
3028 /// cv-qualifiers.
3029 QualType getSignatureParameterType(QualType T) const;
3030
3031 QualType getExceptionObjectType(QualType T) const;
3032
3033 /// Return the properly qualified result of decaying the specified
3034 /// array type to a pointer.
3035 ///
3036 /// This operation is non-trivial when handling typedefs etc. The canonical
3037 /// type of \p T must be an array type, this returns a pointer to a properly
3038 /// qualified element of the array.
3039 ///
3040 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3041 QualType getArrayDecayedType(QualType T) const;
3042
3043 /// Return the type that \p PromotableType will promote to: C99
3044 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
3045 QualType getPromotedIntegerType(QualType PromotableType) const;
3046
3047 /// Recurses in pointer/array types until it finds an Objective-C
3048 /// retainable type and returns its ownership.
3049 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
3050
3051 /// Whether this is a promotable bitfield reference according
3052 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3053 ///
3054 /// \returns the type this bit-field will promote to, or NULL if no
3055 /// promotion occurs.
3056 QualType isPromotableBitField(Expr *E) const;
3057
3058 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
3059 ///
3060 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
3061 /// \p LHS < \p RHS, return -1.
3062 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
3063
3064 /// Compare the rank of the two specified floating point types,
3065 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
3066 ///
3067 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
3068 /// \p LHS < \p RHS, return -1.
3069 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
3070
3071 /// Compare the rank of two floating point types as above, but compare equal
3072 /// if both types have the same floating-point semantics on the target (i.e.
3073 /// long double and double on AArch64 will return 0).
3074 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
3075
3076 unsigned getTargetAddressSpace(LangAS AS) const;
3077
3078 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
3079
3080 /// Get target-dependent integer value for null pointer which is used for
3081 /// constant folding.
3082 uint64_t getTargetNullPointerValue(QualType QT) const;
3083
3084 bool addressSpaceMapManglingFor(LangAS AS) const {
3085 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
3086 }
3087
3088 bool hasAnyFunctionEffects() const { return AnyFunctionEffects; }
3089
3090 // Merges two exception specifications, such that the resulting
3091 // exception spec is the union of both. For example, if either
3092 // of them can throw something, the result can throw it as well.
3093 FunctionProtoType::ExceptionSpecInfo
3094 mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
3095 FunctionProtoType::ExceptionSpecInfo ESI2,
3096 SmallVectorImpl<QualType> &ExceptionTypeStorage,
3097 bool AcceptDependent);
3098
3099 // For two "same" types, return a type which has
3100 // the common sugar between them. If Unqualified is true,
3101 // both types need only be the same unqualified type.
3102 // The result will drop the qualifiers which do not occur
3103 // in both types.
3104 QualType getCommonSugaredType(QualType X, QualType Y,
3105 bool Unqualified = false);
3106
3107private:
3108 // Helper for integer ordering
3109 unsigned getIntegerRank(const Type *T) const;
3110
3111public:
3112 //===--------------------------------------------------------------------===//
3113 // Type Compatibility Predicates
3114 //===--------------------------------------------------------------------===//
3115
3116 /// Compatibility predicates used to check assignment expressions.
3117 bool typesAreCompatible(QualType T1, QualType T2,
3118 bool CompareUnqualified = false); // C99 6.2.7p1
3119
3120 bool propertyTypesAreCompatible(QualType, QualType);
3121 bool typesAreBlockPointerCompatible(QualType, QualType);
3122
3123 bool isObjCIdType(QualType T) const {
3124 if (const auto *ET = dyn_cast<ElaboratedType>(T))
3125 T = ET->getNamedType();
3126 return T == getObjCIdType();
3127 }
3128
3129 bool isObjCClassType(QualType T) const {
3130 if (const auto *ET = dyn_cast<ElaboratedType>(T))
3131 T = ET->getNamedType();
3132 return T == getObjCClassType();
3133 }
3134
3135 bool isObjCSelType(QualType T) const {
3136 if (const auto *ET = dyn_cast<ElaboratedType>(T))
3137 T = ET->getNamedType();
3138 return T == getObjCSelType();
3139 }
3140
3141 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
3142 const ObjCObjectPointerType *RHS,
3143 bool ForCompare);
3144
3145 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
3146 const ObjCObjectPointerType *RHS);
3147
3148 // Check the safety of assignment from LHS to RHS
3149 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3150 const ObjCObjectPointerType *RHSOPT);
3151 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
3152 const ObjCObjectType *RHS);
3153 bool canAssignObjCInterfacesInBlockPointer(
3154 const ObjCObjectPointerType *LHSOPT,
3155 const ObjCObjectPointerType *RHSOPT,
3156 bool BlockReturnType);
3157 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
3158 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
3159 const ObjCObjectPointerType *RHSOPT);
3160 bool canBindObjCObjectType(QualType To, QualType From);
3161
3162 // Functions for calculating composite types
3163 QualType mergeTypes(QualType, QualType, bool OfBlockPointer = false,
3164 bool Unqualified = false, bool BlockReturnType = false,
3165 bool IsConditionalOperator = false);
3166 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer = false,
3167 bool Unqualified = false, bool AllowCXX = false,
3168 bool IsConditionalOperator = false);
3169 QualType mergeFunctionParameterTypes(QualType, QualType,
3170 bool OfBlockPointer = false,
3171 bool Unqualified = false);
3172 QualType mergeTransparentUnionType(QualType, QualType,
3173 bool OfBlockPointer=false,
3174 bool Unqualified = false);
3175 QualType mergeTagDefinitions(QualType, QualType);
3176
3177 QualType mergeObjCGCQualifiers(QualType, QualType);
3178
3179 /// This function merges the ExtParameterInfo lists of two functions. It
3180 /// returns true if the lists are compatible. The merged list is returned in
3181 /// NewParamInfos.
3182 ///
3183 /// \param FirstFnType The type of the first function.
3184 ///
3185 /// \param SecondFnType The type of the second function.
3186 ///
3187 /// \param CanUseFirst This flag is set to true if the first function's
3188 /// ExtParameterInfo list can be used as the composite list of
3189 /// ExtParameterInfo.
3190 ///
3191 /// \param CanUseSecond This flag is set to true if the second function's
3192 /// ExtParameterInfo list can be used as the composite list of
3193 /// ExtParameterInfo.
3194 ///
3195 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
3196 /// empty if none of the flags are set.
3197 ///
3198 bool mergeExtParameterInfo(
3199 const FunctionProtoType *FirstFnType,
3200 const FunctionProtoType *SecondFnType,
3201 bool &CanUseFirst, bool &CanUseSecond,
3202 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
3203
3204 void ResetObjCLayout(const ObjCInterfaceDecl *D);
3205
3206 void addObjCSubClass(const ObjCInterfaceDecl *D,
3207 const ObjCInterfaceDecl *SubClass) {
3208 ObjCSubClasses[D].push_back(SubClass);
3209 }
3210
3211 //===--------------------------------------------------------------------===//
3212 // Integer Predicates
3213 //===--------------------------------------------------------------------===//
3214
3215 // The width of an integer, as defined in C99 6.2.6.2. This is the number
3216 // of bits in an integer type excluding any padding bits.
3217 unsigned getIntWidth(QualType T) const;
3218
3219 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
3220 // unsigned integer type. This method takes a signed type, and returns the
3221 // corresponding unsigned integer type.
3222 // With the introduction of fixed point types in ISO N1169, this method also
3223 // accepts fixed point types and returns the corresponding unsigned type for
3224 // a given fixed point type.
3225 QualType getCorrespondingUnsignedType(QualType T) const;
3226
3227 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
3228 // unsigned integer type. This method takes an unsigned type, and returns the
3229 // corresponding signed integer type.
3230 // With the introduction of fixed point types in ISO N1169, this method also
3231 // accepts fixed point types and returns the corresponding signed type for
3232 // a given fixed point type.
3233 QualType getCorrespondingSignedType(QualType T) const;
3234
3235 // Per ISO N1169, this method accepts fixed point types and returns the
3236 // corresponding saturated type for a given fixed point type.
3237 QualType getCorrespondingSaturatedType(QualType Ty) const;
3238
3239 // Per ISO N1169, this method accepts fixed point types and returns the
3240 // corresponding non-saturated type for a given fixed point type.
3241 QualType getCorrespondingUnsaturatedType(QualType Ty) const;
3242
3243 // This method accepts fixed point types and returns the corresponding signed
3244 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
3245 // fixed point types because there are unsigned integer types like bool and
3246 // char8_t that don't have signed equivalents.
3247 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
3248
3249 //===--------------------------------------------------------------------===//
3250 // Integer Values
3251 //===--------------------------------------------------------------------===//
3252
3253 /// Make an APSInt of the appropriate width and signedness for the
3254 /// given \p Value and integer \p Type.
3255 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
3256 // If Type is a signed integer type larger than 64 bits, we need to be sure
3257 // to sign extend Res appropriately.
3258 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
3259 Res = Value;
3260 unsigned Width = getIntWidth(T: Type);
3261 if (Width != Res.getBitWidth())
3262 return Res.extOrTrunc(width: Width);
3263 return Res;
3264 }
3265
3266 bool isSentinelNullExpr(const Expr *E);
3267
3268 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
3269 /// none exists.
3270 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
3271
3272 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
3273 /// none exists.
3274 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
3275
3276 /// Return true if there is at least one \@implementation in the TU.
3277 bool AnyObjCImplementation() {
3278 return !ObjCImpls.empty();
3279 }
3280
3281 /// Set the implementation of ObjCInterfaceDecl.
3282 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3283 ObjCImplementationDecl *ImplD);
3284
3285 /// Set the implementation of ObjCCategoryDecl.
3286 void setObjCImplementation(ObjCCategoryDecl *CatD,
3287 ObjCCategoryImplDecl *ImplD);
3288
3289 /// Get the duplicate declaration of a ObjCMethod in the same
3290 /// interface, or null if none exists.
3291 const ObjCMethodDecl *
3292 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
3293
3294 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3295 const ObjCMethodDecl *Redecl);
3296
3297 /// Returns the Objective-C interface that \p ND belongs to if it is
3298 /// an Objective-C method/property/ivar etc. that is part of an interface,
3299 /// otherwise returns null.
3300 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
3301
3302 /// Set the copy initialization expression of a block var decl. \p CanThrow
3303 /// indicates whether the copy expression can throw or not.
3304 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
3305
3306 /// Get the copy initialization expression of the VarDecl \p VD, or
3307 /// nullptr if none exists.
3308 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
3309
3310 /// Allocate an uninitialized TypeSourceInfo.
3311 ///
3312 /// The caller should initialize the memory held by TypeSourceInfo using
3313 /// the TypeLoc wrappers.
3314 ///
3315 /// \param T the type that will be the basis for type source info. This type
3316 /// should refer to how the declarator was written in source code, not to
3317 /// what type semantic analysis resolved the declarator to.
3318 ///
3319 /// \param Size the size of the type info to create, or 0 if the size
3320 /// should be calculated based on the type.
3321 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
3322
3323 /// Allocate a TypeSourceInfo where all locations have been
3324 /// initialized to a given location, which defaults to the empty
3325 /// location.
3326 TypeSourceInfo *
3327 getTrivialTypeSourceInfo(QualType T,
3328 SourceLocation Loc = SourceLocation()) const;
3329
3330 /// Add a deallocation callback that will be invoked when the
3331 /// ASTContext is destroyed.
3332 ///
3333 /// \param Callback A callback function that will be invoked on destruction.
3334 ///
3335 /// \param Data Pointer data that will be provided to the callback function
3336 /// when it is called.
3337 void AddDeallocation(void (*Callback)(void *), void *Data) const;
3338
3339 /// If T isn't trivially destructible, calls AddDeallocation to register it
3340 /// for destruction.
3341 template <typename T> void addDestruction(T *Ptr) const {
3342 if (!std::is_trivially_destructible<T>::value) {
3343 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
3344 AddDeallocation(Callback: DestroyPtr, Data: Ptr);
3345 }
3346 }
3347
3348 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
3349 GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const;
3350
3351 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
3352 /// lazily, only when used; this is only relevant for function or file scoped
3353 /// var definitions.
3354 ///
3355 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
3356 /// it is not used.
3357 bool DeclMustBeEmitted(const Decl *D);
3358
3359 /// Visits all versions of a multiversioned function with the passed
3360 /// predicate.
3361 void forEachMultiversionedFunctionVersion(
3362 const FunctionDecl *FD,
3363 llvm::function_ref<void(FunctionDecl *)> Pred) const;
3364
3365 const CXXConstructorDecl *
3366 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
3367
3368 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
3369 CXXConstructorDecl *CD);
3370
3371 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
3372
3373 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
3374
3375 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
3376
3377 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
3378
3379 void setManglingNumber(const NamedDecl *ND, unsigned Number);
3380 unsigned getManglingNumber(const NamedDecl *ND,
3381 bool ForAuxTarget = false) const;
3382
3383 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
3384 unsigned getStaticLocalNumber(const VarDecl *VD) const;
3385
3386 bool hasSeenTypeAwareOperatorNewOrDelete() const {
3387 return !TypeAwareOperatorNewAndDeletes.empty();
3388 }
3389 void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying);
3390 bool isDestroyingOperatorDelete(const FunctionDecl *FD) const;
3391 void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
3392 bool IsTypeAware);
3393 bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const;
3394
3395 /// Retrieve the context for computing mangling numbers in the given
3396 /// DeclContext.
3397 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
3398 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
3399 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
3400 const Decl *D);
3401
3402 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
3403
3404 /// Used by ParmVarDecl to store on the side the
3405 /// index of the parameter when it exceeds the size of the normal bitfield.
3406 void setParameterIndex(const ParmVarDecl *D, unsigned index);
3407
3408 /// Used by ParmVarDecl to retrieve on the side the
3409 /// index of the parameter when it exceeds the size of the normal bitfield.
3410 unsigned getParameterIndex(const ParmVarDecl *D) const;
3411
3412 /// Return a string representing the human readable name for the specified
3413 /// function declaration or file name. Used by SourceLocExpr and
3414 /// PredefinedExpr to cache evaluated results.
3415 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
3416
3417 /// Return the next version number to be used for a string literal evaluated
3418 /// as part of constant evaluation.
3419 unsigned getNextStringLiteralVersion() { return NextStringLiteralVersion++; }
3420
3421 /// Return a declaration for the global GUID object representing the given
3422 /// GUID value.
3423 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
3424
3425 /// Return a declaration for a uniquified anonymous global constant
3426 /// corresponding to a given APValue.
3427 UnnamedGlobalConstantDecl *
3428 getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const;
3429
3430 /// Return the template parameter object of the given type with the given
3431 /// value.
3432 TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
3433 const APValue &V) const;
3434
3435 /// Parses the target attributes passed in, and returns only the ones that are
3436 /// valid feature names.
3437 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
3438
3439 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3440 const FunctionDecl *) const;
3441 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3442 GlobalDecl GD) const;
3443
3444 /// Generates and stores SYCL kernel metadata for the provided
3445 /// SYCL kernel entry point function. The provided function must have
3446 /// an attached sycl_kernel_entry_point attribute that specifies a unique
3447 /// type for the name of a SYCL kernel. Callers are required to detect
3448 /// conflicting SYCL kernel names and issue a diagnostic prior to calling
3449 /// this function.
3450 void registerSYCLEntryPointFunction(FunctionDecl *FD);
3451
3452 /// Given a type used as a SYCL kernel name, returns a reference to the
3453 /// metadata generated from the corresponding SYCL kernel entry point.
3454 /// Aborts if the provided type is not a registered SYCL kernel name.
3455 const SYCLKernelInfo &getSYCLKernelInfo(QualType T) const;
3456
3457 /// Returns a pointer to the metadata generated from the corresponding
3458 /// SYCLkernel entry point if the provided type corresponds to a registered
3459 /// SYCL kernel name. Returns a null pointer otherwise.
3460 const SYCLKernelInfo *findSYCLKernelInfo(QualType T) const;
3461
3462 //===--------------------------------------------------------------------===//
3463 // Statistics
3464 //===--------------------------------------------------------------------===//
3465
3466 /// The number of implicitly-declared default constructors.
3467 unsigned NumImplicitDefaultConstructors = 0;
3468
3469 /// The number of implicitly-declared default constructors for
3470 /// which declarations were built.
3471 unsigned NumImplicitDefaultConstructorsDeclared = 0;
3472
3473 /// The number of implicitly-declared copy constructors.
3474 unsigned NumImplicitCopyConstructors = 0;
3475
3476 /// The number of implicitly-declared copy constructors for
3477 /// which declarations were built.
3478 unsigned NumImplicitCopyConstructorsDeclared = 0;
3479
3480 /// The number of implicitly-declared move constructors.
3481 unsigned NumImplicitMoveConstructors = 0;
3482
3483 /// The number of implicitly-declared move constructors for
3484 /// which declarations were built.
3485 unsigned NumImplicitMoveConstructorsDeclared = 0;
3486
3487 /// The number of implicitly-declared copy assignment operators.
3488 unsigned NumImplicitCopyAssignmentOperators = 0;
3489
3490 /// The number of implicitly-declared copy assignment operators for
3491 /// which declarations were built.
3492 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
3493
3494 /// The number of implicitly-declared move assignment operators.
3495 unsigned NumImplicitMoveAssignmentOperators = 0;
3496
3497 /// The number of implicitly-declared move assignment operators for
3498 /// which declarations were built.
3499 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
3500
3501 /// The number of implicitly-declared destructors.
3502 unsigned NumImplicitDestructors = 0;
3503
3504 /// The number of implicitly-declared destructors for which
3505 /// declarations were built.
3506 unsigned NumImplicitDestructorsDeclared = 0;
3507
3508public:
3509 /// Initialize built-in types.
3510 ///
3511 /// This routine may only be invoked once for a given ASTContext object.
3512 /// It is normally invoked after ASTContext construction.
3513 ///
3514 /// \param Target The target
3515 void InitBuiltinTypes(const TargetInfo &Target,
3516 const TargetInfo *AuxTarget = nullptr);
3517
3518private:
3519 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
3520
3521 class ObjCEncOptions {
3522 unsigned Bits;
3523
3524 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
3525
3526 public:
3527 ObjCEncOptions() : Bits(0) {}
3528
3529#define OPT_LIST(V) \
3530 V(ExpandPointedToStructures, 0) \
3531 V(ExpandStructures, 1) \
3532 V(IsOutermostType, 2) \
3533 V(EncodingProperty, 3) \
3534 V(IsStructField, 4) \
3535 V(EncodeBlockParameters, 5) \
3536 V(EncodeClassNames, 6) \
3537
3538#define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
3539OPT_LIST(V)
3540#undef V
3541
3542#define V(N,I) bool N() const { return Bits & 1 << I; }
3543OPT_LIST(V)
3544#undef V
3545
3546#undef OPT_LIST
3547
3548 [[nodiscard]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
3549 return Bits & Mask.Bits;
3550 }
3551
3552 [[nodiscard]] ObjCEncOptions forComponentType() const {
3553 ObjCEncOptions Mask = ObjCEncOptions()
3554 .setIsOutermostType()
3555 .setIsStructField();
3556 return Bits & ~Mask.Bits;
3557 }
3558 };
3559
3560 // Return the Objective-C type encoding for a given type.
3561 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
3562 ObjCEncOptions Options,
3563 const FieldDecl *Field,
3564 QualType *NotEncodedT = nullptr) const;
3565
3566 // Adds the encoding of the structure's members.
3567 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
3568 const FieldDecl *Field,
3569 bool includeVBases = true,
3570 QualType *NotEncodedT=nullptr) const;
3571
3572public:
3573 // Adds the encoding of a method parameter or return type.
3574 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
3575 QualType T, std::string& S,
3576 bool Extended) const;
3577
3578 /// Returns true if this is an inline-initialized static data member
3579 /// which is treated as a definition for MSVC compatibility.
3580 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
3581
3582 enum class InlineVariableDefinitionKind {
3583 /// Not an inline variable.
3584 None,
3585
3586 /// Weak definition of inline variable.
3587 Weak,
3588
3589 /// Weak for now, might become strong later in this TU.
3590 WeakUnknown,
3591
3592 /// Strong definition.
3593 Strong
3594 };
3595
3596 /// Determine whether a definition of this inline variable should
3597 /// be treated as a weak or strong definition. For compatibility with
3598 /// C++14 and before, for a constexpr static data member, if there is an
3599 /// out-of-line declaration of the member, we may promote it from weak to
3600 /// strong.
3601 InlineVariableDefinitionKind
3602 getInlineVariableDefinitionKind(const VarDecl *VD) const;
3603
3604private:
3605 friend class DeclarationNameTable;
3606 friend class DeclContext;
3607
3608 const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D) const;
3609
3610 /// A set of deallocations that should be performed when the
3611 /// ASTContext is destroyed.
3612 // FIXME: We really should have a better mechanism in the ASTContext to
3613 // manage running destructors for types which do variable sized allocation
3614 // within the AST. In some places we thread the AST bump pointer allocator
3615 // into the datastructures which avoids this mess during deallocation but is
3616 // wasteful of memory, and here we require a lot of error prone book keeping
3617 // in order to track and run destructors while we're tearing things down.
3618 using DeallocationFunctionsAndArguments =
3619 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
3620 mutable DeallocationFunctionsAndArguments Deallocations;
3621
3622 // FIXME: This currently contains the set of StoredDeclMaps used
3623 // by DeclContext objects. This probably should not be in ASTContext,
3624 // but we include it here so that ASTContext can quickly deallocate them.
3625 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3626
3627 std::vector<Decl *> TraversalScope;
3628
3629 std::unique_ptr<VTableContextBase> VTContext;
3630
3631 void ReleaseDeclContextMaps();
3632
3633public:
3634 enum PragmaSectionFlag : unsigned {
3635 PSF_None = 0,
3636 PSF_Read = 0x1,
3637 PSF_Write = 0x2,
3638 PSF_Execute = 0x4,
3639 PSF_Implicit = 0x8,
3640 PSF_ZeroInit = 0x10,
3641 PSF_Invalid = 0x80000000U,
3642 };
3643
3644 struct SectionInfo {
3645 NamedDecl *Decl;
3646 SourceLocation PragmaSectionLocation;
3647 int SectionFlags;
3648
3649 SectionInfo() = default;
3650 SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
3651 int SectionFlags)
3652 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3653 SectionFlags(SectionFlags) {}
3654 };
3655
3656 llvm::StringMap<SectionInfo> SectionInfos;
3657
3658 /// Return a new OMPTraitInfo object owned by this context.
3659 OMPTraitInfo &getNewOMPTraitInfo();
3660
3661 /// Whether a C++ static variable or CUDA/HIP kernel may be externalized.
3662 bool mayExternalize(const Decl *D) const;
3663
3664 /// Whether a C++ static variable or CUDA/HIP kernel should be externalized.
3665 bool shouldExternalize(const Decl *D) const;
3666
3667 /// Resolve the root record to be used to derive the vtable pointer
3668 /// authentication policy for the specified record.
3669 const CXXRecordDecl *
3670 baseForVTableAuthentication(const CXXRecordDecl *ThisClass);
3671 bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
3672 StringRef MangledName);
3673
3674 StringRef getCUIDHash() const;
3675
3676private:
3677 /// All OMPTraitInfo objects live in this collection, one per
3678 /// `pragma omp [begin] declare variant` directive.
3679 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3680
3681 llvm::DenseMap<GlobalDecl, llvm::StringSet<>> ThunksToBeAbbreviated;
3682};
3683
3684/// Insertion operator for diagnostics.
3685const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
3686 const ASTContext::SectionInfo &Section);
3687
3688/// Utility function for constructing a nullary selector.
3689inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3690 const IdentifierInfo *II = &Ctx.Idents.get(Name: name);
3691 return Ctx.Selectors.getSelector(NumArgs: 0, IIV: &II);
3692}
3693
3694/// Utility function for constructing an unary selector.
3695inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3696 const IdentifierInfo *II = &Ctx.Idents.get(Name: name);
3697 return Ctx.Selectors.getSelector(NumArgs: 1, IIV: &II);
3698}
3699
3700} // namespace clang
3701
3702// operator new and delete aren't allowed inside namespaces.
3703
3704/// Placement new for using the ASTContext's allocator.
3705///
3706/// This placement form of operator new uses the ASTContext's allocator for
3707/// obtaining memory.
3708///
3709/// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3710/// Any changes here need to also be made there.
3711///
3712/// We intentionally avoid using a nothrow specification here so that the calls
3713/// to this operator will not perform a null check on the result -- the
3714/// underlying allocator never returns null pointers.
3715///
3716/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3717/// @code
3718/// // Default alignment (8)
3719/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3720/// // Specific alignment
3721/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3722/// @endcode
3723/// Memory allocated through this placement new operator does not need to be
3724/// explicitly freed, as ASTContext will free all of this memory when it gets
3725/// destroyed. Please note that you cannot use delete on the pointer.
3726///
3727/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3728/// @param C The ASTContext that provides the allocator.
3729/// @param Alignment The alignment of the allocated memory (if the underlying
3730/// allocator supports it).
3731/// @return The allocated memory. Could be nullptr.
3732inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3733 size_t Alignment /* = 8 */) {
3734 return C.Allocate(Size: Bytes, Align: Alignment);
3735}
3736
3737/// Placement delete companion to the new above.
3738///
3739/// This operator is just a companion to the new above. There is no way of
3740/// invoking it directly; see the new operator for more details. This operator
3741/// is called implicitly by the compiler if a placement new expression using
3742/// the ASTContext throws in the object constructor.
3743inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3744 C.Deallocate(Ptr);
3745}
3746
3747/// This placement form of operator new[] uses the ASTContext's allocator for
3748/// obtaining memory.
3749///
3750/// We intentionally avoid using a nothrow specification here so that the calls
3751/// to this operator will not perform a null check on the result -- the
3752/// underlying allocator never returns null pointers.
3753///
3754/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3755/// @code
3756/// // Default alignment (8)
3757/// char *data = new (Context) char[10];
3758/// // Specific alignment
3759/// char *data = new (Context, 4) char[10];
3760/// @endcode
3761/// Memory allocated through this placement new[] operator does not need to be
3762/// explicitly freed, as ASTContext will free all of this memory when it gets
3763/// destroyed. Please note that you cannot use delete on the pointer.
3764///
3765/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3766/// @param C The ASTContext that provides the allocator.
3767/// @param Alignment The alignment of the allocated memory (if the underlying
3768/// allocator supports it).
3769/// @return The allocated memory. Could be nullptr.
3770inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3771 size_t Alignment /* = 8 */) {
3772 return C.Allocate(Size: Bytes, Align: Alignment);
3773}
3774
3775/// Placement delete[] companion to the new[] above.
3776///
3777/// This operator is just a companion to the new[] above. There is no way of
3778/// invoking it directly; see the new[] operator for more details. This operator
3779/// is called implicitly by the compiler if a placement new[] expression using
3780/// the ASTContext throws in the object constructor.
3781inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3782 C.Deallocate(Ptr);
3783}
3784
3785/// Create the representation of a LazyGenerationalUpdatePtr.
3786template <typename Owner, typename T,
3787 void (clang::ExternalASTSource::*Update)(Owner)>
3788typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3789 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3790 const clang::ASTContext &Ctx, T Value) {
3791 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3792 // include ASTContext.h. We explicitly instantiate it for all relevant types
3793 // in ASTContext.cpp.
3794 if (auto *Source = Ctx.getExternalSource())
3795 return new (Ctx) LazyData(Source, Value);
3796 return Value;
3797}
3798
3799#endif // LLVM_CLANG_AST_ASTCONTEXT_H
3800

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/include/clang/AST/ASTContext.h