ASTContext.h 131 KB
Newer Older
1
//===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
2
//
3
4
5
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7
//
//===----------------------------------------------------------------------===//
8
//
9
/// \file
10
/// Defines the clang::ASTContext interface.
11
//
12
13
14
15
16
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
#define LLVM_CLANG_AST_ASTCONTEXT_H

17
#include "clang/AST/ASTContextAllocate.h"
18
#include "clang/AST/ASTFwd.h"
19
20
#include "clang/AST/CanonicalType.h"
#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
39
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/PartialDiagnostic.h"
40
#include "clang/Basic/ProfileList.h"
41
42
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
43
#include "clang/Basic/TargetCXXABI.h"
44
#include "clang/Basic/XRayLists.h"
45
46
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
47
#include "llvm/ADT/DenseMap.h"
48
#include "llvm/ADT/DenseSet.h"
Steve Naroff's avatar
   
Steve Naroff committed
49
#include "llvm/ADT/FoldingSet.h"
50
#include "llvm/ADT/IntrusiveRefCntPtr.h"
51
#include "llvm/ADT/MapVector.h"
52
53
54
55
56
57
58
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
59
60
61
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/iterator_range.h"
62
#include "llvm/Support/AlignOf.h"
63
#include "llvm/Support/Allocator.h"
64
65
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
66
#include "llvm/Support/TypeSize.h"
67
68
69
70
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
71
#include <memory>
72
#include <string>
73
#include <type_traits>
74
#include <utility>
75
#include <vector>
Chris Lattner's avatar
Chris Lattner committed
76

Chris Lattner's avatar
Chris Lattner committed
77
namespace llvm {
78

79
80
class APFixedPoint;
class FixedPointSemantics;
81
struct fltSemantics;
82
template <typename T, unsigned N> class SmallPtrSet;
83

84
} // namespace llvm
Chris Lattner's avatar
Chris Lattner committed
85

86
namespace clang {
87

88
class APValue;
89
90
91
92
class ASTMutationListener;
class ASTRecordLayout;
class AtomicExpr;
class BlockExpr;
93
class BuiltinTemplateDecl;
94
class CharUnits;
95
class ConceptDecl;
96
class CXXABI;
97
98
99
class CXXConstructorDecl;
class CXXMethodDecl;
class CXXRecordDecl;
100
class DiagnosticsEngine;
101
102
class ParentMapContext;
class DynTypedNodeList;
103
class Expr;
104
enum class FloatModeKind;
105
class GlobalDecl;
106
class MangleContext;
107
class MangleNumberingContext;
108
109
class MemberSpecializationInfo;
class Module;
110
struct MSGuidDeclParts;
111
112
113
114
115
116
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
117
class ObjCIvarDecl;
118
class ObjCMethodDecl;
119
class ObjCPropertyDecl;
120
121
122
class ObjCPropertyImplDecl;
class ObjCProtocolDecl;
class ObjCTypeParamDecl;
123
class OMPTraitInfo;
124
struct ParsedTargetAttr;
125
126
class Preprocessor;
class StoredDeclsMap;
127
class TargetAttr;
128
class TargetInfo;
129
130
131
132
class TemplateDecl;
class TemplateParameterList;
class TemplateTemplateParmDecl;
class TemplateTypeParmDecl;
133
134
class UnresolvedSetIterator;
class UsingShadowDecl;
135
class VarTemplateDecl;
136
class VTableContextBase;
137
struct BlockVarCopyInit;
138
139
140

namespace Builtin {

141
class Context;
142

143
} // namespace Builtin
144
145

enum BuiltinTemplateKind : int;
146
enum OpenCLTypeKind : uint8_t;
147
148
149

namespace comments {

150
class FullComment;
151

152
} // namespace comments
153

154
155
156
157
158
159
namespace interp {

class Context;

} // namespace interp

160
161
162
163
namespace serialization {
template <class> class AbstractTypeReader;
} // namespace serialization

164
165
166
167
168
169
170
171
172
173
174
175
176
177
enum class AlignRequirementKind {
  /// The alignment was not explicit in code.
  None,

