Coverage Report

Created: 2022-05-17 06:19

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