  /// The alignment comes from an alignment attribute on a typedef.
  RequiredByTypedef,

  /// The alignment comes from an alignment attribute on a record type.
  RequiredByRecord,

  /// The alignment comes from an alignment attribute on a enum type.
  RequiredByEnum,
};

178
struct TypeInfo {
179
180
  uint64_t Width = 0;
  unsigned Align = 0;
181
182
183
184
185
186
187
188
189
  AlignRequirementKind AlignRequirement;

  TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
  TypeInfo(uint64_t Width, unsigned Align,
           AlignRequirementKind AlignRequirement)
      : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
  bool isAlignRequired() {
    return AlignRequirement != AlignRequirementKind::None;
  }
190
};
191

192
193
194
struct TypeInfoChars {
  CharUnits Width;
  CharUnits Align;
195
196
197
198
199
200
201
202
203
  AlignRequirementKind AlignRequirement;

  TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
  TypeInfoChars(CharUnits Width, CharUnits Align,
                AlignRequirementKind AlignRequirement)
      : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
  bool isAlignRequired() {
    return AlignRequirement != AlignRequirementKind::None;
  }
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
213
214
  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
  mutable llvm::FoldingSet<PointerType> PointerTypes;
215
  mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
216
217
218
219
  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
220
221
  mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
      ConstantArrayTypes;
222
223
224
225
226
  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
  mutable std::vector<VariableArrayType*> VariableArrayTypes;
  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
  mutable llvm::FoldingSet<DependentSizedExtVectorType>
    DependentSizedExtVectorTypes;
227
228
  mutable llvm::FoldingSet<DependentAddressSpaceType>
      DependentAddressSpaceTypes;
229
  mutable llvm::FoldingSet<VectorType> VectorTypes;
230
  mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
231
232
  mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
  mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
233
  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
234
235
  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
    FunctionProtoTypes;
236
237
238
  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
239
  mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
240
241
  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
    SubstTemplateTypeParmTypes;
242
243
  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
    SubstTemplateTypeParmPackTypes;
244
  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
245
    TemplateSpecializationTypes;
246
  mutable llvm::FoldingSet<ParenType> ParenTypes;
247
  mutable llvm::FoldingSet<UsingType> UsingTypes;
248
249
250
251
  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
                                     ASTContext&>
252
    DependentTemplateSpecializationTypes;
253
  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
254
255
  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
256
257
  mutable llvm::FoldingSet<DependentUnaryTransformType>
    DependentUnaryTransformTypes;
258
  mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
259
260
  mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
    DeducedTemplateSpecializationTypes;
261
  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
262
  llvm::FoldingSet<AttributedType> AttributedTypes;
263
  mutable llvm::FoldingSet<PipeType> PipeTypes;
264
265
  mutable llvm::FoldingSet<BitIntType> BitIntTypes;
  mutable llvm::FoldingSet<DependentBitIntType> DependentBitIntTypes;
266

267
268
  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
Simon Pilgrim's avatar
Simon Pilgrim committed
269
  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
270
271
    SubstTemplateTemplateParms;
  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
Simon Pilgrim's avatar
Simon Pilgrim committed
272
                                     ASTContext&>
273
    SubstTemplateTemplateParmPacks;
Simon Pilgrim's avatar
Simon Pilgrim committed
274

275
  /// The set of nested name specifiers.
276
277
  ///
  /// This set is managed by the NestedNameSpecifier class.
278
  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
279
  mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
280

281
  /// A cache mapping from RecordDecls to ASTRecordLayouts.
282
283
  ///
  /// This is lazily created.  This is intentionally not serialized.
284
285
286
287
  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
    ASTRecordLayouts;
  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
    ObjCLayouts;
288

289
  /// A cache from types to size and alignment information.
290
  using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
291
292
  mutable TypeInfoMap MemoizedTypeInfo;

293
294
295
296
297
298
  /// A cache from types to unadjusted alignment information. Only ARM and
  /// AArch64 targets need this information, keeping it separate prevents
  /// imposing overhead on TypeInfo size.
  using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
  mutable UnadjustedAlignMap MemoizedUnadjustedAlign;

299
  /// A cache mapping from CXXRecordDecls to key functions.
300
  llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
Simon Pilgrim's avatar
Simon Pilgrim committed
301

302
  /// Mapping from ObjCContainers to their ObjCImplementations.
303
  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
Simon Pilgrim's avatar
Simon Pilgrim committed
304

305
  /// Mapping from ObjCMethod to its duplicate declaration in the same
306
307
  /// interface.
  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
308

309
310
  /// Mapping from __block VarDecls to BlockVarCopyInit.
  llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
Simon Pilgrim's avatar
Simon Pilgrim committed
311

312
313
314
  /// Mapping from GUIDs to the corresponding MSGuidDecl.
  mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;

315
316
317
  /// Mapping from APValues to the corresponding TemplateParamObjects.
  mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;

318
319
320
321
322
323
  /// A cache mapping a string value to a StringLiteral object with the same
  /// value.
  ///
  /// This is lazily created.  This is intentionally not serialized.
  mutable llvm::StringMap<StringLiteral *> StringLiteralCache;

324
325
326
327
  /// MD5 hash of CUID. It is calculated when first used and cached by this
  /// data member.
  mutable std::string CUIDHash;

328
  /// Representation of a "canonical" template template parameter that
329
330
331
  /// is used in canonical template names.
  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
    TemplateTemplateParmDecl *Parm;
Simon Pilgrim's avatar
Simon Pilgrim committed
332

333
  public:
Simon Pilgrim's avatar
Simon Pilgrim committed
334
    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
335
        : Parm(Parm) {}
Simon Pilgrim's avatar
Simon Pilgrim committed
336

337
    TemplateTemplateParmDecl *getParam() const { return Parm; }
Simon Pilgrim's avatar
Simon Pilgrim committed
338

Saar Raz's avatar
Saar Raz committed
339
340
341
    void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
      Profile(ID, C, Parm);
    }
Simon Pilgrim's avatar
Simon Pilgrim committed
342
343

    static void Profile(llvm::FoldingSetNodeID &ID,
Saar Raz's avatar
Saar Raz committed
344
                        const ASTContext &C,
345
346
                        TemplateTemplateParmDecl *Parm);
  };
Saar Raz's avatar
Saar Raz committed
347
348
  mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
                                     const ASTContext&>
349
    CanonTemplateTemplateParms;
Simon Pilgrim's avatar
Simon Pilgrim committed
350

351
352
  TemplateTemplateParmDecl *
    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
353

354
  /// The typedef for the __int128_t type.
355
  mutable TypedefDecl *Int128Decl = nullptr;
356

357
  /// The typedef for the __uint128_t type.
358
  mutable TypedefDecl *UInt128Decl = nullptr;
359

360
  /// The typedef for the target specific predefined
361
  /// __builtin_va_list type.
362
  mutable TypedefDecl *BuiltinVaListDecl = nullptr;
363

Charles Davis's avatar
Charles Davis committed
364
  /// The typedef for the predefined \c __builtin_ms_va_list type.
365
  mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
Charles Davis's avatar
Charles Davis committed
366

367
  /// The typedef for the predefined \c id type.
368
  mutable TypedefDecl *ObjCIdDecl = nullptr;
Simon Pilgrim's avatar
Simon Pilgrim committed
369

370
  /// The typedef for the predefined \c SEL type.
371
  mutable TypedefDecl *ObjCSelDecl = nullptr;
372

373
  /// The typedef for the predefined \c Class type.
374
  mutable TypedefDecl *ObjCClassDecl = nullptr;
375

376
  /// The typedef for the predefined \c Protocol class in Objective-C.
377
  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
Simon Pilgrim's avatar
Simon Pilgrim committed
378

379
  /// The typedef for the predefined 'BOOL' type.
380
  mutable TypedefDecl *BOOLDecl = nullptr;
381

382
383
384
385
386
387
  // Typedefs which may be provided defining the structure of Objective-C
  // pseudo-builtins
  QualType ObjCIdRedefinitionType;
  QualType ObjCClassRedefinitionType;
  QualType ObjCSelRedefinitionType;

388
389
390
  /// The identifier 'bool'.
  mutable IdentifierInfo *BoolName = nullptr;

391
  /// The identifier 'NSObject'.
392
  mutable IdentifierInfo *NSObjectName = nullptr;
393
394
395
396

  /// The identifier 'NSCopying'.
  IdentifierInfo *NSCopyingName = nullptr;

397
398
399
  /// The identifier '__make_integer_seq'.
  mutable IdentifierInfo *MakeIntegerSeqName = nullptr;

400
401
402
  /// The identifier '__type_pack_element'.
  mutable IdentifierInfo *TypePackElementName = nullptr;

403
  QualType ObjCConstantStringType;
404
405
  mutable RecordDecl *CFConstantStringTagDecl = nullptr;
  mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
406

407
  mutable QualType ObjCSuperType;
Simon Pilgrim's avatar
Simon Pilgrim committed
408

409
  QualType ObjCNSStringType;
410

411
  /// The typedef declaration for the Objective-C "instancetype" type.
412
  TypedefDecl *ObjCInstanceTypeDecl = nullptr;
Simon Pilgrim's avatar
Simon Pilgrim committed
413

414
  /// The type for the C FILE type.
415
  TypeDecl *FILEDecl = nullptr;
416

417
  /// The type for the C jmp_buf type.
418
  TypeDecl *jmp_bufDecl = nullptr;
419

420
  /// The type for the C sigjmp_buf type.
421
  TypeDecl *sigjmp_bufDecl = nullptr;
422

423
  /// The type for the C ucontext_t type.
424
  TypeDecl *ucontext_tDecl = nullptr;
425

426
  /// Type for the Block descriptor for Blocks CodeGen.
427
428
429
  ///
  /// Since this is only used for generation of debug info, it is not
  /// serialized.
430
  mutable RecordDecl *BlockDescriptorType = nullptr;
431

432
  /// Type for the Block descriptor for Blocks CodeGen.
433
434
435
  ///
  /// Since this is only used for generation of debug info, it is not
  /// serialized.
436
  mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
437

438
  /// Declaration for the CUDA cudaConfigureCall function.
439
  FunctionDecl *cudaConfigureCallDecl = nullptr;
440

441
  /// Keeps track of all declaration attributes.
442
443
444
  ///
  /// Since so few decls have attrs, we keep them in a hash map instead of
  /// wasting space in the Decl class.
445
  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
446

447
  /// A mapping from non-redeclarable declarations in modules that were
448
449
450
451
  /// merged with other declarations to the canonical declaration that they were
  /// merged into.
  llvm::DenseMap<Decl*, Decl*> MergedDecls;

452
  /// A mapping from a defining declaration to a list of modules (other
453
454
  /// than the owning module of the declaration) that contain merged
  /// definitions of that entity.
455
  llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
456

457
  /// Initializers for a module, in order. Each Decl will be either
458
459
460
461
462
463
464
465
466
467
468
  /// something that has a semantic effect on startup (such as a variable with
  /// a non-constant initializer), or an ImportDecl (which recursively triggers
  /// initialization of another module).
  struct PerModuleInitializers {
    llvm::SmallVector<Decl*, 4> Initializers;
    llvm::SmallVector<uint32_t, 4> LazyInitializers;

    void resolve(ASTContext &Ctx);
  };
  llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;

469
470
  ASTContext &this_() { return *this; }

471
public:
472
  /// A type synonym for the TemplateOrInstantiation mapping.
473
474
  using TemplateOrSpecializationInfo =
      llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
475
476

private:
477
478
479
  friend class ASTDeclReader;
  friend class ASTReader;
  friend class ASTWriter;
480
  template <class> friend class serialization::AbstractTypeReader;
481
  friend class CXXRecordDecl;
482
  friend class IncrementalParser;
483

484
  /// A mapping to contain the template or declaration that
485
486
  /// a variable declaration describes or was instantiated from,
  /// respectively.
487
  ///
488
489
490
491
492
493
494
495
  /// For non-templates, this value will be NULL. For variable
  /// declarations that describe a variable template, this will be a
  /// pointer to a VarTemplateDecl. For static data members
  /// of class template specializations, this will be the
  /// MemberSpecializationInfo referring to the member variable that was
  /// instantiated or specialized. Thus, the mapping will keep track of
  /// the static data member templates from which static data members of
  /// class template specializations were instantiated.
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
  ///
  /// Given the following example:
  ///
  /// \code
  /// template<typename T>
  /// struct X {
  ///   static T value;
  /// };
  ///
  /// template<typename T>
  ///   T X<T>::value = T(17);
  ///
  /// int *x = &X<int>::value;
  /// \endcode
  ///
511
  /// This mapping will contain an entry that maps from the VarDecl for
512
  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
513
  /// class template X) and will be marked TSK_ImplicitInstantiation.
514
515
  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
  TemplateOrInstantiation;
516

517
  /// Keeps track of the declaration from which a using declaration was
518
519
  /// created during instantiation.
  ///
520
521
  /// The source and target declarations are always a UsingDecl, an
  /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
  ///
  /// For example:
  /// \code
  /// template<typename T>
  /// struct A {
  ///   void f();
  /// };
  ///
  /// template<typename T>
  /// struct B : A<T> {
  ///   using A<T>::f;
  /// };
  ///
  /// template struct B<int>;
  /// \endcode
  ///
  /// This mapping will contain an entry that maps from the UsingDecl in
  /// B<int> to the UnresolvedUsingDecl in B<T>.
540
  llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
541

542
543
544
545
546
547
548
549
550
551
552
  /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
  /// from the instantiated using-enum to the templated decl from whence it
  /// came.
  /// Note that using-enum-declarations cannot be dependent and
  /// thus will never be instantiated from an "unresolved"
  /// version thereof (as with using-declarations), so each mapping is from
  /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
  llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
      InstantiatedFromUsingEnumDecl;

  /// Simlarly maps instantiated UsingShadowDecls to their origin.
553
554
  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
    InstantiatedFromUsingShadowDecl;
555

556
  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
557

558
  /// Mapping that stores the methods overridden by a given C++
559
560
561
562
563
  /// member function.
  ///
  /// Since most C++ member functions aren't virtual and therefore
  /// don't override anything, we store the overridden functions in
  /// this map on the side rather than within the CXXMethodDecl structure.
564
  using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
565
566
  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;

567
  /// Mapping from each declaration context to its corresponding
568
569
  /// mangling numbering context (used for constructs like lambdas which
  /// need to be consistently numbered for the mangler).
570
  llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
571
      MangleNumberingContexts;
572
573
  llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
      ExtraMangleNumberingContexts;
574

575
  /// Side-table of mangling numbers for declarations which rarely
Eli Friedman's avatar
Eli Friedman committed
576
  /// need them (like static local vars).
577
578
  llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
  llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
579
580
581
  /// Mapping the associated device lambda mangling number if present.
  mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
      DeviceLambdaManglingNumbers;
582

583
  /// Mapping that stores parameterIndex values for ParmVarDecls when
584
  /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
585
  using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
Simon Pilgrim's avatar
Simon Pilgrim committed
586
587
  ParameterIndexTable ParamIndices;

588
589
  ImportDecl *FirstLocalImport = nullptr;
  ImportDecl *LastLocalImport = nullptr;
Simon Pilgrim's avatar
Simon Pilgrim committed
590

591
  TranslationUnitDecl *TUDecl = nullptr;
592
593
594
  mutable ExternCContextDecl *ExternCContext = nullptr;
  mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
  mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
595

596
  /// The associated SourceManager object.
597
  SourceManager &SourceMgr;
598

599
  /// The language options used to create the AST associated with
600
  ///  this ASTContext object.
601
  LangOptions &LangOpts;
602

603
  /// NoSanitizeList object that is used by sanitizers to decide which
604
  /// entities should not be instrumented.
605
  std::unique_ptr<NoSanitizeList> NoSanitizeL;
606

607
  /// Function filtering mechanism to determine whether a given function
608
609
610
  /// should be imbued with the XRay "always" or "never" attributes.
  std::unique_ptr<XRayFunctionFilter> XRayFilter;

611
612
613
614
  /// ProfileList object that is used by the profile instrumentation
  /// to decide which entities should be instrumented.
  std::unique_ptr<ProfileList> ProfList;

615
  /// The allocator used to create AST objects.
616
617
618
  ///
  /// AST objects are never destructed; rather, all memory associated with the
  /// AST objects will be released when the ASTContext itself is destroyed.
619
  mutable llvm::BumpPtrAllocator BumpAlloc;
620

621
  /// Allocator for partial diagnostics.
622
  PartialDiagnostic::DiagStorageAllocator DiagAllocator;
623

624
  /// The current C++ ABI.
625
  std::unique_ptr<CXXABI> ABI;
626
  CXXABI *createCXXABI(const TargetInfo &T);
627

628
  /// The logical -> physical address space map.
629
  const LangASMap *AddrSpaceMap = nullptr;
630

631
  /// Address space map mangling must be used with language specific
632
633
634
  /// address spaces (e.g. OpenCL/CUDA)
  bool AddrSpaceMapMangling;

635
636
  const TargetInfo *Target = nullptr;
  const TargetInfo *AuxTarget = nullptr;
637
  clang::PrintingPolicy PrintingPolicy;
638
  std::unique_ptr<interp::Context> InterpContext;
639
  std::unique_ptr<ParentMapContext> ParentMapCtx;
640

641
642
643
  /// Keeps track of the deallocated DeclListNodes for future reuse.
  DeclListNode *ListNodeFreeList = nullptr;

644
public:
645
  IdentifierTable &Idents;
Steve Naroff's avatar
   
Steve Naroff committed
646
  SelectorTable &Selectors;
647
  Builtin::Context &BuiltinInfo;
648
  const TranslationUnitKind TUKind;
649
  mutable DeclarationNameTable DeclarationNames;
650
  IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
651
  ASTMutationListener *Listener = nullptr;
652

653
654
655
  /// Returns the clang bytecode interpreter context.
  interp::Context &getInterpContext();

656
657
  /// Returns the dynamic AST node parent map context.
  ParentMapContext &getParentMapContext();
658

659
  // A traversal scope limits the parts of the AST visible to certain analyses.
660
  // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
661
662
  // getParents() will only observe reachable parent edges.
  //
663
664
665
666
667
668
669
670
671
672
673
674
675
  // The scope is defined by a set of "top-level" declarations which will be
  // visible under the TranslationUnitDecl.
  // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
  //
  // After setTraversalScope({foo, bar}), the exposed AST looks like:
  // TranslationUnitDecl
  //  - foo
  //    - ...
  //  - bar
  //    - ...
  // All other siblings of foo and bar are pruned from the tree.
  // (However they are still accessible via TranslationUnitDecl->decls())
  //
676
677
678
679
  // Changing the scope clears the parent cache, which is expensive to rebuild.
  std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
  void setTraversalScope(const std::vector<Decl *> &);

680
681
682
  /// Forwards to get node parents from the ParentMapContext. New callers should
  /// use ParentMapContext::getParents() directly.
  template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
683

684
685
686
  const clang::PrintingPolicy &getPrintingPolicy() const {
    return PrintingPolicy;
  }
687

688
  void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
689
690
    PrintingPolicy = Policy;
  }
Simon Pilgrim's avatar
Simon Pilgrim committed
691

692
  SourceManager& getSourceManager() { return SourceMgr; }
693
  const SourceManager& getSourceManager() const { return SourceMgr; }
694

695
696
697
698
699
700
  // Cleans up some of the data structures. This allows us to do cleanup
  // normally done in the destructor earlier. Renders much of the ASTContext
  // unusable, mostly the actual AST nodes, so should be called when we no
  // longer need access to the AST.
  void cleanup();

701
702
703
704
  llvm::BumpPtrAllocator &getAllocator() const {
    return BumpAlloc;
  }

705
  void *Allocate(size_t Size, unsigned Align = 8) const {
706
    return BumpAlloc.Allocate(Size, Align);
707
  }
708
  template <typename T> T *Allocate(size_t Num = 1) const {
709
    return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
710
  }
711
  void Deallocate(void *Ptr) const {}
Simon Pilgrim's avatar
Simon Pilgrim committed
712

713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
  /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
  /// pool.
  DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
    if (DeclListNode *Alloc = ListNodeFreeList) {
      ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>();
      Alloc->D = ND;
      Alloc->Rest = nullptr;
      return Alloc;
    }
    return new (*this) DeclListNode(ND);
  }
  /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList
  /// pool.
  void DeallocateDeclListNode(DeclListNode *N) {
    N->Rest = ListNodeFreeList;
    ListNodeFreeList = N;
  }

731
732
  /// Return the total amount of physical memory allocated for representing
  /// AST nodes and type information.
733
  size_t getASTAllocatedMemory() const {
734
735
    return BumpAlloc.getTotalMemory();
  }
736

737
738
  /// Return the total memory used for various side tables.
  size_t getSideTableAllocatedMemory() const;
Simon Pilgrim's avatar
Simon Pilgrim committed
739

740
  PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
741
    return DiagAllocator;
742
743
  }

744
  const TargetInfo &getTargetInfo() const { return *Target; }
745
746
  const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }

747
748
749
750
751
752
  /// getIntTypeForBitwidth -
  /// sets integer QualTy according to specified details:
  /// bitwidth, signed/unsigned.
  /// Returns empty type if there is no appropriate target types.
  QualType getIntTypeForBitwidth(unsigned DestWidth,
                                 unsigned Signed) const;
753

754
755
756
  /// getRealTypeForBitwidth -
  /// sets floating point QualTy according to specified bitwidth.
  /// Returns empty type if there is no appropriate target types.
757
758
  QualType getRealTypeForBitwidth(unsigned DestWidth,
                                  FloatModeKind ExplicitType) const;
759

760
  bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
Simon Pilgrim's avatar
Simon Pilgrim committed
761

762
  const LangOptions& getLangOpts() const { return LangOpts; }
763

764
765
766
767
768
769
770
771
  // If this condition is false, typo correction must be performed eagerly
  // rather than delayed in many places, as it makes use of dependent types.
  // the condition is false for clang's C-only codepath, as it doesn't support
  // dependent types yet.
  bool isDependenceAllowed() const {
    return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
  }

772
  const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
773

774
775
776
777
  const XRayFunctionFilter &getXRayFilter() const {
    return *XRayFilter;
  }

778
779
  const ProfileList &getProfileList() const { return *ProfList; }

780
  DiagnosticsEngine &getDiagnostics() const;
781

782
  FullSourceLoc getFullLoc(SourceLocation Loc) const {
783
784
    return FullSourceLoc(Loc,SourceMgr);
  }
785

786
787
788
789
790
  /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
  /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
  /// the default ABI set by the target.
  TargetCXXABI::Kind getCXXABIKind() const;

791
  /// All comments in this translation unit.
792
793
  RawCommentList Comments;

794
  /// True if comments are already loaded from ExternalASTSource.
795
  mutable bool CommentsLoaded = false;
796

797
798
799
800
801
  /// Mapping from declaration to directly attached comment.
  ///
  /// Raw comments are owned by Comments list.  This mapping is populated
  /// lazily.
  mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;