Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Serialization/ASTWriter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
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
//  This file defines the ASTWriter class, which writes AST files.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Serialization/ASTWriter.h"
14
#include "ASTCommon.h"
15
#include "ASTReaderInternals.h"
16
#include "MultiOnDiskHashTable.h"
17
#include "clang/AST/ASTContext.h"
18
#include "clang/AST/ASTUnresolvedSet.h"
19
#include "clang/AST/Attr.h"
20
#include "clang/AST/Decl.h"
21
#include "clang/AST/DeclBase.h"
22
#include "clang/AST/DeclCXX.h"
23
#include "clang/AST/DeclContextInternals.h"
24
#include "clang/AST/DeclFriend.h"
25
#include "clang/AST/DeclObjC.h"
26
#include "clang/AST/DeclTemplate.h"
27
#include "clang/AST/DeclarationName.h"
28
#include "clang/AST/Expr.h"
29
#include "clang/AST/ExprCXX.h"
30
#include "clang/AST/LambdaCapture.h"
31
#include "clang/AST/NestedNameSpecifier.h"
32
#include "clang/AST/RawCommentList.h"
33
#include "clang/AST/TemplateName.h"
34
#include "clang/AST/Type.h"
35
#include "clang/AST/TypeLocVisitor.h"
36
#include "clang/Basic/Diagnostic.h"
37
#include "clang/Basic/DiagnosticOptions.h"
38
#include "clang/Basic/FileManager.h"
39
#include "clang/Basic/FileSystemOptions.h"
40
#include "clang/Basic/IdentifierTable.h"
41
#include "clang/Basic/LLVM.h"
42
#include "clang/Basic/Lambda.h"
43
#include "clang/Basic/LangOptions.h"
44
#include "clang/Basic/Module.h"
45
#include "clang/Basic/ObjCRuntime.h"
46
#include "clang/Basic/OpenCLOptions.h"
47
#include "clang/Basic/SourceLocation.h"
48
#include "clang/Basic/SourceManager.h"
49
#include "clang/Basic/SourceManagerInternals.h"
50
#include "clang/Basic/Specifiers.h"
51
#include "clang/Basic/TargetInfo.h"
52
#include "clang/Basic/TargetOptions.h"
53
#include "clang/Basic/Version.h"
54
#include "clang/Lex/HeaderSearch.h"
55
#include "clang/Lex/HeaderSearchOptions.h"
56
#include "clang/Lex/MacroInfo.h"
57
#include "clang/Lex/ModuleMap.h"
58
#include "clang/Lex/PreprocessingRecord.h"
59
#include "clang/Lex/Preprocessor.h"
60
#include "clang/Lex/PreprocessorOptions.h"
61
#include "clang/Lex/Token.h"
62
#include "clang/Sema/IdentifierResolver.h"
63
#include "clang/Sema/ObjCMethodList.h"
64
#include "clang/Sema/Sema.h"
65
#include "clang/Sema/Weak.h"
66
#include "clang/Serialization/ASTReader.h"
67
#include "clang/Serialization/InMemoryModuleCache.h"
68
#include "clang/Serialization/Module.h"
69
#include "clang/Serialization/ModuleFileExtension.h"
70
#include "clang/Serialization/SerializationDiagnostic.h"
71
#include "llvm/ADT/APFloat.h"
72
#include "llvm/ADT/APInt.h"
73
#include "llvm/ADT/APSInt.h"
74
#include "llvm/ADT/ArrayRef.h"
75
#include "llvm/ADT/DenseMap.h"
76
#include "llvm/ADT/Hashing.h"
77
#include "llvm/ADT/Optional.h"
78
#include "llvm/ADT/PointerIntPair.h"
79
#include "llvm/ADT/STLExtras.h"
80
#include "llvm/ADT/ScopeExit.h"
81
#include "llvm/ADT/SmallSet.h"
82
#include "llvm/ADT/SmallString.h"
83
#include "llvm/ADT/SmallVector.h"
84
#include "llvm/ADT/StringMap.h"
85
#include "llvm/ADT/StringRef.h"
86
#include "llvm/Bitstream/BitCodes.h"
87
#include "llvm/Bitstream/BitstreamWriter.h"
88
#include "llvm/Support/Casting.h"
89
#include "llvm/Support/Compression.h"
90
#include "llvm/Support/DJB.h"
91
#include "llvm/Support/Endian.h"
92
#include "llvm/Support/EndianStream.h"
93
#include "llvm/Support/Error.h"
94
#include "llvm/Support/ErrorHandling.h"
95
#include "llvm/Support/MemoryBuffer.h"
96
#include "llvm/Support/OnDiskHashTable.h"
97
#include "llvm/Support/Path.h"
98
#include "llvm/Support/SHA1.h"
99
#include "llvm/Support/VersionTuple.h"
100
#include "llvm/Support/raw_ostream.h"
101
#include <algorithm>
102
#include <cassert>
103
#include <cstdint>
104
#include <cstdlib>
105
#include <cstring>
106
#include <ctime>
107
#include <deque>
108
#include <limits>
109
#include <memory>
110
#include <queue>
111
#include <tuple>
112
#include <utility>
113
#include <vector>
114
115
using namespace clang;
116
using namespace clang::serialization;
117
118
template <typename T, typename Allocator>
119
21.9k
static StringRef bytes(const std::vector<T, Allocator> &v) {
120
21.9k
  if (v.empty()) 
return StringRef()1.38k
;
121
20.5k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
122
20.5k
                         sizeof(T) * v.size());
123
20.5k
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned long long, std::__1::allocator<unsigned long long> >(std::__1::vector<unsigned long long, std::__1::allocator<unsigned long long> > const&)
Line
Count
Source
119
3.61k
static StringRef bytes(const std::vector<T, Allocator> &v) {
120
3.61k
  if (v.empty()) 
return StringRef()0
;
121
3.61k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
122
3.61k
                         sizeof(T) * v.size());
123
3.61k
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned int, std::__1::allocator<unsigned int> >(std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > const&)
Line
Count
Source
119
14.6k
static StringRef bytes(const std::vector<T, Allocator> &v) {
120
14.6k
  if (v.empty()) 
return StringRef()1.24k
;
121
13.4k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
122
13.4k
                         sizeof(T) * v.size());
123
13.4k
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::PPSkippedRange, std::__1::allocator<clang::serialization::PPSkippedRange> >(std::__1::vector<clang::serialization::PPSkippedRange, std::__1::allocator<clang::serialization::PPSkippedRange> > const&)
Line
Count
Source
119
31
static StringRef bytes(const std::vector<T, Allocator> &v) {
120
31
  if (v.empty()) 
return StringRef()0
;
121
31
  return StringRef(reinterpret_cast<const char*>(&v[0]),
122
31
                         sizeof(T) * v.size());
123
31
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::DeclOffset, std::__1::allocator<clang::serialization::DeclOffset> >(std::__1::vector<clang::serialization::DeclOffset, std::__1::allocator<clang::serialization::DeclOffset> > const&)
Line
Count
Source
119
3.61k
static StringRef bytes(const std::vector<T, Allocator> &v) {
120
3.61k
  if (v.empty()) 
return StringRef()142
;
121
3.47k
  return StringRef(reinterpret_cast<const char*>(&v[0]),
122
3.47k
                         sizeof(T) * v.size());
123
3.47k
}
124
125
template <typename T>
126
81.3k
static StringRef bytes(const SmallVectorImpl<T> &v) {
127
81.3k
  return StringRef(reinterpret_cast<const char*>(v.data()),
128
81.3k
                         sizeof(T) * v.size());
129
81.3k
}
ASTWriter.cpp:llvm::StringRef bytes<clang::serialization::PPEntityOffset>(llvm::SmallVectorImpl<clang::serialization::PPEntityOffset> const&)
Line
Count
Source
126
188
static StringRef bytes(const SmallVectorImpl<T> &v) {
127
188
  return StringRef(reinterpret_cast<const char*>(v.data()),
128
188
                         sizeof(T) * v.size());
129
188
}
ASTWriter.cpp:llvm::StringRef bytes<unsigned int>(llvm::SmallVectorImpl<unsigned int> const&)
Line
Count
Source
126
81.1k
static StringRef bytes(const SmallVectorImpl<T> &v) {
127
81.1k
  return StringRef(reinterpret_cast<const char*>(v.data()),
128
81.1k
                         sizeof(T) * v.size());
129
81.1k
}
130
131
//===----------------------------------------------------------------------===//
132
// Type serialization
133
//===----------------------------------------------------------------------===//
134
135
namespace clang {
136
137
  class ASTTypeWriter {
138
    ASTWriter &Writer;
139
    ASTRecordWriter Record;
140
141
    /// Type code that corresponds to the record generated.
142
    TypeCode Code = static_cast<TypeCode>(0);
143
144
    /// Abbreviation to use for the record, if any.
145
    unsigned AbbrevToUse = 0;
146
147
  public:
148
    ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
149
155k
      : Writer(Writer), Record(Writer, Record) {}
150
151
155k
    uint64_t Emit() {
152
155k
      return Record.Emit(Code, AbbrevToUse);
153
155k
    }
154
155
155k
    void Visit(QualType T) {
156
155k
      if (T.hasLocalNonFastQualifiers()) {
157
2.50k
        Qualifiers Qs = T.getLocalQualifiers();
158
2.50k
        Record.AddTypeRef(T.getLocalUnqualifiedType());
159
2.50k
        Record.push_back(Qs.getAsOpaqueValue());
160
2.50k
        Code = TYPE_EXT_QUAL;
161
2.50k
        AbbrevToUse = Writer.TypeExtQualAbbrev;
162
153k
      } else {
163
153k
        switch (T->getTypeClass()) {
164
153k
          // For all of the concrete, non-dependent types, call the
165
153k
          // appropriate visitor function.
166
153k
#define TYPE(Class, Base) \
167
153k
        case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
168
153k
#define ABSTRACT_TYPE(Class, Base)
169
153k
#include 
"clang/AST/TypeNodes.def"0
170
153k
        }
171
153k
      }
172
155k
    }
173
174
    void VisitArrayType(const ArrayType *T);
175
    void VisitFunctionType(const FunctionType *T);
176
    void VisitTagType(const TagType *T);
177
178
#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
179
#define ABSTRACT_TYPE(Class, Base)
180
#include "clang/AST/TypeNodes.def"
181
  };
182
183
} // namespace clang
184
185
0
void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
186
0
  llvm_unreachable("Built-in types are never serialized");
187
0
}
188
189
45
void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
190
45
  Record.AddTypeRef(T->getElementType());
191
45
  Code = TYPE_COMPLEX;
192
45
}
193
194
37.4k
void ASTTypeWriter::VisitPointerType(const PointerType *T) {
195
37.4k
  Record.AddTypeRef(T->getPointeeType());
196
37.4k
  Code = TYPE_POINTER;
197
37.4k
}
198
199
105
void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
200
105
  Record.AddTypeRef(T->getOriginalType());
201
105
  Code = TYPE_DECAYED;
202
105
}
203
204
0
void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
205
0
  Record.AddTypeRef(T->getOriginalType());
206
0
  Record.AddTypeRef(T->getAdjustedType());
207
0
  Code = TYPE_ADJUSTED;
208
0
}
209
210
46
void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
211
46
  Record.AddTypeRef(T->getPointeeType());
212
46
  Code = TYPE_BLOCK_POINTER;
213
46
}
214
215
6.84k
void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
216
6.84k
  Record.AddTypeRef(T->getPointeeTypeAsWritten());
217
6.84k
  Record.push_back(T->isSpelledAsLValue());
218
6.84k
  Code = TYPE_LVALUE_REFERENCE;
219
6.84k
}
220
221
1.26k
void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
222
1.26k
  Record.AddTypeRef(T->getPointeeTypeAsWritten());
223
1.26k
  Code = TYPE_RVALUE_REFERENCE;
224
1.26k
}
225
226
45
void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
227
45
  Record.AddTypeRef(T->getPointeeType());
228
45
  Record.AddTypeRef(QualType(T->getClass(), 0));
229
45
  Code = TYPE_MEMBER_POINTER;
230
45
}
231
232
5.42k
void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
233
5.42k
  Record.AddTypeRef(T->getElementType());
234
5.42k
  Record.push_back(T->getSizeModifier()); // FIXME: stable values
235
5.42k
  Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
236
5.42k
}
237
238
2.68k
void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
239
2.68k
  VisitArrayType(T);
240
2.68k
  Record.AddAPInt(T->getSize());
241
2.68k
  Code = TYPE_CONSTANT_ARRAY;
242
2.68k
}
243
244
1.27k
void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
245
1.27k
  VisitArrayType(T);
246
1.27k
  Code = TYPE_INCOMPLETE_ARRAY;
247
1.27k
}
248
249
975
void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
250
975
  VisitArrayType(T);
251
975
  Record.AddSourceLocation(T->getLBracketLoc());
252
975
  Record.AddSourceLocation(T->getRBracketLoc());
253
975
  Record.AddStmt(T->getSizeExpr());
254
975
  Code = TYPE_VARIABLE_ARRAY;
255
975
}
256
257
826
void ASTTypeWriter::VisitVectorType(const VectorType *T) {
258
826
  Record.AddTypeRef(T->getElementType());
259
826
  Record.push_back(T->getNumElements());
260
826
  Record.push_back(T->getVectorKind());
261
826
  Code = TYPE_VECTOR;
262
826
}
263
264
319
void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
265
319
  VisitVectorType(T);
266
319
  Code = TYPE_EXT_VECTOR;
267
319
}
268
269
37.4k
void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
270
37.4k
  Record.AddTypeRef(T->getReturnType());
271
37.4k
  FunctionType::ExtInfo C = T->getExtInfo();
272
37.4k
  Record.push_back(C.getNoReturn());
273
37.4k
  Record.push_back(C.getHasRegParm());
274
37.4k
  Record.push_back(C.getRegParm());
275
37.4k
  // FIXME: need to stabilize encoding of calling convention...
276
37.4k
  Record.push_back(C.getCC());
277
37.4k
  Record.push_back(C.getProducesResult());
278
37.4k
  Record.push_back(C.getNoCallerSavedRegs());
279
37.4k
  Record.push_back(C.getNoCfCheck());
280
37.4k
281
37.4k
  if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
282
0
    AbbrevToUse = 0;
283
37.4k
}
284
285
108
void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
286
108
  VisitFunctionType(T);
287
108
  Code = TYPE_FUNCTION_NO_PROTO;
288
108
}
289
290
static void addExceptionSpec(const FunctionProtoType *T,
291
37.4k
                             ASTRecordWriter &Record) {
292
37.4k
  Record.push_back(T->getExceptionSpecType());
293
37.4k
  if (T->getExceptionSpecType() == EST_Dynamic) {
294
3
    Record.push_back(T->getNumExceptions());
295
10
    for (unsigned I = 0, N = T->getNumExceptions(); I != N; 
++I7
)
296
7
      Record.AddTypeRef(T->getExceptionType(I));
297
37.3k
  } else if (isComputedNoexcept(T->getExceptionSpecType())) {
298
37
    Record.AddStmt(T->getNoexceptExpr());
299
37.3k
  } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
300
2
    Record.AddDeclRef(T->getExceptionSpecDecl());
301
2
    Record.AddDeclRef(T->getExceptionSpecTemplate());
302
37.3k
  } else if (T->getExceptionSpecType() == EST_Unevaluated) {
303
3.34k
    Record.AddDeclRef(T->getExceptionSpecDecl());
304
3.34k
  }
305
37.4k
}
306
307
37.3k
void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
308
37.3k
  VisitFunctionType(T);
309
37.3k
310
37.3k
  Record.push_back(T->isVariadic());
311
37.3k
  Record.push_back(T->hasTrailingReturn());
312
37.3k
  Record.push_back(T->getMethodQuals().getAsOpaqueValue());
313
37.3k
  Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
314
37.3k
  addExceptionSpec(T, Record);
315
37.3k
316
37.3k
  Record.push_back(T->getNumParams());
317
96.2k
  for (unsigned I = 0, N = T->getNumParams(); I != N; 
++I58.8k
)
318
58.8k
    Record.AddTypeRef(T->getParamType(I));
319
37.3k
320
37.3k
  if (T->hasExtParameterInfos()) {
321
4
    for (unsigned I = 0, N = T->getNumParams(); I != N; 
++I2
)
322
2
      Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
323
2
  }
324
37.3k
325
37.3k
  if (T->isVariadic() || 
T->hasTrailingReturn()35.9k
||
T->getMethodQuals()35.8k
||
326
37.3k
      
T->getRefQualifier()35.2k
||
T->getExceptionSpecType() != EST_None35.2k
||
327
37.3k
      
T->hasExtParameterInfos()30.0k
)
328
7.28k
    AbbrevToUse = 0;
329
37.3k
330
37.3k
  Code = TYPE_FUNCTION_PROTO;
331
37.3k
}
332
333
7
void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
334
7
  Record.AddDeclRef(T->getDecl());
335
7
  Code = TYPE_UNRESOLVED_USING;
336
7
}
337
338
9.35k
void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
339
9.35k
  Record.AddDeclRef(T->getDecl());
340
9.35k
  assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
341
9.35k
  Record.AddTypeRef(T->getCanonicalTypeInternal());
342
9.35k
  Code = TYPE_TYPEDEF;
343
9.35k
}
344
345
54
void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
346
54
  Record.AddStmt(T->getUnderlyingExpr());
347
54
  Code = TYPE_TYPEOF_EXPR;
348
54
}
349
350
18
void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
351
18
  Record.AddTypeRef(T->getUnderlyingType());
352
18
  Code = TYPE_TYPEOF;
353
18
}
354
355
121
void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
356
121
  Record.AddTypeRef(T->getUnderlyingType());
357
121
  Record.AddStmt(T->getUnderlyingExpr());
358
121
  Code = TYPE_DECLTYPE;
359
121
}
360
361
13
void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
362
13
  Record.AddTypeRef(T->getBaseType());
363
13
  Record.AddTypeRef(T->getUnderlyingType());
364
13
  Record.push_back(T->getUTTKind());
365
13
  Code = TYPE_UNARY_TRANSFORM;
366
13
}
367
368
223
void ASTTypeWriter::VisitAutoType(const AutoType *T) {
369
223
  Record.AddTypeRef(T->getDeducedType());
370
223
  Record.push_back((unsigned)T->getKeyword());
371
223
  if (T->getDeducedType().isNull())
372
46
    Record.push_back(T->containsUnexpandedParameterPack() ? 
20
:
373
46
                     T->isDependentType() ? 
138
:
08
);
374
223
  Code = TYPE_AUTO;
375
223
}
376
377
void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
378
10
    const DeducedTemplateSpecializationType *T) {
379
10
  Record.AddTemplateName(T->getTemplateName());
380
10
  Record.AddTypeRef(T->getDeducedType());
381
10
  if (T->getDeducedType().isNull())
382
4
    Record.push_back(T->isDependentType());
383
10
  Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
384
10
}
385
386
31.5k
void ASTTypeWriter::VisitTagType(const TagType *T) {
387
31.5k
  Record.push_back(T->isDependentType());
388
31.5k
  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
389
31.5k
  assert(!T->isBeingDefined() &&
390
31.5k
         "Cannot serialize in the middle of a type definition");
391
31.5k
}
392
393
31.2k
void ASTTypeWriter::VisitRecordType(const RecordType *T) {
394
31.2k
  VisitTagType(T);
395
31.2k
  Code = TYPE_RECORD;
396
31.2k
}
397
398
307
void ASTTypeWriter::VisitEnumType(const EnumType *T) {
399
307
  VisitTagType(T);
400
307
  Code = TYPE_ENUM;
401
307
}
402
403
25
void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
404
25
  Record.AddTypeRef(T->getModifiedType());
405
25
  Record.AddTypeRef(T->getEquivalentType());
406
25
  Record.push_back(T->getAttrKind());
407
25
  Code = TYPE_ATTRIBUTED;
408
25
}
409
410
void
411
ASTTypeWriter::VisitSubstTemplateTypeParmType(
412
1.97k
                                        const SubstTemplateTypeParmType *T) {
413
1.97k
  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
414
1.97k
  Record.AddTypeRef(T->getReplacementType());
415
1.97k
  Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
416
1.97k
}
417
418
void
419
ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
420
3
                                      const SubstTemplateTypeParmPackType *T) {
421
3
  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
422
3
  Record.AddTemplateArgument(T->getArgumentPack());
423
3
  Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
424
3
}
425
426
void
427
ASTTypeWriter::VisitTemplateSpecializationType(
428
10.3k
                                       const TemplateSpecializationType *T) {
429
10.3k
  Record.push_back(T->isDependentType());
430
10.3k
  Record.AddTemplateName(T->getTemplateName());
431
10.3k
  Record.push_back(T->getNumArgs());
432
10.3k
  for (const auto &ArgI : *T)
433
12.1k
    Record.AddTemplateArgument(ArgI);
434
10.3k
  Record.AddTypeRef(T->isTypeAlias() ? 
T->getAliasedType()27
435
10.3k
                                     : T->isCanonicalUnqualified()
436
10.3k
                                           ? 
QualType()2.03k
437
10.3k
                                           : 
T->getCanonicalTypeInternal()8.32k
);
438
10.3k
  Code = TYPE_TEMPLATE_SPECIALIZATION;
439
10.3k
}
440
441
void
442
492
ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
443
492
  VisitArrayType(T);
444
492
  Record.AddStmt(T->getSizeExpr());
445
492
  Record.AddSourceRange(T->getBracketsRange());
446
492
  Code = TYPE_DEPENDENT_SIZED_ARRAY;
447
492
}
448
449
void
450
ASTTypeWriter::VisitDependentSizedExtVectorType(
451
7
                                        const DependentSizedExtVectorType *T) {
452
7
  Record.AddTypeRef(T->getElementType());
453
7
  Record.AddStmt(T->getSizeExpr());
454
7
  Record.AddSourceLocation(T->getAttributeLoc());
455
7
  Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
456
7
}
457
458
0
void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) {
459
0
  Record.AddTypeRef(T->getElementType());
460
0
  Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
461
0
  Record.AddSourceLocation(T->getAttributeLoc());
462
0
  Record.push_back(T->getVectorKind());
463
0
  Code = TYPE_DEPENDENT_SIZED_VECTOR;
464
0
}
465
466
void
467
ASTTypeWriter::VisitDependentAddressSpaceType(
468
10
    const DependentAddressSpaceType *T) {
469
10
  Record.AddTypeRef(T->getPointeeType());
470
10
  Record.AddStmt(T->getAddrSpaceExpr());
471
10
  Record.AddSourceLocation(T->getAttributeLoc());
472
10
  Code = TYPE_DEPENDENT_ADDRESS_SPACE;
473
10
}
474
475
void
476
5.30k
ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
477
5.30k
  Record.push_back(T->getDepth());
478
5.30k
  Record.push_back(T->getIndex());
479
5.30k
  Record.push_back(T->isParameterPack());
480
5.30k
  Record.AddDeclRef(T->getDecl());
481
5.30k
  Code = TYPE_TEMPLATE_TYPE_PARM;
482
5.30k
}
483
484
void
485
186
ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
486
186
  Record.push_back(T->getKeyword());
487
186
  Record.AddNestedNameSpecifier(T->getQualifier());
488
186
  Record.AddIdentifierRef(T->getIdentifier());
489
186
  Record.AddTypeRef(
490
186
      T->isCanonicalUnqualified() ? 
QualType()88
:
T->getCanonicalTypeInternal()98
);
491
186
  Code = TYPE_DEPENDENT_NAME;
492
186
}
493
494
void
495
ASTTypeWriter::VisitDependentTemplateSpecializationType(
496
7
                                const DependentTemplateSpecializationType *T) {
497
7
  Record.push_back(T->getKeyword());
498
7
  Record.AddNestedNameSpecifier(T->getQualifier());
499
7
  Record.AddIdentifierRef(T->getIdentifier());
500
7
  Record.push_back(T->getNumArgs());
501
7
  for (const auto &I : *T)
502
7
    Record.AddTemplateArgument(I);
503
7
  Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
504
7
}
505
506
68
void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
507
68
  Record.AddTypeRef(T->getPattern());
508
68
  if (Optional<unsigned> NumExpansions = T->getNumExpansions())
509
0
    Record.push_back(*NumExpansions + 1);
510
68
  else
511
68
    Record.push_back(0);
512
68
  Code = TYPE_PACK_EXPANSION;
513
68
}
514
515
95
void ASTTypeWriter::VisitParenType(const ParenType *T) {
516
95
  Record.AddTypeRef(T->getInnerType());
517
95
  Code = TYPE_PAREN;
518
95
}
519
520
4
void ASTTypeWriter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
521
4
  Record.AddTypeRef(T->getUnderlyingType());
522
4
  Record.AddIdentifierRef(T->getMacroIdentifier());
523
4
  Code = TYPE_MACRO_QUALIFIED;
524
4
}
525
526
1.62k
void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
527
1.62k
  Record.push_back(T->getKeyword());
528
1.62k
  Record.AddNestedNameSpecifier(T->getQualifier());
529
1.62k
  Record.AddTypeRef(T->getNamedType());
530
1.62k
  Record.AddDeclRef(T->getOwnedTagDecl());
531
1.62k
  Code = TYPE_ELABORATED;
532
1.62k
}
533
534
1.92k
void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
535
1.92k
  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
536
1.92k
  Record.AddTypeRef(T->getInjectedSpecializationType());
537
1.92k
  Code = TYPE_INJECTED_CLASS_NAME;
538
1.92k
}
539
540
327
void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
541
327
  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
542
327
  Code = TYPE_OBJC_INTERFACE;
543
327
}
544
545
24
void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
546
24
  Record.AddDeclRef(T->getDecl());
547
24
  Record.push_back(T->getNumProtocols());
548
24
  for (const auto *I : T->quals())
549
7
    Record.AddDeclRef(I);
550
24
  Code = TYPE_OBJC_TYPE_PARAM;
551
24
}
552
553
148
void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
554
148
  Record.AddTypeRef(T->getBaseType());
555
148
  Record.push_back(T->getTypeArgsAsWritten().size());
556
148
  for (auto TypeArg : T->getTypeArgsAsWritten())
557
9
    Record.AddTypeRef(TypeArg);
558
148
  Record.push_back(T->getNumProtocols());
559
148
  for (const auto *I : T->quals())
560
18
    Record.AddDeclRef(I);
561
148
  Record.push_back(T->isKindOfTypeAsWritten());
562
148
  Code = TYPE_OBJC_OBJECT;
563
148
}
564
565
void
566
226
ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
567
226
  Record.AddTypeRef(T->getPointeeType());
568
226
  Code = TYPE_OBJC_OBJECT_POINTER;
569
226
}
570
571
void
572
84
ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
573
84
  Record.AddTypeRef(T->getValueType());
574
84
  Code = TYPE_ATOMIC;
575
84
}
576
577
void
578
7
ASTTypeWriter::VisitPipeType(const PipeType *T) {
579
7
  Record.AddTypeRef(T->getElementType());
580
7
  Record.push_back(T->isReadOnly());
581
7
  Code = TYPE_PIPE;
582
7
}
583
584
namespace {
585
586
class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
587
  ASTRecordWriter &Record;
588
589
public:
590
452k
  TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
591
592
#define ABSTRACT_TYPELOC(CLASS, PARENT)
593
#define TYPELOC(CLASS, PARENT) \
594
    void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
595
#include "clang/AST/TypeLocNodes.def"
596
597
  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
598
  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
599
};
600
601
} // namespace
602
603
83.3k
void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
604
83.3k
  // nothing to do
605
83.3k
}
606
607
135k
void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
608
135k
  Record.AddSourceLocation(TL.getBuiltinLoc());
609
135k
  if (TL.needsExtraLocalData()) {
610
110k
    Record.push_back(TL.getWrittenTypeSpec());
611
110k
    Record.push_back(TL.getWrittenSignSpec());
612
110k
    Record.push_back(TL.getWrittenWidthSpec());
613
110k
    Record.push_back(TL.hasModeAttr());
614
110k
  }
615
135k
}
616
617
99
void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
618
99
  Record.AddSourceLocation(TL.getNameLoc());
619
99
}
620
621
23.1k
void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
622
23.1k
  Record.AddSourceLocation(TL.getStarLoc());
623
23.1k
}
624
625
142
void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
626
142
  // nothing to do
627
142
}
628
629
0
void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
630
0
  // nothing to do
631
0
}
632
633
56
void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
634
56
  Record.AddSourceLocation(TL.getCaretLoc());
635
56
}
636
637
13.3k
void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
638
13.3k
  Record.AddSourceLocation(TL.getAmpLoc());
639
13.3k
}
640
641
163
void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
642
163
  Record.AddSourceLocation(TL.getAmpAmpLoc());
643
163
}
644
645
41
void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
646
41
  Record.AddSourceLocation(TL.getStarLoc());
647
41
  Record.AddTypeSourceInfo(TL.getClassTInfo());
648
41
}
649
650
10.7k
void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
651
10.7k
  Record.AddSourceLocation(TL.getLBracketLoc());
652
10.7k
  Record.AddSourceLocation(TL.getRBracketLoc());
653
10.7k
  Record.push_back(TL.getSizeExpr() ? 
13.63k
:
07.12k
);
654
10.7k
  if (TL.getSizeExpr())
655
3.63k
    Record.AddStmt(TL.getSizeExpr());
656
10.7k
}
657
658
5.55k
void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
659
5.55k
  VisitArrayTypeLoc(TL);
660
5.55k
}
661
662
1.29k
void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
663
1.29k
  VisitArrayTypeLoc(TL);
664
1.29k
}
665
666
3.40k
void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
667
3.40k
  VisitArrayTypeLoc(TL);
668
3.40k
}
669
670
void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
671
498
                                            DependentSizedArrayTypeLoc TL) {
672
498
  VisitArrayTypeLoc(TL);
673
498
}
674
675
void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
676
10
    DependentAddressSpaceTypeLoc TL) {
677
10
  Record.AddSourceLocation(TL.getAttrNameLoc());
678
10
  SourceRange range = TL.getAttrOperandParensRange();
679
10
  Record.AddSourceLocation(range.getBegin());
680
10
  Record.AddSourceLocation(range.getEnd());
681
10
  Record.AddStmt(TL.getAttrExprOperand());
682
10
}
683
684
void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
685
7
                                        DependentSizedExtVectorTypeLoc TL) {
686
7
  Record.AddSourceLocation(TL.getNameLoc());
687
7
}
688
689
475
void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
690
475
  Record.AddSourceLocation(TL.getNameLoc());
691
475
}
692
693
void TypeLocWriter::VisitDependentVectorTypeLoc(
694
0
    DependentVectorTypeLoc TL) {
695
0
  Record.AddSourceLocation(TL.getNameLoc());
696
0
}
697
698
240
void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
699
240
  Record.AddSourceLocation(TL.getNameLoc());
700
240
}
701
702
93.2k
void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
703
93.2k
  Record.AddSourceLocation(TL.getLocalRangeBegin());
704
93.2k
  Record.AddSourceLocation(TL.getLParenLoc());
705
93.2k
  Record.AddSourceLocation(TL.getRParenLoc());
706
93.2k
  Record.AddSourceRange(TL.getExceptionSpecRange());
707
93.2k
  Record.AddSourceLocation(TL.getLocalRangeEnd());
708
242k
  for (unsigned i = 0, e = TL.getNumParams(); i != e; 
++i149k
)
709
149k
    Record.AddDeclRef(TL.getParam(i));
710
93.2k
}
711
712
93.1k
void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
713
93.1k
  VisitFunctionTypeLoc(TL);
714
93.1k
}
715
716
144
void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
717
144
  VisitFunctionTypeLoc(TL);
718
144
}
719
720
7
void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
721
7
  Record.AddSourceLocation(TL.getNameLoc());
722
7
}
723
724
280k
void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
725
280k
  Record.AddSourceLocation(TL.getNameLoc());
726
280k
}
727
728
8
void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
729
8
  if (TL.getNumProtocols()) {
730
6
    Record.AddSourceLocation(TL.getProtocolLAngleLoc());
731
6
    Record.AddSourceLocation(TL.getProtocolRAngleLoc());
732
6
  }
733
15
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; 
++i7
)
734
7
    Record.AddSourceLocation(TL.getProtocolLoc(i));
735
8
}
736
737
54
void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
738
54
  Record.AddSourceLocation(TL.getTypeofLoc());
739
54
  Record.AddSourceLocation(TL.getLParenLoc());
740
54
  Record.AddSourceLocation(TL.getRParenLoc());
741
54
}
742
743
18
void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
744
18
  Record.AddSourceLocation(TL.getTypeofLoc());
745
18
  Record.AddSourceLocation(TL.getLParenLoc());
746
18
  Record.AddSourceLocation(TL.getRParenLoc());
747
18
  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
748
18
}
749
750
107
void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
751
107
  Record.AddSourceLocation(TL.getNameLoc());
752
107
}
753
754
13
void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
755
13
  Record.AddSourceLocation(TL.getKWLoc());
756
13
  Record.AddSourceLocation(TL.getLParenLoc());
757
13
  Record.AddSourceLocation(TL.getRParenLoc());
758
13
  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
759
13
}
760
761
399
void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
762
399
  Record.AddSourceLocation(TL.getNameLoc());
763
399
}
764
765
void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
766
6
    DeducedTemplateSpecializationTypeLoc TL) {
767
6
  Record.AddSourceLocation(TL.getTemplateNameLoc());
768
6
}
769
770
8.97k
void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
771
8.97k
  Record.AddSourceLocation(TL.getNameLoc());
772
8.97k
}
773
774
171
void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
775
171
  Record.AddSourceLocation(TL.getNameLoc());
776
171
}
777
778
33
void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
779
33
  Record.AddAttr(TL.getAttr());
780
33
}
781
782
10.0k
void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
783
10.0k
  Record.AddSourceLocation(TL.getNameLoc());
784
10.0k
}
785
786
void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
787
4.09k
                                            SubstTemplateTypeParmTypeLoc TL) {
788
4.09k
  Record.AddSourceLocation(TL.getNameLoc());
789
4.09k
}
790
791
void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
792
0
                                          SubstTemplateTypeParmPackTypeLoc TL) {
793
0
  Record.AddSourceLocation(TL.getNameLoc());
794
0
}
795
796
void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
797
9.88k
                                           TemplateSpecializationTypeLoc TL) {
798
9.88k
  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
799
9.88k
  Record.AddSourceLocation(TL.getTemplateNameLoc());
800
9.88k
  Record.AddSourceLocation(TL.getLAngleLoc());
801
9.88k
  Record.AddSourceLocation(TL.getRAngleLoc());
802
20.5k
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; 
++i10.7k
)
803
10.7k
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
804
10.7k
                                      TL.getArgLoc(i).getLocInfo());
805
9.88k
}
806
807
164
void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
808
164
  Record.AddSourceLocation(TL.getLParenLoc());
809
164
  Record.AddSourceLocation(TL.getRParenLoc());
810
164
}
811
812
4
void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
813
4
  Record.AddSourceLocation(TL.getExpansionLoc());
814
4
}
815
816
1.92k
void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
817
1.92k
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
818
1.92k
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
819
1.92k
}
820
821
2.08k
void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
822
2.08k
  Record.AddSourceLocation(TL.getNameLoc());
823
2.08k
}
824
825
104
void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
826
104
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
827
104
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
828
104
  Record.AddSourceLocation(TL.getNameLoc());
829
104
}
830
831
void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
832
7
       DependentTemplateSpecializationTypeLoc TL) {
833
7
  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
834
7
  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
835
7
  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
836
7
  Record.AddSourceLocation(TL.getTemplateNameLoc());
837
7
  Record.AddSourceLocation(TL.getLAngleLoc());
838
7
  Record.AddSourceLocation(TL.getRAngleLoc());
839
14
  for (unsigned I = 0, E = TL.getNumArgs(); I != E; 
++I7
)
840
7
    Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
841
7
                                      TL.getArgLoc(I).getLocInfo());
842
7
}
843
844
45
void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
845
45
  Record.AddSourceLocation(TL.getEllipsisLoc());
846
45
}
847
848
188
void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
849
188
  Record.AddSourceLocation(TL.getNameLoc());
850
188
}
851
852
25
void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
853
25
  Record.push_back(TL.hasBaseTypeAsWritten());
854
25
  Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
855
25
  Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
856
35
  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; 
++i10
)
857
10
    Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
858
25
  Record.AddSourceLocation(TL.getProtocolLAngleLoc());
859
25
  Record.AddSourceLocation(TL.getProtocolRAngleLoc());
860
44
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; 
++i19
)
861
19
    Record.AddSourceLocation(TL.getProtocolLoc(i));
862
25
}
863
864
138
void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
865
138
  Record.AddSourceLocation(TL.getStarLoc());
866
138
}
867
868
140
void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
869
140
  Record.AddSourceLocation(TL.getKWLoc());
870
140
  Record.AddSourceLocation(TL.getLParenLoc());
871
140
  Record.AddSourceLocation(TL.getRParenLoc());
872
140
}
873
874
12
void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
875
12
  Record.AddSourceLocation(TL.getKWLoc());
876
12
}
877
878
3.61k
void ASTWriter::WriteTypeAbbrevs() {
879
3.61k
  using namespace llvm;
880
3.61k
881
3.61k
  std::shared_ptr<BitCodeAbbrev> Abv;
882
3.61k
883
3.61k
  // Abbreviation for TYPE_EXT_QUAL
884
3.61k
  Abv = std::make_shared<BitCodeAbbrev>();
885
3.61k
  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
886
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
887
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
888
3.61k
  TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
889
3.61k
890
3.61k
  // Abbreviation for TYPE_FUNCTION_PROTO
891
3.61k
  Abv = std::make_shared<BitCodeAbbrev>();
892
3.61k
  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
893
3.61k
  // FunctionType
894
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // ReturnType
895
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
896
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // HasRegParm
897
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // RegParm
898
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
899
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // ProducesResult
900
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // NoCallerSavedRegs
901
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // NoCfCheck
902
3.61k
  // FunctionProtoType
903
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // IsVariadic
904
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // HasTrailingReturn
905
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // TypeQuals
906
3.61k
  Abv->Add(BitCodeAbbrevOp(0));                         // RefQualifier
907
3.61k
  Abv->Add(BitCodeAbbrevOp(EST_None));                  // ExceptionSpec
908
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // NumParams
909
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
910
3.61k
  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Params
911
3.61k
  TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
912
3.61k
}
913
914
//===----------------------------------------------------------------------===//
915
// ASTWriter Implementation
916
//===----------------------------------------------------------------------===//
917
918
static void EmitBlockID(unsigned ID, const char *Name,
919
                        llvm::BitstreamWriter &Stream,
920
43.4k
                        ASTWriter::RecordDataImpl &Record) {
921
43.4k
  Record.clear();
922
43.4k
  Record.push_back(ID);
923
43.4k
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
924
43.4k
925
43.4k
  // Emit the block name if present.
926
43.4k
  if (!Name || Name[0] == 0)
927
0
    return;
928
43.4k
  Record.clear();
929
752k
  while (*Name)
930
709k
    Record.push_back(*Name++);
931
43.4k
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
932
43.4k
}
933
934
static void EmitRecordID(unsigned ID, const char *Name,
935
                         llvm::BitstreamWriter &Stream,
936
1.23M
                         ASTWriter::RecordDataImpl &Record) {
937
1.23M
  Record.clear();
938
1.23M
  Record.push_back(ID);
939
24.6M
  while (*Name)
940
23.4M
    Record.push_back(*Name++);
941
1.23M
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
942
1.23M
}
943
944
static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
945
3.61k
                          ASTWriter::RecordDataImpl &Record) {
946
445k
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
947
3.61k
  RECORD(STMT_STOP);
948
3.61k
  RECORD(STMT_NULL_PTR);
949
3.61k
  RECORD(STMT_REF_PTR);
950
3.61k
  RECORD(STMT_NULL);
951
3.61k
  RECORD(STMT_COMPOUND);
952
3.61k
  RECORD(STMT_CASE);
953
3.61k
  RECORD(STMT_DEFAULT);
954
3.61k
  RECORD(STMT_LABEL);
955
3.61k
  RECORD(STMT_ATTRIBUTED);
956
3.61k
  RECORD(STMT_IF);
957
3.61k
  RECORD(STMT_SWITCH);
958
3.61k
  RECORD(STMT_WHILE);
959
3.61k
  RECORD(STMT_DO);
960
3.61k
  RECORD(STMT_FOR);
961
3.61k
  RECORD(STMT_GOTO);
962
3.61k
  RECORD(STMT_INDIRECT_GOTO);
963
3.61k
  RECORD(STMT_CONTINUE);
964
3.61k
  RECORD(STMT_BREAK);
965
3.61k
  RECORD(STMT_RETURN);
966
3.61k
  RECORD(STMT_DECL);
967
3.61k
  RECORD(STMT_GCCASM);
968
3.61k
  RECORD(STMT_MSASM);
969
3.61k
  RECORD(EXPR_PREDEFINED);
970
3.61k
  RECORD(EXPR_DECL_REF);
971
3.61k
  RECORD(EXPR_INTEGER_LITERAL);
972
3.61k
  RECORD(EXPR_FLOATING_LITERAL);
973
3.61k
  RECORD(EXPR_IMAGINARY_LITERAL);
974
3.61k
  RECORD(EXPR_STRING_LITERAL);
975
3.61k
  RECORD(EXPR_CHARACTER_LITERAL);
976
3.61k
  RECORD(EXPR_PAREN);
977
3.61k
  RECORD(EXPR_PAREN_LIST);
978
3.61k
  RECORD(EXPR_UNARY_OPERATOR);
979
3.61k
  RECORD(EXPR_SIZEOF_ALIGN_OF);
980
3.61k
  RECORD(EXPR_ARRAY_SUBSCRIPT);
981
3.61k
  RECORD(EXPR_CALL);
982
3.61k
  RECORD(EXPR_MEMBER);
983
3.61k
  RECORD(EXPR_BINARY_OPERATOR);
984
3.61k
  RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
985
3.61k
  RECORD(EXPR_CONDITIONAL_OPERATOR);
986
3.61k
  RECORD(EXPR_IMPLICIT_CAST);
987
3.61k
  RECORD(EXPR_CSTYLE_CAST);
988
3.61k
  RECORD(EXPR_COMPOUND_LITERAL);
989
3.61k
  RECORD(EXPR_EXT_VECTOR_ELEMENT);
990
3.61k
  RECORD(EXPR_INIT_LIST);
991
3.61k
  RECORD(EXPR_DESIGNATED_INIT);
992
3.61k
  RECORD(EXPR_DESIGNATED_INIT_UPDATE);
993
3.61k
  RECORD(EXPR_IMPLICIT_VALUE_INIT);
994
3.61k
  RECORD(EXPR_NO_INIT);
995
3.61k
  RECORD(EXPR_VA_ARG);
996
3.61k
  RECORD(EXPR_ADDR_LABEL);
997
3.61k
  RECORD(EXPR_STMT);
998
3.61k
  RECORD(EXPR_CHOOSE);
999
3.61k
  RECORD(EXPR_GNU_NULL);
1000
3.61k
  RECORD(EXPR_SHUFFLE_VECTOR);
1001
3.61k
  RECORD(EXPR_BLOCK);
1002
3.61k
  RECORD(EXPR_GENERIC_SELECTION);
1003
3.61k
  RECORD(EXPR_OBJC_STRING_LITERAL);
1004
3.61k
  RECORD(EXPR_OBJC_BOXED_EXPRESSION);
1005
3.61k
  RECORD(EXPR_OBJC_ARRAY_LITERAL);
1006
3.61k
  RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
1007
3.61k
  RECORD(EXPR_OBJC_ENCODE);
1008
3.61k
  RECORD(EXPR_OBJC_SELECTOR_EXPR);
1009
3.61k
  RECORD(EXPR_OBJC_PROTOCOL_EXPR);
1010
3.61k
  RECORD(EXPR_OBJC_IVAR_REF_EXPR);
1011
3.61k
  RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
1012
3.61k
  RECORD(EXPR_OBJC_KVC_REF_EXPR);
1013
3.61k
  RECORD(EXPR_OBJC_MESSAGE_EXPR);
1014
3.61k
  RECORD(STMT_OBJC_FOR_COLLECTION);
1015
3.61k
  RECORD(STMT_OBJC_CATCH);
1016
3.61k
  RECORD(STMT_OBJC_FINALLY);
1017
3.61k
  RECORD(STMT_OBJC_AT_TRY);
1018
3.61k
  RECORD(STMT_OBJC_AT_SYNCHRONIZED);
1019
3.61k
  RECORD(STMT_OBJC_AT_THROW);
1020
3.61k
  RECORD(EXPR_OBJC_BOOL_LITERAL);
1021
3.61k
  RECORD(STMT_CXX_CATCH);
1022
3.61k
  RECORD(STMT_CXX_TRY);
1023
3.61k
  RECORD(STMT_CXX_FOR_RANGE);
1024
3.61k
  RECORD(EXPR_CXX_OPERATOR_CALL);
1025
3.61k
  RECORD(EXPR_CXX_MEMBER_CALL);
1026
3.61k
  RECORD(EXPR_CXX_CONSTRUCT);
1027
3.61k
  RECORD(EXPR_CXX_TEMPORARY_OBJECT);
1028
3.61k
  RECORD(EXPR_CXX_STATIC_CAST);
1029
3.61k
  RECORD(EXPR_CXX_DYNAMIC_CAST);
1030
3.61k
  RECORD(EXPR_CXX_REINTERPRET_CAST);
1031
3.61k
  RECORD(EXPR_CXX_CONST_CAST);
1032
3.61k
  RECORD(EXPR_CXX_FUNCTIONAL_CAST);
1033
3.61k
  RECORD(EXPR_USER_DEFINED_LITERAL);
1034
3.61k
  RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
1035
3.61k
  RECORD(EXPR_CXX_BOOL_LITERAL);
1036
3.61k
  RECORD(EXPR_CXX_NULL_PTR_LITERAL);
1037
3.61k
  RECORD(EXPR_CXX_TYPEID_EXPR);
1038
3.61k
  RECORD(EXPR_CXX_TYPEID_TYPE);
1039
3.61k
  RECORD(EXPR_CXX_THIS);
1040
3.61k
  RECORD(EXPR_CXX_THROW);
1041
3.61k
  RECORD(EXPR_CXX_DEFAULT_ARG);
1042
3.61k
  RECORD(EXPR_CXX_DEFAULT_INIT);
1043
3.61k
  RECORD(EXPR_CXX_BIND_TEMPORARY);
1044
3.61k
  RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
1045
3.61k
  RECORD(EXPR_CXX_NEW);
1046
3.61k
  RECORD(EXPR_CXX_DELETE);
1047
3.61k
  RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
1048
3.61k
  RECORD(EXPR_EXPR_WITH_CLEANUPS);
1049
3.61k
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
1050
3.61k
  RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
1051
3.61k
  RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
1052
3.61k
  RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
1053
3.61k
  RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
1054
3.61k
  RECORD(EXPR_CXX_EXPRESSION_TRAIT);
1055
3.61k
  RECORD(EXPR_CXX_NOEXCEPT);
1056
3.61k
  RECORD(EXPR_OPAQUE_VALUE);
1057
3.61k
  RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1058
3.61k
  RECORD(EXPR_TYPE_TRAIT);
1059
3.61k
  RECORD(EXPR_ARRAY_TYPE_TRAIT);
1060
3.61k
  RECORD(EXPR_PACK_EXPANSION);
1061
3.61k
  RECORD(EXPR_SIZEOF_PACK);
1062
3.61k
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
1063
3.61k
  RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
1064
3.61k
  RECORD(EXPR_FUNCTION_PARM_PACK);
1065
3.61k
  RECORD(EXPR_MATERIALIZE_TEMPORARY);
1066
3.61k
  RECORD(EXPR_CUDA_KERNEL_CALL);
1067
3.61k
  RECORD(EXPR_CXX_UUIDOF_EXPR);
1068
3.61k
  RECORD(EXPR_CXX_UUIDOF_TYPE);
1069
3.61k
  RECORD(EXPR_LAMBDA);
1070
3.61k
#undef RECORD
1071
3.61k
}
1072
1073
3.61k
void ASTWriter::WriteBlockInfoBlock() {
1074
3.61k
  RecordData Record;
1075
3.61k
  Stream.EnterBlockInfoBlock();
1076
3.61k
1077
43.4k
#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1078
785k
#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1079
3.61k
1080
3.61k
  // Control Block.
1081
3.61k
  BLOCK(CONTROL_BLOCK);
1082
3.61k
  RECORD(METADATA);
1083
3.61k
  RECORD(MODULE_NAME);
1084
3.61k
  RECORD(MODULE_DIRECTORY);
1085
3.61k
  RECORD(MODULE_MAP_FILE);
1086
3.61k
  RECORD(IMPORTS);
1087
3.61k
  RECORD(ORIGINAL_FILE);
1088
3.61k
  RECORD(ORIGINAL_PCH_DIR);
1089
3.61k
  RECORD(ORIGINAL_FILE_ID);
1090
3.61k
  RECORD(INPUT_FILE_OFFSETS);
1091
3.61k
1092
3.61k
  BLOCK(OPTIONS_BLOCK);
1093
3.61k
  RECORD(LANGUAGE_OPTIONS);
1094
3.61k
  RECORD(TARGET_OPTIONS);
1095
3.61k
  RECORD(FILE_SYSTEM_OPTIONS);
1096
3.61k
  RECORD(HEADER_SEARCH_OPTIONS);
1097
3.61k
  RECORD(PREPROCESSOR_OPTIONS);
1098
3.61k
1099
3.61k
  BLOCK(INPUT_FILES_BLOCK);
1100
3.61k
  RECORD(INPUT_FILE);
1101
3.61k
1102
3.61k
  // AST Top-Level Block.
1103
3.61k
  BLOCK(AST_BLOCK);
1104
3.61k
  RECORD(TYPE_OFFSET);
1105
3.61k
  RECORD(DECL_OFFSET);
1106
3.61k
  RECORD(IDENTIFIER_OFFSET);
1107
3.61k
  RECORD(IDENTIFIER_TABLE);
1108
3.61k
  RECORD(EAGERLY_DESERIALIZED_DECLS);
1109
3.61k
  RECORD(MODULAR_CODEGEN_DECLS);
1110
3.61k
  RECORD(SPECIAL_TYPES);
1111
3.61k
  RECORD(STATISTICS);
1112
3.61k
  RECORD(TENTATIVE_DEFINITIONS);
1113
3.61k
  RECORD(SELECTOR_OFFSETS);
1114
3.61k
  RECORD(METHOD_POOL);
1115
3.61k
  RECORD(PP_COUNTER_VALUE);
1116
3.61k
  RECORD(SOURCE_LOCATION_OFFSETS);
1117
3.61k
  RECORD(SOURCE_LOCATION_PRELOADS);
1118
3.61k
  RECORD(EXT_VECTOR_DECLS);
1119
3.61k
  RECORD(UNUSED_FILESCOPED_DECLS);
1120
3.61k
  RECORD(PPD_ENTITIES_OFFSETS);
1121
3.61k
  RECORD(VTABLE_USES);
1122
3.61k
  RECORD(PPD_SKIPPED_RANGES);
1123
3.61k
  RECORD(REFERENCED_SELECTOR_POOL);
1124
3.61k
  RECORD(TU_UPDATE_LEXICAL);
1125
3.61k
  RECORD(SEMA_DECL_REFS);
1126
3.61k
  RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1127
3.61k
  RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1128
3.61k
  RECORD(UPDATE_VISIBLE);
1129
3.61k
  RECORD(DECL_UPDATE_OFFSETS);
1130
3.61k
  RECORD(DECL_UPDATES);
1131
3.61k
  RECORD(CUDA_SPECIAL_DECL_REFS);
1132
3.61k
  RECORD(HEADER_SEARCH_TABLE);
1133
3.61k
  RECORD(FP_PRAGMA_OPTIONS);
1134
3.61k
  RECORD(OPENCL_EXTENSIONS);
1135
3.61k
  RECORD(OPENCL_EXTENSION_TYPES);
1136
3.61k
  RECORD(OPENCL_EXTENSION_DECLS);
1137
3.61k
  RECORD(DELEGATING_CTORS);
1138
3.61k
  RECORD(KNOWN_NAMESPACES);
1139
3.61k
  RECORD(MODULE_OFFSET_MAP);
1140
3.61k
  RECORD(SOURCE_MANAGER_LINE_TABLE);
1141
3.61k
  RECORD(OBJC_CATEGORIES_MAP);
1142
3.61k
  RECORD(FILE_SORTED_DECLS);
1143
3.61k
  RECORD(IMPORTED_MODULES);
1144
3.61k
  RECORD(OBJC_CATEGORIES);
1145
3.61k
  RECORD(MACRO_OFFSET);
1146
3.61k
  RECORD(INTERESTING_IDENTIFIERS);
1147
3.61k
  RECORD(UNDEFINED_BUT_USED);
1148
3.61k
  RECORD(LATE_PARSED_TEMPLATE);
1149
3.61k
  RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1150
3.61k
  RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1151
3.61k
  RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1152
3.61k
  RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1153
3.61k
  RECORD(DELETE_EXPRS_TO_ANALYZE);
1154
3.61k
  RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1155
3.61k
  RECORD(PP_CONDITIONAL_STACK);
1156
3.61k
1157
3.61k
  // SourceManager Block.
1158
3.61k
  BLOCK(SOURCE_MANAGER_BLOCK);
1159
3.61k
  RECORD(SM_SLOC_FILE_ENTRY);
1160
3.61k
  RECORD(SM_SLOC_BUFFER_ENTRY);
1161
3.61k
  RECORD(SM_SLOC_BUFFER_BLOB);
1162
3.61k
  RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1163
3.61k
  RECORD(SM_SLOC_EXPANSION_ENTRY);
1164
3.61k
1165
3.61k
  // Preprocessor Block.
1166
3.61k
  BLOCK(PREPROCESSOR_BLOCK);
1167
3.61k
  RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1168
3.61k
  RECORD(PP_MACRO_FUNCTION_LIKE);
1169
3.61k
  RECORD(PP_MACRO_OBJECT_LIKE);
1170
3.61k
  RECORD(PP_MODULE_MACRO);
1171
3.61k
  RECORD(PP_TOKEN);
1172
3.61k
1173
3.61k
  // Submodule Block.
1174
3.61k
  BLOCK(SUBMODULE_BLOCK);
1175
3.61k
  RECORD(SUBMODULE_METADATA);
1176
3.61k
  RECORD(SUBMODULE_DEFINITION);
1177
3.61k
  RECORD(SUBMODULE_UMBRELLA_HEADER);
1178
3.61k
  RECORD(SUBMODULE_HEADER);
1179
3.61k
  RECORD(SUBMODULE_TOPHEADER);
1180
3.61k
  RECORD(SUBMODULE_UMBRELLA_DIR);
1181
3.61k
  RECORD(SUBMODULE_IMPORTS);
1182
3.61k
  RECORD(SUBMODULE_EXPORTS);
1183
3.61k
  RECORD(SUBMODULE_REQUIRES);
1184
3.61k
  RECORD(SUBMODULE_EXCLUDED_HEADER);
1185
3.61k
  RECORD(SUBMODULE_LINK_LIBRARY);
1186
3.61k
  RECORD(SUBMODULE_CONFIG_MACRO);
1187
3.61k
  RECORD(SUBMODULE_CONFLICT);
1188
3.61k
  RECORD(SUBMODULE_PRIVATE_HEADER);
1189
3.61k
  RECORD(SUBMODULE_TEXTUAL_HEADER);
1190
3.61k
  RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1191
3.61k
  RECORD(SUBMODULE_INITIALIZERS);
1192
3.61k
  RECORD(SUBMODULE_EXPORT_AS);
1193
3.61k
1194
3.61k
  // Comments Block.
1195
3.61k
  BLOCK(COMMENTS_BLOCK);
1196
3.61k
  RECORD(COMMENTS_RAW_COMMENT);
1197
3.61k
1198
3.61k
  // Decls and Types block.
1199
3.61k
  BLOCK(DECLTYPES_BLOCK);
1200
3.61k
  RECORD(TYPE_EXT_QUAL);
1201
3.61k
  RECORD(TYPE_COMPLEX);
1202
3.61k
  RECORD(TYPE_POINTER);
1203
3.61k
  RECORD(TYPE_BLOCK_POINTER);
1204
3.61k
  RECORD(TYPE_LVALUE_REFERENCE);
1205
3.61k
  RECORD(TYPE_RVALUE_REFERENCE);
1206
3.61k
  RECORD(TYPE_MEMBER_POINTER);
1207
3.61k
  RECORD(TYPE_CONSTANT_ARRAY);
1208
3.61k
  RECORD(TYPE_INCOMPLETE_ARRAY);
1209
3.61k
  RECORD(TYPE_VARIABLE_ARRAY);
1210
3.61k
  RECORD(TYPE_VECTOR);
1211
3.61k
  RECORD(TYPE_EXT_VECTOR);
1212
3.61k
  RECORD(TYPE_FUNCTION_NO_PROTO);
1213
3.61k
  RECORD(TYPE_FUNCTION_PROTO);
1214
3.61k
  RECORD(TYPE_TYPEDEF);
1215
3.61k
  RECORD(TYPE_TYPEOF_EXPR);
1216
3.61k
  RECORD(TYPE_TYPEOF);
1217
3.61k
  RECORD(TYPE_RECORD);
1218
3.61k
  RECORD(TYPE_ENUM);
1219
3.61k
  RECORD(TYPE_OBJC_INTERFACE);
1220
3.61k
  RECORD(TYPE_OBJC_OBJECT_POINTER);
1221
3.61k
  RECORD(TYPE_DECLTYPE);
1222
3.61k
  RECORD(TYPE_ELABORATED);
1223
3.61k
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1224
3.61k
  RECORD(TYPE_UNRESOLVED_USING);
1225
3.61k
  RECORD(TYPE_INJECTED_CLASS_NAME);
1226
3.61k
  RECORD(TYPE_OBJC_OBJECT);
1227
3.61k
  RECORD(TYPE_TEMPLATE_TYPE_PARM);
1228
3.61k
  RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1229
3.61k
  RECORD(TYPE_DEPENDENT_NAME);
1230
3.61k
  RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1231
3.61k
  RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1232
3.61k
  RECORD(TYPE_PAREN);
1233
3.61k
  RECORD(TYPE_MACRO_QUALIFIED);
1234
3.61k
  RECORD(TYPE_PACK_EXPANSION);
1235
3.61k
  RECORD(TYPE_ATTRIBUTED);
1236
3.61k
  RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1237
3.61k
  RECORD(TYPE_AUTO);
1238
3.61k
  RECORD(TYPE_UNARY_TRANSFORM);
1239
3.61k
  RECORD(TYPE_ATOMIC);
1240
3.61k
  RECORD(TYPE_DECAYED);
1241
3.61k
  RECORD(TYPE_ADJUSTED);
1242
3.61k
  RECORD(TYPE_OBJC_TYPE_PARAM);
1243
3.61k
  RECORD(LOCAL_REDECLARATIONS);
1244
3.61k
  RECORD(DECL_TYPEDEF);
1245
3.61k
  RECORD(DECL_TYPEALIAS);
1246
3.61k
  RECORD(DECL_ENUM);
1247
3.61k
  RECORD(DECL_RECORD);
1248
3.61k
  RECORD(DECL_ENUM_CONSTANT);
1249
3.61k
  RECORD(DECL_FUNCTION);
1250
3.61k
  RECORD(DECL_OBJC_METHOD);
1251
3.61k
  RECORD(DECL_OBJC_INTERFACE);
1252
3.61k
  RECORD(DECL_OBJC_PROTOCOL);
1253
3.61k
  RECORD(DECL_OBJC_IVAR);
1254
3.61k
  RECORD(DECL_OBJC_AT_DEFS_FIELD);
1255
3.61k
  RECORD(DECL_OBJC_CATEGORY);
1256
3.61k
  RECORD(DECL_OBJC_CATEGORY_IMPL);
1257
3.61k
  RECORD(DECL_OBJC_IMPLEMENTATION);
1258
3.61k
  RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1259
3.61k
  RECORD(DECL_OBJC_PROPERTY);
1260
3.61k
  RECORD(DECL_OBJC_PROPERTY_IMPL);
1261
3.61k
  RECORD(DECL_FIELD);
1262
3.61k
  RECORD(DECL_MS_PROPERTY);
1263
3.61k
  RECORD(DECL_VAR);
1264
3.61k
  RECORD(DECL_IMPLICIT_PARAM);
1265
3.61k
  RECORD(DECL_PARM_VAR);
1266
3.61k
  RECORD(DECL_FILE_SCOPE_ASM);
1267
3.61k
  RECORD(DECL_BLOCK);
1268
3.61k
  RECORD(DECL_CONTEXT_LEXICAL);
1269
3.61k
  RECORD(DECL_CONTEXT_VISIBLE);
1270
3.61k
  RECORD(DECL_NAMESPACE);
1271
3.61k
  RECORD(DECL_NAMESPACE_ALIAS);
1272
3.61k
  RECORD(DECL_USING);
1273
3.61k
  RECORD(DECL_USING_SHADOW);
1274
3.61k
  RECORD(DECL_USING_DIRECTIVE);
1275
3.61k
  RECORD(DECL_UNRESOLVED_USING_VALUE);
1276
3.61k
  RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1277
3.61k
  RECORD(DECL_LINKAGE_SPEC);
1278
3.61k
  RECORD(DECL_CXX_RECORD);
1279
3.61k
  RECORD(DECL_CXX_METHOD);
1280
3.61k
  RECORD(DECL_CXX_CONSTRUCTOR);
1281
3.61k
  RECORD(DECL_CXX_DESTRUCTOR);
1282
3.61k
  RECORD(DECL_CXX_CONVERSION);
1283
3.61k
  RECORD(DECL_ACCESS_SPEC);
1284
3.61k
  RECORD(DECL_FRIEND);
1285
3.61k
  RECORD(DECL_FRIEND_TEMPLATE);
1286
3.61k
  RECORD(DECL_CLASS_TEMPLATE);
1287
3.61k
  RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1288
3.61k
  RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1289
3.61k
  RECORD(DECL_VAR_TEMPLATE);
1290
3.61k
  RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1291
3.61k
  RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1292
3.61k
  RECORD(DECL_FUNCTION_TEMPLATE);
1293
3.61k
  RECORD(DECL_TEMPLATE_TYPE_PARM);
1294
3.61k
  RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1295
3.61k
  RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1296
3.61k
  RECORD(DECL_CONCEPT);
1297
3.61k
  RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1298
3.61k
  RECORD(DECL_STATIC_ASSERT);
1299
3.61k
  RECORD(DECL_CXX_BASE_SPECIFIERS);
1300
3.61k
  RECORD(DECL_CXX_CTOR_INITIALIZERS);
1301
3.61k
  RECORD(DECL_INDIRECTFIELD);
1302
3.61k
  RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1303
3.61k
  RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1304
3.61k
  RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1305
3.61k
  RECORD(DECL_IMPORT);
1306
3.61k
  RECORD(DECL_OMP_THREADPRIVATE);
1307
3.61k
  RECORD(DECL_EMPTY);
1308
3.61k
  RECORD(DECL_OBJC_TYPE_PARAM);
1309
3.61k
  RECORD(DECL_OMP_CAPTUREDEXPR);
1310
3.61k
  RECORD(DECL_PRAGMA_COMMENT);
1311
3.61k
  RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1312
3.61k
  RECORD(DECL_OMP_DECLARE_REDUCTION);
1313
3.61k
  RECORD(DECL_OMP_ALLOCATE);
1314
3.61k
1315
3.61k
  // Statements and Exprs can occur in the Decls and Types block.
1316
3.61k
  AddStmtsExprs(Stream, Record);
1317
3.61k
1318
3.61k
  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1319
3.61k
  RECORD(PPD_MACRO_EXPANSION);
1320
3.61k
  RECORD(PPD_MACRO_DEFINITION);
1321
3.61k
  RECORD(PPD_INCLUSION_DIRECTIVE);
1322
3.61k
1323
3.61k
  // Decls and Types block.
1324
3.61k
  BLOCK(EXTENSION_BLOCK);
1325
3.61k
  RECORD(EXTENSION_METADATA);
1326
3.61k
1327
3.61k
  BLOCK(UNHASHED_CONTROL_BLOCK);
1328
3.61k
  RECORD(SIGNATURE);
1329
3.61k
  RECORD(DIAGNOSTIC_OPTIONS);
1330
3.61k
  RECORD(DIAG_PRAGMA_MAPPINGS);
1331
3.61k
1332
3.61k
#undef RECORD
1333
3.61k
#undef BLOCK
1334
3.61k
  Stream.ExitBlock();
1335
3.61k
}
1336
1337
/// Prepares a path for being written to an AST file by converting it
1338
/// to an absolute path and removing nested './'s.
1339
///
1340
/// \return \c true if the path was changed.
1341
static bool cleanPathForOutput(FileManager &FileMgr,
1342
25.8k
                               SmallVectorImpl<char> &Path) {
1343
25.8k
  bool Changed = FileMgr.makeAbsolutePath(Path);
1344
25.8k
  return Changed | llvm::sys::path::remove_dots(Path);
1345
25.8k
}
1346
1347
/// Adjusts the given filename to only write out the portion of the
1348
/// filename that is not part of the system root directory.
1349
///
1350
/// \param Filename the file name to adjust.
1351
///
1352
/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1353
/// the returned filename will be adjusted by this root directory.
1354
///
1355
/// \returns either the original filename (if it needs no adjustment) or the
1356
/// adjusted filename (which points into the @p Filename parameter).
1357
static const char *
1358
24.3k
adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1359
24.3k
  assert(Filename && "No file name to adjust?");
1360
24.3k
1361
24.3k
  if (BaseDir.empty())
1362
11.3k
    return Filename;
1363
13.0k
1364
13.0k
  // Verify that the filename and the system root have the same prefix.
1365
13.0k
  unsigned Pos = 0;
1366
1.30M
  for (; Filename[Pos] && Pos < BaseDir.size(); 
++Pos1.28M
)
1367
1.29M
    if (Filename[Pos] != BaseDir[Pos])
1368
3.64k
      return Filename; // Prefixes don't match.
1369
13.0k
1370
13.0k
  // We hit the end of the filename before we hit the end of the system root.
1371
13.0k
  
if (9.42k
!Filename[Pos]9.42k
)
1372
0
    return Filename;
1373
9.42k
1374
9.42k
  // If there's not a path separator at the end of the base directory nor
1375
9.42k
  // immediately after it, then this isn't within the base directory.
1376
9.42k
  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1377
3
    if (!llvm::sys::path::is_separator(BaseDir.back()))
1378
3
      return Filename;
1379
9.42k
  } else {
1380
9.42k
    // If the file name has a '/' at the current position, skip over the '/'.
1381
9.42k
    // We distinguish relative paths from absolute paths by the
1382
9.42k
    // absence of '/' at the beginning of relative paths.
1383
9.42k
    //
1384
9.42k
    // FIXME: This is wrong. We distinguish them by asking if the path is
1385
9.42k
    // absolute, which isn't the same thing. And there might be multiple '/'s
1386
9.42k
    // in a row. Use a better mechanism to indicate whether we have emitted an
1387
9.42k
    // absolute or relative path.
1388
9.42k
    ++Pos;
1389
9.42k
  }
1390
9.42k
1391
9.42k
  
return Filename + Pos9.42k
;
1392
9.42k
}
1393
1394
1.25k
ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1395
1.25k
  // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1396
1.25k
  llvm::SHA1 Hasher;
1397
1.25k
  Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1398
1.25k
  auto Hash = Hasher.result();
1399
1.25k
1400
1.25k
  // Convert to an array [5*i32].
1401
1.25k
  ASTFileSignature Signature;
1402
25.0k
  auto LShift = [&](unsigned char Val, unsigned Shift) {
1403
25.0k
    return (uint32_t)Val << Shift;
1404
25.0k
  };
1405
7.50k
  for (int I = 0; I != 5; 
++I6.25k
)
1406
6.25k
    Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1407
6.25k
                   LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1408
1.25k
1409
1.25k
  return Signature;
1410
1.25k
}
1411
1412
ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1413
3.61k
                                                      ASTContext &Context) {
1414
3.61k
  // Flush first to prepare the PCM hash (signature).
1415
3.61k
  Stream.FlushToWord();
1416
3.61k
  auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1417
3.61k
1418
3.61k
  // Enter the block and prepare to write records.
1419
3.61k
  RecordData Record;
1420
3.61k
  Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1421
3.61k
1422
3.61k
  // For implicit modules, write the hash of the PCM as its signature.
1423
3.61k
  ASTFileSignature Signature;
1424
3.61k
  if (WritingModule &&
1425
3.61k
      
PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent1.48k
) {
1426
1.25k
    Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1427
1.25k
    Record.append(Signature.begin(), Signature.end());
1428
1.25k
    Stream.EmitRecord(SIGNATURE, Record);
1429
1.25k
    Record.clear();
1430
1.25k
  }
1431
3.61k
1432
3.61k
  // Diagnostic options.
1433
3.61k
  const auto &Diags = Context.getDiagnostics();
1434
3.61k
  const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1435
101k
#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1436
3.61k
#define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1437
10.8k
  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1438
3.61k
#include "clang/Basic/DiagnosticOptions.def"
1439
3.61k
  Record.push_back(DiagOpts.Warnings.size());
1440
4.22k
  for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; 
++I606
)
1441
606
    AddString(DiagOpts.Warnings[I], Record);
1442
3.61k
  Record.push_back(DiagOpts.Remarks.size());
1443
3.70k
  for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; 
++I90
)
1444
90
    AddString(DiagOpts.Remarks[I], Record);
1445
3.61k
  // Note: we don't serialize the log or serialization file names, because they
1446
3.61k
  // are generally transient files and will almost always be overridden.
1447
3.61k
  Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1448
3.61k
1449
3.61k
  // Write out the diagnostic/pragma mappings.
1450
3.61k
  WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1451
3.61k
1452
3.61k
  // Leave the options block.
1453
3.61k
  Stream.ExitBlock();
1454
3.61k
  return Signature;
1455
3.61k
}
1456
1457
/// Write the control block.
1458
void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1459
                                  StringRef isysroot,
1460
3.61k
                                  const std::string &OutputFile) {
1461
3.61k
  using namespace llvm;
1462
3.61k
1463
3.61k
  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1464
3.61k
  RecordData Record;
1465
3.61k
1466
3.61k
  // Metadata
1467
3.61k
  auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1468
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1469
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1470
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1471
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1472
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1473
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1474
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1475
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
1476
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1477
3.61k
  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1478
3.61k
  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1479
3.61k
  assert((!WritingModule || isysroot.empty()) &&
1480
3.61k
         "writing module as a relocatable PCH?");
1481
3.61k
  {
1482
3.61k
    RecordData::value_type Record[] = {
1483
3.61k
        METADATA,
1484
3.61k
        VERSION_MAJOR,
1485
3.61k
        VERSION_MINOR,
1486
3.61k
        CLANG_VERSION_MAJOR,
1487
3.61k
        CLANG_VERSION_MINOR,
1488
3.61k
        !isysroot.empty(),
1489
3.61k
        IncludeTimestamps,
1490
3.61k
        Context.getLangOpts().BuildingPCHWithObjectFile,
1491
3.61k
        ASTHasCompilerErrors};
1492
3.61k
    Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1493
3.61k
                              getClangFullRepositoryVersion());
1494
3.61k
  }
1495
3.61k
1496
3.61k
  if (WritingModule) {
1497
1.48k
    // Module name
1498
1.48k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1499
1.48k
    Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1500
1.48k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1501
1.48k
    unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1502
1.48k
    RecordData::value_type Record[] = {MODULE_NAME};
1503
1.48k
    Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1504
1.48k
  }
1505
3.61k
1506
3.61k
  if (WritingModule && 
WritingModule->Directory1.48k
) {
1507
1.43k
    SmallString<128> BaseDir(WritingModule->Directory->getName());
1508
1.43k
    cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1509
1.43k
1510
1.43k
    // If the home of the module is the current working directory, then we
1511
1.43k
    // want to pick up the cwd of the build process loading the module, not
1512
1.43k
    // our cwd, when we load this module.
1513
1.43k
    if (!PP.getHeaderSearchInfo()
1514
1.43k
             .getHeaderSearchOpts()
1515
1.43k
             .ModuleMapFileHomeIsCwd ||
1516
1.43k
        
WritingModule->Directory->getName() != StringRef(".")27
) {
1517
1.41k
      // Module directory.
1518
1.41k
      auto Abbrev = std::make_shared<BitCodeAbbrev>();
1519
1.41k
      Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1520
1.41k
      Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1521
1.41k
      unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1522
1.41k
1523
1.41k
      RecordData::value_type Record[] = {MODULE_DIRECTORY};
1524
1.41k
      Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1525
1.41k
    }
1526
1.43k
1527
1.43k
    // Write out all other paths relative to the base directory if possible.
1528
1.43k
    BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1529
2.18k
  } else if (!isysroot.empty()) {
1530
1
    // Write out paths relative to the sysroot if possible.
1531
1
    BaseDirectory = isysroot;
1532
1
  }
1533
3.61k
1534
3.61k
  // Module map file
1535
3.61k
  if (WritingModule && 
WritingModule->Kind == Module::ModuleMapModule1.48k
) {
1536
1.43k
    Record.clear();
1537
1.43k
1538
1.43k
    auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1539
1.43k
    AddPath(WritingModule->PresumedModuleMapFile.empty()
1540
1.43k
                ? 
Map.getModuleMapFileForUniquing(WritingModule)->getName()1.41k
1541
1.43k
                : 
StringRef(WritingModule->PresumedModuleMapFile)16
,
1542
1.43k
            Record);
1543
1.43k
1544
1.43k
    // Additional module map files.
1545
1.43k
    if (auto *AdditionalModMaps =
1546
41
            Map.getAdditionalModuleMapFiles(WritingModule)) {
1547
41
      Record.push_back(AdditionalModMaps->size());
1548
41
      for (const FileEntry *F : *AdditionalModMaps)
1549
41
        AddPath(F->getName(), Record);
1550
1.39k
    } else {
1551
1.39k
      Record.push_back(0);
1552
1.39k
    }
1553
1.43k
1554
1.43k
    Stream.EmitRecord(MODULE_MAP_FILE, Record);
1555
1.43k
  }
1556
3.61k
1557
3.61k
  // Imports
1558
3.61k
  if (Chain) {
1559
1.61k
    serialization::ModuleManager &Mgr = Chain->getModuleManager();
1560
1.61k
    Record.clear();
1561
1.61k
1562
1.69k
    for (ModuleFile &M : Mgr) {
1563
1.69k
      // Skip modules that weren't directly imported.
1564
1.69k
      if (!M.isDirectlyImported())
1565
917
        continue;
1566
780
1567
780
      Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1568
780
      AddSourceLocation(M.ImportLoc, Record);
1569
780
1570
780
      // If we have calculated signature, there is no need to store
1571
780
      // the size or timestamp.
1572
780
      Record.push_back(M.Signature ? 
0570
:
M.File->getSize()210
);
1573
780
      Record.push_back(M.Signature ? 
0570
:
getTimestampForOutput(M.File)210
);
1574
780
1575
780
      for (auto I : M.Signature)
1576
3.90k
        Record.push_back(I);
1577
780
1578
780
      AddString(M.ModuleName, Record);
1579
780
      AddPath(M.FileName, Record);
1580
780
    }
1581
1.61k
    Stream.EmitRecord(IMPORTS, Record);
1582
1.61k
  }
1583
3.61k
1584
3.61k
  // Write the options block.
1585
3.61k
  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1586
3.61k
1587
3.61k
  // Language options.
1588
3.61k
  Record.clear();
1589
3.61k
  const LangOptions &LangOpts = Context.getLangOpts();
1590
3.61k
#define LANGOPT(Name, Bits, Default, Description) \
1591
662k
  Record.push_back(LangOpts.Name);
1592
3.61k
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1593
43.4k
  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1594
3.61k
#include "clang/Basic/LangOptions.def"
1595
3.61k
#define SANITIZER(NAME, ID)                                                    \
1596
191k
  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1597
3.61k
#include "clang/Basic/Sanitizers.def"
1598
3.61k
1599
3.61k
  Record.push_back(LangOpts.ModuleFeatures.size());
1600
3.61k
  for (StringRef Feature : LangOpts.ModuleFeatures)
1601
13
    AddString(Feature, Record);
1602
3.61k
1603
3.61k
  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1604
3.61k
  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1605
3.61k
1606
3.61k
  AddString(LangOpts.CurrentModule, Record);
1607
3.61k
1608
3.61k
  // Comment options.
1609
3.61k
  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1610
3.61k
  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1611
2
    AddString(I, Record);
1612
2
  }
1613
3.61k
  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1614
3.61k
1615
3.61k
  // OpenMP offloading options.
1616
3.61k
  Record.push_back(LangOpts.OMPTargetTriples.size());
1617
3.61k
  for (auto &T : LangOpts.OMPTargetTriples)
1618
1.23k
    AddString(T.getTriple(), Record);
1619
3.61k
1620
3.61k
  AddString(LangOpts.OMPHostIRFile, Record);
1621
3.61k
1622
3.61k
  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1623
3.61k
1624
3.61k
  // Target options.
1625
3.61k
  Record.clear();
1626
3.61k
  const TargetInfo &Target = Context.getTargetInfo();
1627
3.61k
  const TargetOptions &TargetOpts = Target.getTargetOpts();
1628
3.61k
  AddString(TargetOpts.Triple, Record);
1629
3.61k
  AddString(TargetOpts.CPU, Record);
1630
3.61k
  AddString(TargetOpts.ABI, Record);
1631
3.61k
  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1632
3.62k
  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; 
++I2
) {
1633
2
    AddString(TargetOpts.FeaturesAsWritten[I], Record);
1634
2
  }
1635
3.61k
  Record.push_back(TargetOpts.Features.size());
1636
24.4k
  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; 
++I20.8k
) {
1637
20.8k
    AddString(TargetOpts.Features[I], Record);
1638
20.8k
  }
1639
3.61k
  Stream.EmitRecord(TARGET_OPTIONS, Record);
1640
3.61k
1641
3.61k
  // File system options.
1642
3.61k
  Record.clear();
1643
3.61k
  const FileSystemOptions &FSOpts =
1644
3.61k
      Context.getSourceManager().getFileManager().getFileSystemOpts();
1645
3.61k
  AddString(FSOpts.WorkingDir, Record);
1646
3.61k
  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1647
3.61k
1648
3.61k
  // Header search options.
1649
3.61k
  Record.clear();
1650
3.61k
  const HeaderSearchOptions &HSOpts
1651
3.61k
    = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1652
3.61k
  AddString(HSOpts.Sysroot, Record);
1653
3.61k
1654
3.61k
  // Include entries.
1655
3.61k
  Record.push_back(HSOpts.UserEntries.size());
1656
9.28k
  for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; 
++I5.66k
) {
1657
5.66k
    const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1658
5.66k
    AddString(Entry.Path, Record);
1659
5.66k
    Record.push_back(static_cast<unsigned>(Entry.Group));
1660
5.66k
    Record.push_back(Entry.IsFramework);
1661
5.66k
    Record.push_back(Entry.IgnoreSysRoot);
1662
5.66k
  }
1663
3.61k
1664
3.61k
  // System header prefixes.
1665
3.61k
  Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1666
3.61k
  for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; 
++I0
) {
1667
0
    AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1668
0
    Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1669
0
  }
1670
3.61k
1671
3.61k
  AddString(HSOpts.ResourceDir, Record);
1672
3.61k
  AddString(HSOpts.ModuleCachePath, Record);
1673
3.61k
  AddString(HSOpts.ModuleUserBuildPath, Record);
1674
3.61k
  Record.push_back(HSOpts.DisableModuleHash);
1675
3.61k
  Record.push_back(HSOpts.ImplicitModuleMaps);
1676
3.61k
  Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1677
3.61k
  Record.push_back(HSOpts.UseBuiltinIncludes);
1678
3.61k
  Record.push_back(HSOpts.UseStandardSystemIncludes);
1679
3.61k
  Record.push_back(HSOpts.UseStandardCXXIncludes);
1680
3.61k
  Record.push_back(HSOpts.UseLibcxx);
1681
3.61k
  // Write out the specific module cache path that contains the module files.
1682
3.61k
  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1683
3.61k
  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1684
3.61k
1685
3.61k
  // Preprocessor options.
1686
3.61k
  Record.clear();
1687
3.61k
  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1688
3.61k
1689
3.61k
  // Macro definitions.
1690
3.61k
  Record.push_back(PPOpts.Macros.size());
1691
5.30k
  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; 
++I1.68k
) {
1692
1.68k
    AddString(PPOpts.Macros[I].first, Record);
1693
1.68k
    Record.push_back(PPOpts.Macros[I].second);
1694
1.68k
  }
1695
3.61k
1696
3.61k
  // Includes
1697
3.61k
  Record.push_back(PPOpts.Includes.size());
1698
3.62k
  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; 
++I11
)
1699
11
    AddString(PPOpts.Includes[I], Record);
1700
3.61k
1701
3.61k
  // Macro includes
1702
3.61k
  Record.push_back(PPOpts.MacroIncludes.size());
1703
3.61k
  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; 
++I0
)
1704
0
    AddString(PPOpts.MacroIncludes[I], Record);
1705
3.61k
1706
3.61k
  Record.push_back(PPOpts.UsePredefines);
1707
3.61k
  // Detailed record is important since it is used for the module cache hash.
1708
3.61k
  Record.push_back(PPOpts.DetailedRecord);
1709
3.61k
  AddString(PPOpts.ImplicitPCHInclude, Record);
1710
3.61k
  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1711
3.61k
  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1712
3.61k
1713
3.61k
  // Leave the options block.
1714
3.61k
  Stream.ExitBlock();
1715
3.61k
1716
3.61k
  // Original file name and file ID
1717
3.61k
  SourceManager &SM = Context.getSourceManager();
1718
3.61k
  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1719
2.25k
    auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1720
2.25k
    FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1721
2.25k
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1722
2.25k
    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1723
2.25k
    unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1724
2.25k
1725
2.25k
    Record.clear();
1726
2.25k
    Record.push_back(ORIGINAL_FILE);
1727
2.25k
    Record.push_back(SM.getMainFileID().getOpaqueValue());
1728
2.25k
    EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1729
2.25k
  }
1730
3.61k
1731
3.61k
  Record.clear();
1732
3.61k
  Record.push_back(SM.getMainFileID().getOpaqueValue());
1733
3.61k
  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1734
3.61k
1735
3.61k
  // Original PCH directory
1736
3.61k
  if (!OutputFile.empty() && 
OutputFile != "-"3.46k
) {
1737
3.41k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
1738
3.41k
    Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1739
3.41k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1740
3.41k
    unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1741
3.41k
1742
3.41k
    SmallString<128> OutputPath(OutputFile);
1743
3.41k
1744
3.41k
    SM.getFileManager().makeAbsolutePath(OutputPath);
1745
3.41k
    StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1746
3.41k
1747
3.41k
    RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1748
3.41k
    Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1749
3.41k
  }
1750
3.61k
1751
3.61k
  WriteInputFiles(Context.SourceMgr,
1752
3.61k
                  PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1753
3.61k
                  PP.getLangOpts().Modules);
1754
3.61k
  Stream.ExitBlock();
1755
3.61k
}
1756
1757
namespace  {
1758
1759
/// An input file.
1760
struct InputFileEntry {
1761
  const FileEntry *File;
1762
  bool IsSystemFile;
1763
  bool IsTransient;
1764
  bool BufferOverridden;
1765
  bool IsTopLevelModuleMap;
1766
};
1767
1768
} // namespace
1769
1770
void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1771
                                HeaderSearchOptions &HSOpts,
1772
3.61k
                                bool Modules) {
1773
3.61k
  using namespace llvm;
1774
3.61k
1775
3.61k
  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1776
3.61k
1777
3.61k
  // Create input-file abbreviation.
1778
3.61k
  auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1779
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1780
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1781
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1782
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1783
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1784
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1785
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1786
3.61k
  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1787
3.61k
  unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1788
3.61k
1789
3.61k
  // Get all ContentCache objects for files, sorted by whether the file is a
1790
3.61k
  // system one or not. System files go at the back, users files at the front.
1791
3.61k
  std::deque<InputFileEntry> SortedFiles;
1792
175k
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; 
++I172k
) {
1793
172k
    // Get this source location entry.
1794
172k
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1795
172k
    assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1796
172k
1797
172k
    // We only care about file entries that were not overridden.
1798
172k
    if (!SLoc->isFile())
1799
159k
      continue;
1800
12.2k
    const SrcMgr::FileInfo &File = SLoc->getFile();
1801
12.2k
    const SrcMgr::ContentCache *Cache = File.getContentCache();
1802
12.2k
    if (!Cache->OrigEntry)
1803
5.09k
      continue;
1804
7.19k
1805
7.19k
    InputFileEntry Entry;
1806
7.19k
    Entry.File = Cache->OrigEntry;
1807
7.19k
    Entry.IsSystemFile = Cache->IsSystemFile;
1808
7.19k
    Entry.IsTransient = Cache->IsTransient;
1809
7.19k
    Entry.BufferOverridden = Cache->BufferOverridden;
1810
7.19k
    Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1811
7.19k
                                
File.getIncludeLoc().isInvalid()1.70k
;
1812
7.19k
    if (Cache->IsSystemFile)
1813
982
      SortedFiles.push_back(Entry);
1814
6.21k
    else
1815
6.21k
      SortedFiles.push_front(Entry);
1816
7.19k
  }
1817
3.61k
1818
3.61k
  unsigned UserFilesNum = 0;
1819
3.61k
  // Write out all of the input files.
1820
3.61k
  std::vector<uint64_t> InputFileOffsets;
1821
7.19k
  for (const auto &Entry : SortedFiles) {
1822
7.19k
    uint32_t &InputFileID = InputFileIDs[Entry.File];
1823
7.19k
    if (InputFileID != 0)
1824
195
      continue; // already recorded this file.
1825
7.00k
1826
7.00k
    // Record this entry's offset.
1827
7.00k
    InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1828
7.00k
1829
7.00k
    InputFileID = InputFileOffsets.size();
1830
7.00k
1831
7.00k
    if (!Entry.IsSystemFile)
1832
6.15k
      ++UserFilesNum;
1833
7.00k
1834
7.00k
    // Emit size/modification time for this file.
1835
7.00k
    // And whether this file was overridden.
1836
7.00k
    RecordData::value_type Record[] = {
1837
7.00k
        INPUT_FILE,
1838
7.00k
        InputFileOffsets.size(),
1839
7.00k
        (uint64_t)Entry.File->getSize(),
1840
7.00k
        (uint64_t)getTimestampForOutput(Entry.File),
1841
7.00k
        Entry.BufferOverridden,
1842
7.00k
        Entry.IsTransient,
1843
7.00k
        Entry.IsTopLevelModuleMap};
1844
7.00k
1845
7.00k
    EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1846
7.00k
  }
1847
3.61k
1848
3.61k
  Stream.ExitBlock();
1849
3.61k
1850
3.61k
  // Create input file offsets abbreviation.
1851
3.61k
  auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1852
3.61k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1853
3.61k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1854
3.61k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1855
3.61k
                                                                //   input files
1856
3.61k
  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1857
3.61k
  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1858
3.61k
1859
3.61k
  // Write input file offsets.
1860
3.61k
  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1861
3.61k
                                     InputFileOffsets.size(), UserFilesNum};
1862
3.61k
  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1863
3.61k
}
1864
1865
//===----------------------------------------------------------------------===//
1866
// Source Manager Serialization
1867
//===----------------------------------------------------------------------===//
1868
1869
/// Create an abbreviation for the SLocEntry that refers to a
1870
/// file.
1871
3.61k
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1872
3.61k
  using namespace llvm;
1873
3.61k
1874
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1875
3.61k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1876
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1877
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1878
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1879
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1880
3.61k
  // FileEntry fields.
1881
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1882
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1883
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1884
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1885
3.61k
  return Stream.EmitAbbrev(std::move(Abbrev));
1886
3.61k
}
1887
1888
/// Create an abbreviation for the SLocEntry that refers to a
1889
/// buffer.
1890
3.61k
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1891
3.61k
  using namespace llvm;
1892
3.61k
1893
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1894
3.61k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1895
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1896
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1897
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1898
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1899
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1900
3.61k
  return Stream.EmitAbbrev(std::move(Abbrev));
1901
3.61k
}
1902
1903
/// Create an abbreviation for the SLocEntry that refers to a
1904
/// buffer's blob.
1905
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1906
7.23k
                                           bool Compressed) {
1907
7.23k
  using namespace llvm;
1908
7.23k
1909
7.23k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1910
7.23k
  Abbrev->Add(BitCodeAbbrevOp(Compressed ? 
SM_SLOC_BUFFER_BLOB_COMPRESSED3.61k
1911
7.23k
                                         : 
SM_SLOC_BUFFER_BLOB3.61k
));
1912
7.23k
  if (Compressed)
1913
3.61k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1914
7.23k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1915
7.23k
  return Stream.EmitAbbrev(std::move(Abbrev));
1916
7.23k
}
1917
1918
/// Create an abbreviation for the SLocEntry that refers to a macro
1919
/// expansion.
1920
3.61k
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1921
3.61k
  using namespace llvm;
1922
3.61k
1923
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1924
3.61k
  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1925
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1926
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1927
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1928
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1929
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1930
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1931
3.61k
  return Stream.EmitAbbrev(std::move(Abbrev));
1932
3.61k
}
1933
1934
namespace {
1935
1936
  // Trait used for the on-disk hash table of header search information.
1937
  class HeaderFileInfoTrait {
1938
    ASTWriter &Writer;
1939
1940
    // Keep track of the framework names we've used during serialization.
1941
    SmallVector<char, 128> FrameworkStringData;
1942
    llvm::StringMap<unsigned> FrameworkNameOffset;
1943
1944
  public:
1945
3.61k
    HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1946
1947
    struct key_type {
1948
      StringRef Filename;
1949
      off_t Size;
1950
      time_t ModTime;
1951
    };
1952
    using key_type_ref = const key_type &;
1953
1954
    using UnresolvedModule =
1955
        llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1956
1957
    struct data_type {
1958
      const HeaderFileInfo &HFI;
1959
      ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1960
      UnresolvedModule Unresolved;
1961
    };
1962
    using data_type_ref = const data_type &;
1963
1964
    using hash_value_type = unsigned;
1965
    using offset_type = unsigned;
1966
1967
5.69k
    hash_value_type ComputeHash(key_type_ref key) {
1968
5.69k
      // The hash is based only on size/time of the file, so that the reader can
1969
5.69k
      // match even when symlinking or excess path elements ("foo/../", "../")
1970
5.69k
      // change the form of the name. However, complete path is still the key.
1971
5.69k
      return llvm::hash_combine(key.Size, key.ModTime);
1972
5.69k
    }
1973
1974
    std::pair<unsigned, unsigned>
1975
5.69k
    EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1976
5.69k
      using namespace llvm::support;
1977
5.69k
1978
5.69k
      endian::Writer LE(Out, little);
1979
5.69k
      unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1980
5.69k
      LE.write<uint16_t>(KeyLen);
1981
5.69k
      unsigned DataLen = 1 + 2 + 4 + 4;
1982
5.69k
      for (auto ModInfo : Data.KnownHeaders)
1983
2.94k
        if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1984
2.83k
          DataLen += 4;
1985
5.69k
      if (Data.Unresolved.getPointer())
1986
12
        DataLen += 4;
1987
5.69k
      LE.write<uint8_t>(DataLen);
1988
5.69k
      return std::make_pair(KeyLen, DataLen);
1989
5.69k
    }
1990
1991
5.69k
    void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1992
5.69k
      using namespace llvm::support;
1993
5.69k
1994
5.69k
      endian::Writer LE(Out, little);
1995
5.69k
      LE.write<uint64_t>(key.Size);
1996
5.69k
      KeyLen -= 8;
1997
5.69k
      LE.write<uint64_t>(key.ModTime);
1998
5.69k
      KeyLen -= 8;
1999
5.69k
      Out.write(key.Filename.data(), KeyLen);
2000
5.69k
    }
2001
2002
    void EmitData(raw_ostream &Out, key_type_ref key,
2003
5.69k
                  data_type_ref Data, unsigned DataLen) {
2004
5.69k
      using namespace llvm::support;
2005
5.69k
2006
5.69k
      endian::Writer LE(Out, little);
2007
5.69k
      uint64_t Start = Out.tell(); (void)Start;
2008
5.69k
2009
5.69k
      unsigned char Flags = (Data.HFI.isImport << 5)
2010
5.69k
                          | (Data.HFI.isPragmaOnce << 4)
2011
5.69k
                          | (Data.HFI.DirInfo << 1)
2012
5.69k
                          | Data.HFI.IndexHeaderMapHeader;
2013
5.69k
      LE.write<uint8_t>(Flags);
2014
5.69k
      LE.write<uint16_t>(Data.HFI.NumIncludes);
2015
5.69k
2016
5.69k
      if (!Data.HFI.ControllingMacro)
2017
3.64k
        LE.write<uint32_t>(Data.HFI.ControllingMacroID);
2018
2.05k
      else
2019
2.05k
        LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
2020
5.69k
2021
5.69k
      unsigned Offset = 0;
2022
5.69k
      if (!Data.HFI.Framework.empty()) {
2023
0
        // If this header refers into a framework, save the framework name.
2024
0
        llvm::StringMap<unsigned>::iterator Pos
2025
0
          = FrameworkNameOffset.find(Data.HFI.Framework);
2026
0
        if (Pos == FrameworkNameOffset.end()) {
2027
0
          Offset = FrameworkStringData.size() + 1;
2028
0
          FrameworkStringData.append(Data.HFI.Framework.begin(),
2029
0
                                     Data.HFI.Framework.end());
2030
0
          FrameworkStringData.push_back(0);
2031
0
2032
0
          FrameworkNameOffset[Data.HFI.Framework] = Offset;
2033
0
        } else
2034
0
          Offset = Pos->second;
2035
0
      }
2036
5.69k
      LE.write<uint32_t>(Offset);
2037
5.69k
2038
5.69k
      auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2039
2.95k
        if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2040
2.84k
          uint32_t Value = (ModID << 2) | (unsigned)Role;
2041
2.84k
          assert((Value >> 2) == ModID && "overflow in header module info");
2042
2.84k
          LE.write<uint32_t>(Value);
2043
2.84k
        }
2044
2.95k
      };
2045
5.69k
2046
5.69k
      // FIXME: If the header is excluded, we should write out some
2047
5.69k
      // record of that fact.
2048
5.69k
      for (auto ModInfo : Data.KnownHeaders)
2049
2.94k
        EmitModule(ModInfo.getModule(), ModInfo.getRole());
2050
5.69k
      if (Data.Unresolved.getPointer())
2051
12
        EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2052
5.69k
2053
5.69k
      assert(Out.tell() - Start == DataLen && "Wrong data length");
2054
5.69k
    }
2055
2056
3.61k
    const char *strings_begin() const { return FrameworkStringData.begin(); }
2057
3.61k
    const char *strings_end() const { return FrameworkStringData.end(); }
2058
  };
2059
2060
} // namespace
2061
2062
/// Write the header search block for the list of files that
2063
///
2064
/// \param HS The header search structure to save.
2065
3.61k
void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2066
3.61k
  HeaderFileInfoTrait GeneratorTrait(*this);
2067
3.61k
  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2068
3.61k
  SmallVector<const char *, 4> SavedStrings;
2069
3.61k
  unsigned NumHeaderSearchEntries = 0;
2070
3.61k
2071
3.61k
  // Find all unresolved headers for the current module. We generally will
2072
3.61k
  // have resolved them before we get here, but not necessarily: we might be
2073
3.61k
  // compiling a preprocessed module, where there is no requirement for the
2074
3.61k
  // original files to exist any more.
2075
3.61k
  const HeaderFileInfo Empty; // So we can take a reference.
2076
3.61k
  if (WritingModule) {
2077
1.48k
    llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2078
4.85k
    while (!Worklist.empty()) {
2079
3.36k
      Module *M = Worklist.pop_back_val();
2080
3.36k
      if (!M->isAvailable())
2081
305
        continue;
2082
3.06k
2083
3.06k
      // Map to disk files where possible, to pick up any missing stat
2084
3.06k
      // information. This also means we don't need to check the unresolved
2085
3.06k
      // headers list when emitting resolved headers in the first loop below.
2086
3.06k
      // FIXME: It'd be preferable to avoid doing this if we were given
2087
3.06k
      // sufficient stat information in the module map.
2088
3.06k
      HS.getModuleMap().resolveHeaderDirectives(M);
2089
3.06k
2090
3.06k
      // If the file didn't exist, we can still create a module if we were given
2091
3.06k
      // enough information in the module map.
2092
3.06k
      for (auto U : M->MissingHeaders) {
2093
13
        // Check that we were given enough information to build a module
2094
13
        // without this file existing on disk.
2095
13
        if (!U.Size || 
(12
!U.ModTime12
&&
IncludeTimestamps1
)) {
2096
1
          PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2097
1
            << WritingModule->getFullModuleName() << U.Size.hasValue()
2098
1
            << U.FileName;
2099
1
          continue;
2100
1
        }
2101
12
2102
12
        // Form the effective relative pathname for the file.
2103
12
        SmallString<128> Filename(M->Directory->getName());
2104
12
        llvm::sys::path::append(Filename, U.FileName);
2105
12
        PreparePathForOutput(Filename);
2106
12
2107
12
        StringRef FilenameDup = strdup(Filename.c_str());
2108
12
        SavedStrings.push_back(FilenameDup.data());
2109
12
2110
12
        HeaderFileInfoTrait::key_type Key = {
2111
12
          FilenameDup, *U.Size, IncludeTimestamps ? 
*U.ModTime8
:
04
2112
12
        };
2113
12
        HeaderFileInfoTrait::data_type Data = {
2114
12
          Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2115
12
        };
2116
12
        // FIXME: Deal with cases where there are multiple unresolved header
2117
12
        // directives in different submodules for the same header.
2118
12
        Generator.insert(Key, Data, GeneratorTrait);
2119
12
        ++NumHeaderSearchEntries;
2120
12
      }
2121
3.06k
2122
3.06k
      Worklist.append(M->submodule_begin(), M->submodule_end());
2123
3.06k
    }
2124
1.48k
  }
2125
3.61k
2126
3.61k
  SmallVector<const FileEntry *, 16> FilesByUID;
2127
3.61k
  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2128
3.61k
2129
3.61k
  if (FilesByUID.size() > HS.header_file_size())
2130
760
    FilesByUID.resize(HS.header_file_size());
2131
3.61k
2132
70.3k
  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; 
++UID66.7k
) {
2133
66.7k
    const FileEntry *File = FilesByUID[UID];
2134
66.7k
    if (!File)
2135
0
      continue;
2136
66.7k
2137
66.7k
    // Get the file info. This will load info from the external source if
2138
66.7k
    // necessary. Skip emitting this file if we have no information on it
2139
66.7k
    // as a header file (in which case HFI will be null) or if it hasn't
2140
66.7k
    // changed since it was loaded. Also skip it if it's for a modular header
2141
66.7k
    // from a different module; in that case, we rely on the module(s)
2142
66.7k
    // containing the header to provide this information.
2143
66.7k
    const HeaderFileInfo *HFI =
2144
66.7k
        HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2145
66.7k
    if (!HFI || 
(50.9k
HFI->isModuleHeader50.9k
&&
!HFI->isCompilingModuleHeader47.3k
))
2146
61.0k
      continue;
2147
5.68k
2148
5.68k
    // Massage the file path into an appropriate form.
2149
5.68k
    StringRef Filename = File->getName();
2150
5.68k
    SmallString<128> FilenameTmp(Filename);
2151
5.68k
    if (PreparePathForOutput(FilenameTmp)) {
2152
3.24k
      // If we performed any translation on the file name at all, we need to
2153
3.24k
      // save this string, since the generator will refer to it later.
2154
3.24k
      Filename = StringRef(strdup(FilenameTmp.c_str()));
2155
3.24k
      SavedStrings.push_back(Filename.data());
2156
3.24k
    }
2157
5.68k
2158
5.68k
    HeaderFileInfoTrait::key_type Key = {
2159
5.68k
      Filename, File->getSize(), getTimestampForOutput(File)
2160
5.68k
    };
2161
5.68k
    HeaderFileInfoTrait::data_type Data = {
2162
5.68k
      *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2163
5.68k
    };
2164
5.68k
    Generator.insert(Key, Data, GeneratorTrait);
2165
5.68k
    ++NumHeaderSearchEntries;
2166
5.68k
  }
2167
3.61k
2168
3.61k
  // Create the on-disk hash table in a buffer.
2169
3.61k
  SmallString<4096> TableData;
2170
3.61k
  uint32_t BucketOffset;
2171
3.61k
  {
2172
3.61k
    using namespace llvm::support;
2173
3.61k
2174
3.61k
    llvm::raw_svector_ostream Out(TableData);
2175
3.61k
    // Make sure that no bucket is at offset 0
2176
3.61k
    endian::write<uint32_t>(Out, 0, little);
2177
3.61k
    BucketOffset = Generator.Emit(Out, GeneratorTrait);
2178
3.61k
  }
2179
3.61k
2180
3.61k
  // Create a blob abbreviation
2181
3.61k
  using namespace llvm;
2182
3.61k
2183
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2184
3.61k
  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2185
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2186
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2187
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2188
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2189
3.61k
  unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2190
3.61k
2191
3.61k
  // Write the header search table
2192
3.61k
  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2193
3.61k
                                     NumHeaderSearchEntries, TableData.size()};
2194
3.61k
  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2195
3.61k
  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2196
3.61k
2197
3.61k
  // Free all of the strings we had to duplicate.
2198
6.87k
  for (unsigned I = 0, N = SavedStrings.size(); I != N; 
++I3.25k
)
2199
3.25k
    free(const_cast<char *>(SavedStrings[I]));
2200
3.61k
}
2201
2202
static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2203
                     unsigned SLocBufferBlobCompressedAbbrv,
2204
5.38k
                     unsigned SLocBufferBlobAbbrv) {
2205
5.38k
  using RecordDataType = ASTWriter::RecordData::value_type;
2206
5.38k
2207
5.38k
  // Compress the buffer if possible. We expect that almost all PCM
2208
5.38k
  // consumers will not want its contents.
2209
5.38k
  SmallString<0> CompressedBuffer;
2210
5.38k
  if (llvm::zlib::isAvailable()) {
2211
5.38k
    llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2212
5.38k
    if (!E) {
2213
5.38k
      RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2214
5.38k
                                 Blob.size() - 1};
2215
5.38k
      Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2216
5.38k
                                CompressedBuffer);
2217
5.38k
      return;
2218
5.38k
    }
2219
0
    llvm::consumeError(std::move(E));
2220
0
  }
2221
5.38k
2222
5.38k
  RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2223
0
  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2224
0
}
2225
2226
/// Writes the block containing the serialized form of the
2227
/// source manager.
2228
///
2229
/// TODO: We should probably use an on-disk hash table (stored in a
2230
/// blob), indexed based on the file name, so that we only create
2231
/// entries for files that we actually need. In the common case (no
2232
/// errors), we probably won't have to create file entries for any of
2233
/// the files in the AST.
2234
void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2235
3.61k
                                        const Preprocessor &PP) {
2236
3.61k
  RecordData Record;
2237
3.61k
2238
3.61k
  // Enter the source manager block.
2239
3.61k
  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2240
3.61k
2241
3.61k
  // Abbreviations for the various kinds of source-location entries.
2242
3.61k
  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2243
3.61k
  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2244
3.61k
  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2245
3.61k
  unsigned SLocBufferBlobCompressedAbbrv =
2246
3.61k
      CreateSLocBufferBlobAbbrev(Stream, true);
2247
3.61k
  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2248
3.61k
2249
3.61k
  // Write out the source location entry table. We skip the first
2250
3.61k
  // entry, which is always the same dummy entry.
2251
3.61k
  std::vector<uint32_t> SLocEntryOffsets;
2252
3.61k
  RecordData PreloadSLocs;
2253
3.61k
  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2254
3.61k
  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2255
175k
       I != N; 
++I172k
) {
2256
172k
    // Get this source location entry.
2257
172k
    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2258
172k
    FileID FID = FileID::get(I);
2259
172k
    assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2260
172k
2261
172k
    // Record the offset of this source-location entry.
2262
172k
    SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2263
172k
2264
172k
    // Figure out which record code to use.
2265
172k
    unsigned Code;
2266
172k
    if (SLoc->isFile()) {
2267
12.2k
      const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2268
12.2k
      if (Cache->OrigEntry) {
2269
7.19k
        Code = SM_SLOC_FILE_ENTRY;
2270
7.19k
      } else
2271
5.09k
        Code = SM_SLOC_BUFFER_ENTRY;
2272
12.2k
    } else
2273
159k
      Code = SM_SLOC_EXPANSION_ENTRY;
2274
172k
    Record.clear();
2275
172k
    Record.push_back(Code);
2276
172k
2277
172k
    // Starting offset of this entry within this module, so skip the dummy.
2278
172k
    Record.push_back(SLoc->getOffset() - 2);
2279
172k
    if (SLoc->isFile()) {
2280
12.2k
      const SrcMgr::FileInfo &File = SLoc->getFile();
2281
12.2k
      AddSourceLocation(File.getIncludeLoc(), Record);
2282
12.2k
      Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2283
12.2k
      Record.push_back(File.hasLineDirectives());
2284
12.2k
2285
12.2k
      const SrcMgr::ContentCache *Content = File.getContentCache();
2286
12.2k
      bool EmitBlob = false;
2287
12.2k
      if (Content->OrigEntry) {
2288
7.19k
        assert(Content->OrigEntry == Content->ContentsEntry &&
2289
7.19k
               "Writing to AST an overridden file is not supported");
2290
7.19k
2291
7.19k
        // The source location entry is a file. Emit input file ID.
2292
7.19k
        assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2293
7.19k
        Record.push_back(InputFileIDs[Content->OrigEntry]);
2294
7.19k
2295
7.19k
        Record.push_back(File.NumCreatedFIDs);
2296
7.19k
2297
7.19k
        FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2298
7.19k
        if (FDI != FileDeclIDs.end()) {
2299
5.09k
          Record.push_back(FDI->second->FirstDeclIndex);
2300
5.09k
          Record.push_back(FDI->second->DeclIDs.size());
2301
5.09k
        } else {
2302
2.10k
          Record.push_back(0);
2303
2.10k
          Record.push_back(0);
2304
2.10k
        }
2305
7.19k
2306
7.19k
        Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2307
7.19k
2308
7.19k
        if (Content->BufferOverridden || 
Content->IsTransient6.94k
)
2309
287
          EmitBlob = true;
2310
7.19k
      } else {
2311
5.09k
        // The source location entry is a buffer. The blob associated
2312
5.09k
        // with this entry contains the contents of the buffer.
2313
5.09k
2314
5.09k
        // We add one to the size so that we capture the trailing NULL
2315
5.09k
        // that is required by llvm::MemoryBuffer::getMemBuffer (on
2316
5.09k
        // the reader side).
2317
5.09k
        const llvm::MemoryBuffer *Buffer
2318
5.09k
          = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2319
5.09k
        StringRef Name = Buffer->getBufferIdentifier();
2320
5.09k
        Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2321
5.09k
                                  StringRef(Name.data(), Name.size() + 1));
2322
5.09k
        EmitBlob = true;
2323
5.09k
2324
5.09k
        if (Name == "<built-in>")
2325
3.61k
          PreloadSLocs.push_back(SLocEntryOffsets.size());
2326
5.09k
      }
2327
12.2k
2328
12.2k
      if (EmitBlob) {
2329
5.38k
        // Include the implicit terminating null character in the on-disk buffer
2330
5.38k
        // if we're writing it uncompressed.
2331
5.38k
        const llvm::MemoryBuffer *Buffer =
2332
5.38k
            Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2333
5.38k
        StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2334
5.38k
        emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2335
5.38k
                 SLocBufferBlobAbbrv);
2336
5.38k
      }
2337
159k
    } else {
2338
159k
      // The source location entry is a macro expansion.
2339
159k
      const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2340
159k
      AddSourceLocation(Expansion.getSpellingLoc(), Record);
2341
159k
      AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2342
159k
      AddSourceLocation(Expansion.isMacroArgExpansion()
2343
159k
                            ? 
SourceLocation()24.0k
2344
159k
                            : 
Expansion.getExpansionLocEnd()135k
,
2345
159k
                        Record);
2346
159k
      Record.push_back(Expansion.isExpansionTokenRange());
2347
159k
2348
159k
      // Compute the token length for this macro expansion.
2349
159k
      unsigned NextOffset = SourceMgr.getNextLocalOffset();
2350
159k
      if (I + 1 != N)
2351
159k
        NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2352
159k
      Record.push_back(NextOffset - SLoc->getOffset() - 1);
2353
159k
      Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2354
159k
    }
2355
172k
  }
2356
3.61k
2357
3.61k
  Stream.ExitBlock();
2358
3.61k
2359
3.61k
  if (SLocEntryOffsets.empty())
2360
0
    return;
2361
3.61k
2362
3.61k
  // Write the source-location offsets table into the AST block. This
2363
3.61k
  // table is used for lazily loading source-location information.
2364
3.61k
  using namespace llvm;
2365
3.61k
2366
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2367
3.61k
  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2368
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2369
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2370
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2371
3.61k
  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2372
3.61k
  {
2373
3.61k
    RecordData::value_type Record[] = {
2374
3.61k
        SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2375
3.61k
        SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2376
3.61k
    Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2377
3.61k
                              bytes(SLocEntryOffsets));
2378
3.61k
  }
2379
3.61k
  // Write the source location entry preloads array, telling the AST
2380
3.61k
  // reader which source locations entries it should load eagerly.
2381
3.61k
  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2382
3.61k
2383
3.61k
  // Write the line table. It depends on remapping working, so it must come
2384
3.61k
  // after the source location offsets.
2385
3.61k
  if (SourceMgr.hasLineTable()) {
2386
3.61k
    LineTableInfo &LineTable = SourceMgr.getLineTable();
2387
3.61k
2388
3.61k
    Record.clear();
2389
3.61k
2390
3.61k
    // Emit the needed file names.
2391
3.61k
    llvm::DenseMap<int, int> FilenameMap;
2392
3.61k
    FilenameMap[-1] = -1; // For unspecified filenames.
2393
5.27k
    for (const auto &L : LineTable) {
2394
5.27k
      if (L.first.ID < 0)
2395
1.70k
        continue;
2396
10.8k
      
for (auto &LE : L.second)3.57k
{
2397
10.8k
        if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2398
10.8k
                                              FilenameMap.size() - 1)).second)
2399
7.17k
          AddPath(LineTable.getFilename(LE.FilenameID), Record);
2400
10.8k
      }
2401
3.57k
    }
2402
3.61k
    Record.push_back(0);
2403
3.61k
2404
3.61k
    // Emit the line entries
2405
5.27k
    for (const auto &L : LineTable) {
2406
5.27k
      // Only emit entries for local files.
2407
5.27k
      if (L.first.ID < 0)
2408
1.70k
        continue;
2409
3.57k
2410
3.57k
      // Emit the file ID
2411
3.57k
      Record.push_back(L.first.ID);
2412
3.57k
2413
3.57k
      // Emit the line entries
2414
3.57k
      Record.push_back(L.second.size());
2415
10.8k
      for (const auto &LE : L.second) {
2416
10.8k
        Record.push_back(LE.FileOffset);
2417
10.8k
        Record.push_back(LE.LineNo);
2418
10.8k
        Record.push_back(FilenameMap[LE.FilenameID]);
2419
10.8k
        Record.push_back((unsigned)LE.FileKind);
2420
10.8k
        Record.push_back(LE.IncludeOffset);
2421
10.8k
      }
2422
3.57k
    }
2423
3.61k
2424
3.61k
    Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2425
3.61k
  }
2426
3.61k
}
2427
2428
//===----------------------------------------------------------------------===//
2429
// Preprocessor Serialization
2430
//===----------------------------------------------------------------------===//
2431
2432
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2433
1.37M
                              const Preprocessor &PP) {
2434
1.37M
  if (MacroInfo *MI = MD->getMacroInfo())
2435
1.37M
    if (MI->isBuiltinMacro())
2436
94.6k
      return true;
2437
1.27M
2438
1.27M
  if (IsModule) {
2439
542k
    SourceLocation Loc = MD->getLocation();
2440
542k
    if (Loc.isInvalid())
2441
0
      return true;
2442
542k
    if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2443
542k
      return true;
2444
736k
  }
2445
736k
2446
736k
  return false;
2447
736k
}
2448
2449
/// Writes the block containing the serialized form of the
2450
/// preprocessor.
2451
3.61k
void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2452
3.61k
  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2453
3.61k
  if (PPRec)
2454
189
    WritePreprocessorDetail(*PPRec);
2455
3.61k
2456
3.61k
  RecordData Record;
2457
3.61k
  RecordData ModuleMacroRecord;
2458
3.61k
2459
3.61k
  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2460
3.61k
  if (PP.getCounterValue() != 0) {
2461
2
    RecordData::value_type Record[] = {PP.getCounterValue()};
2462
2
    Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2463
2
  }
2464
3.61k
2465
3.61k
  if (PP.isRecordingPreamble() && 
PP.hasRecordedPreamble()89
) {
2466
7
    assert(!IsModule);
2467
7
    auto SkipInfo = PP.getPreambleSkipInfo();
2468
7
    if (SkipInfo.hasValue()) {
2469
5
      Record.push_back(true);
2470
5
      AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2471
5
      AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2472
5
      Record.push_back(SkipInfo->FoundNonSkipPortion);
2473
5
      Record.push_back(SkipInfo->FoundElse);
2474
5
      AddSourceLocation(SkipInfo->ElseLoc, Record);
2475
5
    } else {
2476
2
      Record.push_back(false);
2477
2
    }
2478
7
    for (const auto &Cond : PP.getPreambleConditionalStack()) {
2479
7
      AddSourceLocation(Cond.IfLoc, Record);
2480
7
      Record.push_back(Cond.WasSkipping);
2481
7
      Record.push_back(Cond.FoundNonSkip);
2482
7
      Record.push_back(Cond.FoundElse);
2483
7
    }
2484
7
    Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2485
7
    Record.clear();
2486
7
  }
2487
3.61k
2488
3.61k
  // Enter the preprocessor block.
2489
3.61k
  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2490
3.61k
2491
3.61k
  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2492
3.61k
  // FIXME: Include a location for the use, and say which one was used.
2493
3.61k
  if (PP.SawDateOrTime())
2494
1
    PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2495
3.61k
2496
3.61k
  // Loop over all the macro directives that are live at the end of the file,
2497
3.61k
  // emitting each to the PP section.
2498
3.61k
2499
3.61k
  // Construct the list of identifiers with macro directives that need to be
2500
3.61k
  // serialized.
2501
3.61k
  SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2502
3.61k
  for (auto &Id : PP.getIdentifierTable())
2503
11.2M
    if (Id.second->hadMacroDefinition() &&
2504
11.2M
        
(1.39M
!Id.second->isFromAST()1.39M
||
2505
1.39M
         
Id.second->hasChangedSinceDeserialization()5.53k
))
2506
1.39M
      MacroIdentifiers.push_back(Id.second);
2507
3.61k
  // Sort the set of macro definitions that need to be serialized by the
2508
3.61k
  // name of the macro, to provide a stable ordering.
2509
3.61k
  llvm::sort(MacroIdentifiers, llvm::less_ptr<IdentifierInfo>());
2510
3.61k
2511
3.61k
  // Emit the macro directives as a list and associate the offset with the
2512
3.61k
  // identifier they belong to.
2513
1.39M
  for (const IdentifierInfo *Name : MacroIdentifiers) {
2514
1.39M
    MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2515
1.39M
    auto StartOffset = Stream.GetCurrentBitNo();
2516
1.39M
2517
1.39M
    // Emit the macro directives in reverse source order.
2518
2.12M
    for (; MD; 
MD = MD->getPrevious()736k
) {
2519
1.37M
      // Once we hit an ignored macro, we're done: the rest of the chain
2520
1.37M
      // will all be ignored macros.
2521
1.37M
      if (shouldIgnoreMacro(MD, IsModule, PP))
2522
636k
        break;
2523
736k
2524
736k
      AddSourceLocation(MD->getLocation(), Record);
2525
736k
      Record.push_back(MD->getKind());
2526
736k
      if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2527
736k
        Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2528
736k
      } else 
if (auto *184
VisMD184
= dyn_cast<VisibilityMacroDirective>(MD)) {
2529
151
        Record.push_back(VisMD->isPublic());
2530
151
      }
2531
736k
    }
2532
1.39M
2533
1.39M
    // Write out any exported module macros.
2534
1.39M
    bool EmittedModuleMacros = false;
2535
1.39M
    // We write out exported module macros for PCH as well.
2536
1.39M
    auto Leafs = PP.getLeafModuleMacros(Name);
2537
1.39M
    SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2538
1.39M
    llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2539
1.40M
    while (!Worklist.empty()) {
2540
18.0k
      auto *Macro = Worklist.pop_back_val();
2541
18.0k
2542
18.0k
      // Emit a record indicating this submodule exports this macro.
2543
18.0k
      ModuleMacroRecord.push_back(
2544
18.0k
          getSubmoduleID(Macro->getOwningModule()));
2545
18.0k
      ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2546
18.0k
      for (auto *M : Macro->overrides())
2547
143
        ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2548
18.0k
2549
18.0k
      Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2550
18.0k
      ModuleMacroRecord.clear();
2551
18.0k
2552
18.0k
      // Enqueue overridden macros once we've visited all their ancestors.
2553
18.0k
      for (auto *M : Macro->overrides())
2554
143
        if (++Visits[M] == M->getNumOverridingMacros())
2555
135
          Worklist.push_back(M);
2556
18.0k
2557
18.0k
      EmittedModuleMacros = true;
2558
18.0k
    }
2559
1.39M
2560
1.39M
    if (Record.empty() && 
!EmittedModuleMacros654k
)
2561
636k
      continue;
2562
753k
2563
753k
    IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2564
753k
    Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2565
753k
    Record.clear();
2566
753k
  }
2567
3.61k
2568
3.61k
  /// Offsets of each of the macros into the bitstream, indexed by
2569
3.61k
  /// the local macro ID
2570
3.61k
  ///
2571
3.61k
  /// For each identifier that is associated with a macro, this map
2572
3.61k
  /// provides the offset into the bitstream where that macro is
2573
3.61k
  /// defined.
2574
3.61k
  std::vector<uint32_t> MacroOffsets;
2575
3.61k
2576
757k
  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; 
++I753k
) {
2577
753k
    const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2578
753k
    MacroInfo *MI = MacroInfosToEmit[I].MI;
2579
753k
    MacroID ID = MacroInfosToEmit[I].ID;
2580
753k
2581
753k
    if (ID < FirstMacroID) {
2582
0
      assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2583
0
      continue;
2584
0
    }
2585
753k
2586
753k
    // Record the local offset of this macro.
2587
753k
    unsigned Index = ID - FirstMacroID;
2588
753k
    if (Index == MacroOffsets.size())
2589
753k
      MacroOffsets.push_back(Stream.GetCurrentBitNo());
2590
0
    else {
2591
0
      if (Index > MacroOffsets.size())
2592
0
        MacroOffsets.resize(Index + 1);
2593
0
2594
0
      MacroOffsets[Index] = Stream.GetCurrentBitNo();
2595
0
    }
2596
753k
2597
753k
    AddIdentifierRef(Name, Record);
2598
753k
    AddSourceLocation(MI->getDefinitionLoc(), Record);
2599
753k
    AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2600
753k
    Record.push_back(MI->isUsed());
2601
753k
    Record.push_back(MI->isUsedForHeaderGuard());
2602
753k
    unsigned Code;
2603
753k
    if (MI->isObjectLike()) {
2604
740k
      Code = PP_MACRO_OBJECT_LIKE;
2605
740k
    } else {
2606
13.0k
      Code = PP_MACRO_FUNCTION_LIKE;
2607
13.0k
2608
13.0k
      Record.push_back(MI->isC99Varargs());
2609
13.0k
      Record.push_back(MI->isGNUVarargs());
2610
13.0k
      Record.push_back(MI->hasCommaPasting());
2611
13.0k
      Record.push_back(MI->getNumParams());
2612
13.0k
      for (const IdentifierInfo *Param : MI->params())
2613
39.1k
        AddIdentifierRef(Param, Record);
2614
13.0k
    }
2615
753k
2616
753k
    // If we have a detailed preprocessing record, record the macro definition
2617
753k
    // ID that corresponds to this macro.
2618
753k
    if (PPRec)
2619
44.4k
      Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2620
753k
2621
753k
    Stream.EmitRecord(Code, Record);
2622
753k
    Record.clear();
2623
753k
2624
753k
    // Emit the tokens array.
2625
2.02M
    for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; 
++TokNo1.26M
) {
2626
1.26M
      // Note that we know that the preprocessor does not have any annotation
2627
1.26M
      // tokens in it because they are created by the parser, and thus can't
2628
1.26M
      // be in a macro definition.
2629
1.26M
      const Token &Tok = MI->getReplacementToken(TokNo);
2630
1.26M
      AddToken(Tok, Record);
2631
1.26M
      Stream.EmitRecord(PP_TOKEN, Record);
2632
1.26M
      Record.clear();
2633
1.26M
    }
2634
753k
    ++NumMacros;
2635
753k
  }
2636
3.61k
2637
3.61k
  Stream.ExitBlock();
2638
3.61k
2639
3.61k
  // Write the offsets table for macro IDs.
2640
3.61k
  using namespace llvm;
2641
3.61k
2642
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2643
3.61k
  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2644
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2645
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2646
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2647
3.61k
2648
3.61k
  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2649
3.61k
  {
2650
3.61k
    RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2651
3.61k
                                       FirstMacroID - NUM_PREDEF_MACRO_IDS};
2652
3.61k
    Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2653
3.61k
  }
2654
3.61k
}
2655
2656
189
void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2657
189
  if (PPRec.local_begin() == PPRec.local_end())
2658
1
    return;
2659
188
2660
188
  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2661
188
2662
188
  // Enter the preprocessor block.
2663
188
  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2664
188
2665
188
  // If the preprocessor has a preprocessing record, emit it.
2666
188
  unsigned NumPreprocessingRecords = 0;
2667
188
  using namespace llvm;
2668
188
2669
188
  // Set up the abbreviation for
2670
188
  unsigned InclusionAbbrev = 0;
2671
188
  {
2672
188
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2673
188
    Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2674
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2675
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2676
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2677
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2678
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2679
188
    InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2680
188
  }
2681
188
2682
188
  unsigned FirstPreprocessorEntityID
2683
188
    = (Chain ? 
PPRec.getNumLoadedPreprocessedEntities()76
:
0112
)
2684
188
    + NUM_PREDEF_PP_ENTITY_IDS;
2685
188
  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2686
188
  RecordData Record;
2687
188
  for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2688
188
                                  EEnd = PPRec.local_end();
2689
60.8k
       E != EEnd;
2690
60.6k
       (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2691
60.6k
    Record.clear();
2692
60.6k
2693
60.6k
    PreprocessedEntityOffsets.push_back(
2694
60.6k
        PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2695
60.6k
2696
60.6k
    if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2697
60.4k
      // Record this macro definition's ID.
2698
60.4k
      MacroDefinitions[MD] = NextPreprocessorEntityID;
2699
60.4k
2700
60.4k
      AddIdentifierRef(MD->getName(), Record);
2701
60.4k
      Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2702
60.4k
      continue;
2703
60.4k
    }
2704
262
2705
262
    if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2706
38
      Record.push_back(ME->isBuiltinMacro());
2707
38
      if (ME->isBuiltinMacro())
2708
6
        AddIdentifierRef(ME->getName(), Record);
2709
32
      else
2710
32
        Record.push_back(MacroDefinitions[ME->getDefinition()]);
2711
38
      Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2712
38
      continue;
2713
38
    }
2714
224
2715
224
    if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2716
224
      Record.push_back(PPD_INCLUSION_DIRECTIVE);
2717
224
      Record.push_back(ID->getFileName().size());
2718
224
      Record.push_back(ID->wasInQuotes());
2719
224
      Record.push_back(static_cast<unsigned>(ID->getKind()));
2720
224
      Record.push_back(ID->importedModule());
2721
224
      SmallString<64> Buffer;
2722
224
      Buffer += ID->getFileName();
2723
224
      // Check that the FileEntry is not null because it was not resolved and
2724
224
      // we create a PCH even with compiler errors.
2725
224
      if (ID->getFile())
2726
222
        Buffer += ID->getFile()->getName();
2727
224
      Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2728
224
      continue;
2729
224
    }
2730
0
2731
0
    llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2732
0
  }
2733
188
  Stream.ExitBlock();
2734
188
2735
188
  // Write the offsets table for the preprocessing record.
2736
188
  if (NumPreprocessingRecords > 0) {
2737
188
    assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2738
188
2739
188
    // Write the offsets table for identifier IDs.
2740
188
    using namespace llvm;
2741
188
2742
188
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2743
188
    Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2744
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2745
188
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2746
188
    unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2747
188
2748
188
    RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2749
188
                                       FirstPreprocessorEntityID -
2750
188
                                           NUM_PREDEF_PP_ENTITY_IDS};
2751
188
    Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2752
188
                              bytes(PreprocessedEntityOffsets));
2753
188
  }
2754
188
2755
188
  // Write the skipped region table for the preprocessing record.
2756
188
  ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2757
188
  if (SkippedRanges.size() > 0) {
2758
31
    std::vector<PPSkippedRange> SerializedSkippedRanges;
2759
31
    SerializedSkippedRanges.reserve(SkippedRanges.size());
2760
31
    for (auto const& Range : SkippedRanges)
2761
45
      SerializedSkippedRanges.emplace_back(Range);
2762
31
2763
31
    using namespace llvm;
2764
31
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
2765
31
    Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2766
31
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2767
31
    unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2768
31
2769
31
    Record.clear();
2770
31
    Record.push_back(PPD_SKIPPED_RANGES);
2771
31
    Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2772
31
                              bytes(SerializedSkippedRanges));
2773
31
  }
2774
188
}
2775
2776
560k
unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2777
560k
  if (!Mod)
2778
239k
    return 0;
2779
320k
2780
320k
  llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2781
320k
  if (Known != SubmoduleIDs.end())
2782
317k
    return Known->second;
2783
3.66k
2784
3.66k
  auto *Top = Mod->getTopLevelModule();
2785
3.66k
  if (Top != WritingModule &&
2786
3.66k
      
(214
getLangOpts().CompilingPCH214
||
2787
214
       
!Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))212
))
2788
214
    return 0;
2789
3.45k
2790
3.45k
  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2791
3.45k
}
2792
2793
554k
unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2794
554k
  // FIXME: This can easily happen, if we have a reference to a submodule that
2795
554k
  // did not result in us loading a module file for that submodule. For
2796
554k
  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2797
554k
  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2798
554k
  assert((ID || !Mod) &&
2799
554k
         "asked for module ID for non-local, non-imported module");
2800
554k
  return ID;
2801
554k
}
2802
2803
/// Compute the number of modules within the given tree (including the
2804
/// given module).
2805
3.45k
static unsigned getNumberOfModules(Module *Mod) {
2806
3.45k
  unsigned ChildModules = 0;
2807
3.45k
  for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2808
5.41k
       Sub != SubEnd; 
++Sub1.96k
)
2809
1.96k
    ChildModules += getNumberOfModules(*Sub);
2810
3.45k
2811
3.45k
  return ChildModules + 1;
2812
3.45k
}
2813
2814
1.48k
void ASTWriter::WriteSubmodules(Module *WritingModule) {
2815
1.48k
  // Enter the submodule description block.
2816
1.48k
  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2817
1.48k
2818
1.48k
  // Write the abbreviations needed for the submodules block.
2819
1.48k
  using namespace llvm;
2820
1.48k
2821
1.48k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2822
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2823
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2824
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2825
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2826
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2827
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2828
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2829
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2830
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2831
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2832
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2833
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2834
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2835
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2836
1.48k
  unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2837
1.48k
2838
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2839
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2840
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2841
1.48k
  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2842
1.48k
2843
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2844
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2845
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2846
1.48k
  unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2847
1.48k
2848
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2849
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2850
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2851
1.48k
  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2852
1.48k
2853
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2854
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2855
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2856
1.48k
  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2857
1.48k
2858
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2859
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2860
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2861
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2862
1.48k
  unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2863
1.48k
2864
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2865
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2866
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2867
1.48k
  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2868
1.48k
2869
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2870
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2871
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2872
1.48k
  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2873
1.48k
2874
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2875
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2876
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2877
1.48k
  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2878
1.48k
2879
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2880
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2881
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2882
1.48k
  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2883
1.48k
2884
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2885
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2886
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2887
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2888
1.48k
  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2889
1.48k
2890
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2891
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2892
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2893
1.48k
  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2894
1.48k
2895
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2896
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2897
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2898
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2899
1.48k
  unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2900
1.48k
2901
1.48k
  Abbrev = std::make_shared<BitCodeAbbrev>();
2902
1.48k
  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2903
1.48k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2904
1.48k
  unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2905
1.48k
2906
1.48k
  // Write the submodule metadata block.
2907
1.48k
  RecordData::value_type Record[] = {
2908
1.48k
      getNumberOfModules(WritingModule),
2909
1.48k
      FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2910
1.48k
  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2911
1.48k
2912
1.48k
  // Write all of the submodules.
2913
1.48k
  std::queue<Module *> Q;
2914
1.48k
  Q.push(WritingModule);
2915
4.93k
  while (!Q.empty()) {
2916
3.45k
    Module *Mod = Q.front();
2917
3.45k
    Q.pop();
2918
3.45k
    unsigned ID = getSubmoduleID(Mod);
2919
3.45k
2920
3.45k
    uint64_t ParentID = 0;
2921
3.45k
    if (Mod->Parent) {
2922
1.96k
      assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2923
1.96k
      ParentID = SubmoduleIDs[Mod->Parent];
2924
1.96k
    }
2925
3.45k
2926
3.45k
    // Emit the definition of the block.
2927
3.45k
    {
2928
3.45k
      RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2929
3.45k
                                         ID,
2930
3.45k
                                         ParentID,
2931
3.45k
                                         (RecordData::value_type)Mod->Kind,
2932
3.45k
                                         Mod->IsFramework,
2933
3.45k
                                         Mod->IsExplicit,
2934
3.45k
                                         Mod->IsSystem,
2935
3.45k
                                         Mod->IsExternC,
2936
3.45k
                                         Mod->InferSubmodules,
2937
3.45k
                                         Mod->InferExplicitSubmodules,
2938
3.45k
                                         Mod->InferExportWildcard,
2939
3.45k
                                         Mod->ConfigMacrosExhaustive,
2940
3.45k
                                         Mod->ModuleMapIsPrivate};
2941
3.45k
      Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2942
3.45k
    }
2943
3.45k
2944
3.45k
    // Emit the requirements.
2945
3.45k
    for (const auto &R : Mod->Requirements) {
2946
533
      RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2947
533
      Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2948
533
    }
2949
3.45k
2950
3.45k
    // Emit the umbrella header, if there is one.
2951
3.45k
    if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2952
248
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2953
248
      Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2954
248
                                UmbrellaHeader.NameAsWritten);
2955
3.20k
    } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2956
19
      RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2957
19
      Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2958
19
                                UmbrellaDir.NameAsWritten);
2959
19
    }
2960
3.45k
2961
3.45k
    // Emit the headers.
2962
3.45k
    struct {
2963
3.45k
      unsigned RecordKind;
2964
3.45k
      unsigned Abbrev;
2965
3.45k
      Module::HeaderKind HeaderKind;
2966
3.45k
    } HeaderLists[] = {
2967
3.45k
      {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2968
3.45k
      {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2969
3.45k
      {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2970
3.45k
      {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2971
3.45k
        Module::HK_PrivateTextual},
2972
3.45k
      {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2973
3.45k
    };
2974
17.2k
    for (auto &HL : HeaderLists) {
2975
17.2k
      RecordData::value_type Record[] = {HL.RecordKind};
2976
17.2k
      for (auto &H : Mod->Headers[HL.HeaderKind])
2977
2.27k
        Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2978
17.2k
    }
2979
3.45k
2980
3.45k
    // Emit the top headers.
2981
3.45k
    {
2982
3.45k
      auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2983
3.45k
      RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2984
3.45k
      for (auto *H : TopHeaders)
2985
2.36k
        Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2986
3.45k
    }
2987
3.45k
2988
3.45k
    // Emit the imports.
2989
3.45k
    if (!Mod->Imports.empty()) {
2990
861
      RecordData Record;
2991
861
      for (auto *I : Mod->Imports)
2992
1.10k
        Record.push_back(getSubmoduleID(I));
2993
861
      Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2994
861
    }
2995
3.45k
2996
3.45k
    // Emit the exports.
2997
3.45k
    if (!Mod->Exports.empty()) {
2998
1.43k
      RecordData Record;
2999
1.45k
      for (const auto &E : Mod->Exports) {
3000
1.45k
        // FIXME: This may fail; we don't require that all exported modules
3001
1.45k
        // are local or imported.
3002
1.45k
        Record.push_back(getSubmoduleID(E.getPointer()));
3003
1.45k
        Record.push_back(E.getInt());
3004
1.45k
      }
3005
1.43k
      Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
3006
1.43k
    }
3007
3.45k
3008
3.45k
    //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
3009
3.45k
    // Might be unnecessary as use declarations are only used to build the
3010
3.45k
    // module itself.
3011
3.45k
3012
3.45k
    // Emit the link libraries.
3013
3.45k
    for (const auto &LL : Mod->LinkLibraries) {
3014
102
      RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3015
102
                                         LL.IsFramework};
3016
102
      Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3017
102
    }
3018
3.45k
3019
3.45k
    // Emit the conflicts.
3020
3.45k
    for (const auto &C : Mod->Conflicts) {
3021
1
      // FIXME: This may fail; we don't require that all conflicting modules
3022
1
      // are local or imported.
3023
1
      RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3024
1
                                         getSubmoduleID(C.Other)};
3025
1
      Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3026
1
    }
3027
3.45k
3028
3.45k
    // Emit the configuration macros.
3029
3.45k
    for (const auto &CM : Mod->ConfigMacros) {
3030
2
      RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3031
2
      Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3032
2
    }
3033
3.45k
3034
3.45k
    // Emit the initializers, if any.
3035
3.45k
    RecordData Inits;
3036
3.45k
    for (Decl *D : Context->getModuleInitializers(Mod))
3037
326
      Inits.push_back(GetDeclRef(D));
3038
3.45k
    if (!Inits.empty())
3039
195
      Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3040
3.45k
3041
3.45k
    // Emit the name of the re-exported module, if any.
3042
3.45k
    if (!Mod->ExportAsModule.empty()) {
3043
6
      RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3044
6
      Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3045
6
    }
3046
3.45k
3047
3.45k
    // Queue up the submodules of this module.
3048
3.45k
    for (auto *M : Mod->submodules())
3049
1.96k
      Q.push(M);
3050
3.45k
  }
3051
1.48k
3052
1.48k
  Stream.ExitBlock();
3053
1.48k
3054
1.48k
  assert((NextSubmoduleID - FirstSubmoduleID ==
3055
1.48k
          getNumberOfModules(WritingModule)) &&
3056
1.48k
         "Wrong # of submodules; found a reference to a non-local, "
3057
1.48k
         "non-imported submodule?");
3058
1.48k
}
3059
3060
void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3061
3.61k
                                              bool isModule) {
3062
3.61k
  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3063
3.61k
      DiagStateIDMap;
3064
3.61k
  unsigned CurrID = 0;
3065
3.61k
  RecordData Record;
3066
3.61k
3067
3.61k
  auto EncodeDiagStateFlags =
3068
3.61k
      [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3069
3.61k
    unsigned Result = (unsigned)DS->ExtBehavior;
3070
3.61k
    for (unsigned Val :
3071
3.61k
         {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3072
3.61k
          (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3073
3.61k
          (unsigned)DS->SuppressSystemWarnings})
3074
18.0k
      Result = (Result << 1) | Val;
3075
3.61k
    return Result;
3076
3.61k
  };
3077
3.61k
3078
3.61k
  unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3079
3.61k
  Record.push_back(Flags);
3080
3.61k
3081
3.61k
  auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3082
7.35k
                          bool IncludeNonPragmaStates) {
3083
7.35k
    // Ensure that the diagnostic state wasn't modified since it was created.
3084
7.35k
    // We will not correctly round-trip this information otherwise.
3085
7.35k
    assert(Flags == EncodeDiagStateFlags(State) &&
3086
7.35k
           "diag state flags vary in single AST file");
3087
7.35k
3088
7.35k
    unsigned &DiagStateID = DiagStateIDMap[State];
3089
7.35k
    Record.push_back(DiagStateID);
3090
7.35k
3091
7.35k
    if (DiagStateID == 0) {
3092
3.70k
      DiagStateID = ++CurrID;
3093
3.70k
3094
3.70k
      // Add a placeholder for the number of mappings.
3095
3.70k
      auto SizeIdx = Record.size();
3096
3.70k
      Record.emplace_back();
3097
91.4k
      for (const auto &I : *State) {
3098
91.4k
        if (I.second.isPragma() || 
IncludeNonPragmaStates86.8k
) {
3099
32.3k
          Record.push_back(I.first);
3100
32.3k
          Record.push_back(I.second.serialize());
3101
32.3k
        }
3102
91.4k
      }
3103
3.70k
      // Update the placeholder.
3104
3.70k
      Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3105
3.70k
    }
3106
7.35k
  };
3107
3.61k
3108
3.61k
  AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3109
3.61k
3110
3.61k
  // Reserve a spot for the number of locations with state transitions.
3111
3.61k
  auto NumLocationsIdx = Record.size();
3112
3.61k
  Record.emplace_back();
3113
3.61k
3114
3.61k
  // Emit the state transitions.
3115
3.61k
  unsigned NumLocations = 0;
3116
3.61k
  for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3117
1.60k
    if (!FileIDAndFile.first.isValid() ||
3118
1.60k
        
!FileIDAndFile.second.HasLocalTransitions1.42k
)
3119
1.54k
      continue;
3120
60
    ++NumLocations;
3121
60
3122
60
    SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3123
60
    assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3124
60
    AddSourceLocation(Loc, Record);
3125
60
3126
60
    Record.push_back(FileIDAndFile.second.StateTransitions.size());
3127
122
    for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3128
122
      Record.push_back(StatePoint.Offset);
3129
122
      AddDiagState(StatePoint.State, false);
3130
122
    }
3131
60
  }
3132
3.61k
3133
3.61k
  // Backpatch the number of locations.
3134
3.61k
  Record[NumLocationsIdx] = NumLocations;
3135
3.61k
3136
3.61k
  // Emit CurDiagStateLoc.  Do it last in order to match source order.
3137
3.61k
  //
3138
3.61k
  // This also protects against a hypothetical corner case with simulating
3139
3.61k
  // -Werror settings for implicit modules in the ASTReader, where reading
3140
3.61k
  // CurDiagState out of context could change whether warning pragmas are
3141
3.61k
  // treated as errors.
3142
3.61k
  AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3143
3.61k
  AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3144
3.61k
3145
3.61k
  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3146
3.61k
}
3147
3148
//===----------------------------------------------------------------------===//
3149
// Type Serialization
3150
//===----------------------------------------------------------------------===//
3151
3152
/// Write the representation of a type to the AST stream.
3153
155k
void ASTWriter::WriteType(QualType T) {
3154
155k
  TypeIdx &IdxRef = TypeIdxs[T];
3155
155k
  if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3156
0
    IdxRef = TypeIdx(NextTypeID++);
3157
155k
  TypeIdx Idx = IdxRef;
3158
155k
3159
155k
  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3160
155k
3161
155k
  RecordData Record;
3162
155k
3163
155k
  // Emit the type's representation.
3164
155k
  ASTTypeWriter W(*this, Record);
3165
155k
  W.Visit(T);
3166
155k
  uint64_t Offset = W.Emit();
3167
155k
3168
155k
  // Record the offset for this type.
3169
155k
  unsigned Index = Idx.getIndex() - FirstTypeID;
3170
155k
  if (TypeOffsets.size() == Index)
3171
155k
    TypeOffsets.push_back(Offset);
3172
0
  else if (TypeOffsets.size() < Index) {
3173
0
    TypeOffsets.resize(Index + 1);
3174
0
    TypeOffsets[Index] = Offset;
3175
0
  } else {
3176
0
    llvm_unreachable("Types emitted in wrong order");
3177
0
  }
3178
155k
}
3179
3180
//===----------------------------------------------------------------------===//
3181
// Declaration Serialization
3182
//===----------------------------------------------------------------------===//
3183
3184
/// Write the block containing all of the declaration IDs
3185
/// lexically declared within the given DeclContext.
3186
///
3187
/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3188
/// bitstream, or 0 if no block was written.
3189
uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3190
164k
                                                 DeclContext *DC) {
3191
164k
  if (DC->decls_empty())
3192
91.0k
    return 0;
3193
73.9k
3194
73.9k
  uint64_t Offset = Stream.GetCurrentBitNo();
3195
73.9k
  SmallVector<uint32_t, 128> KindDeclPairs;
3196
274k
  for (const auto *D : DC->decls()) {
3197
274k
    KindDeclPairs.push_back(D->getKind());
3198
274k
    KindDeclPairs.push_back(GetDeclRef(D));
3199
274k
  }
3200
73.9k
3201
73.9k
  ++NumLexicalDeclContexts;
3202
73.9k
  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3203
73.9k
  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3204
73.9k
                            bytes(KindDeclPairs));
3205
73.9k
  return Offset;
3206
73.9k
}
3207
3208
3.61k
void ASTWriter::WriteTypeDeclOffsets() {
3209
3.61k
  using namespace llvm;
3210
3.61k
3211
3.61k
  // Write the type offsets array
3212
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3213
3.61k
  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3214
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3215
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3216
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3217
3.61k
  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3218
3.61k
  {
3219
3.61k
    RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3220
3.61k
                                       FirstTypeID - NUM_PREDEF_TYPE_IDS};
3221
3.61k
    Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3222
3.61k
  }
3223
3.61k
3224
3.61k
  // Write the declaration offsets array
3225
3.61k
  Abbrev = std::make_shared<BitCodeAbbrev>();
3226
3.61k
  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3227
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3228
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3229
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3230
3.61k
  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3231
3.61k
  {
3232
3.61k
    RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3233
3.61k
                                       FirstDeclID - NUM_PREDEF_DECL_IDS};
3234
3.61k
    Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3235
3.61k
  }
3236
3.61k
}
3237
3238
3.61k
void ASTWriter::WriteFileDeclIDsMap() {
3239
3.61k
  using namespace llvm;
3240
3.61k
3241
3.61k
  SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3242
3.61k
      FileDeclIDs.begin(), FileDeclIDs.end());
3243
3.61k
  llvm::sort(SortedFileDeclIDs, llvm::less_first());
3244
3.61k
3245
3.61k
  // Join the vectors of DeclIDs from all files.
3246
3.61k
  SmallVector<DeclID, 256> FileGroupedDeclIDs;
3247
5.10k
  for (auto &FileDeclEntry : SortedFileDeclIDs) {
3248
5.10k
    DeclIDInFileInfo &Info = *FileDeclEntry.second;
3249
5.10k
    Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3250
5.10k
    for (auto &LocDeclEntry : Info.DeclIDs)
3251
122k
      FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3252
5.10k
  }
3253
3.61k
3254
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3255
3.61k
  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3256
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3257
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3258
3.61k
  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3259
3.61k
  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3260
3.61k
                                     FileGroupedDeclIDs.size()};
3261
3.61k
  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3262
3.61k
}
3263
3264
3.61k
void ASTWriter::WriteComments() {
3265
3.61k
  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3266
3.61k
  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3267
3.61k
  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3268
0
    return;
3269
3.61k
  ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
3270
3.61k
  RecordData Record;
3271
4.35k
  for (const auto *I : RawComments) {
3272
4.35k
    Record.clear();
3273
4.35k
    AddSourceRange(I->getSourceRange(), Record);
3274
4.35k
    Record.push_back(I->getKind());
3275
4.35k
    Record.push_back(I->isTrailingComment());
3276
4.35k
    Record.push_back(I->isAlmostTrailingComment());
3277
4.35k
    Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3278
4.35k
  }
3279
3.61k
}
3280
3281
//===----------------------------------------------------------------------===//
3282
// Global Method Pool and Selector Serialization
3283
//===----------------------------------------------------------------------===//
3284
3285
namespace {
3286
3287
// Trait used for the on-disk hash table used in the method pool.
3288
class ASTMethodPoolTrait {
3289
  ASTWriter &Writer;
3290
3291
public:
3292
  using key_type = Selector;
3293
  using key_type_ref = key_type;
3294
3295
  struct data_type {
3296
    SelectorID ID;
3297
    ObjCMethodList Instance, Factory;
3298
  };
3299
  using data_type_ref = const data_type &;
3300
3301
  using hash_value_type = unsigned;
3302
  using offset_type = unsigned;
3303
3304
352
  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3305
3306
550
  static hash_value_type ComputeHash(Selector Sel) {
3307
550
    return serialization::ComputeHash(Sel);
3308
550
  }
3309
3310
  std::pair<unsigned, unsigned>
3311
    EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3312
550
                      data_type_ref Methods) {
3313
550
    using namespace llvm::support;
3314
550
3315
550
    endian::Writer LE(Out, little);
3316
550
    unsigned KeyLen = 2 + (Sel.getNumArgs()? 
Sel.getNumArgs() * 4157
:
4393
);
3317
550
    LE.write<uint16_t>(KeyLen);
3318
550
    unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3319
1.13k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3320
583
         Method = Method->getNext())
3321
583
      if (Method->getMethod())
3322
381
        DataLen += 4;
3323
1.10k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3324
556
         Method = Method->getNext())
3325
556
      if (Method->getMethod())
3326
202
        DataLen += 4;
3327
550
    LE.write<uint16_t>(DataLen);
3328
550
    return std::make_pair(KeyLen, DataLen);
3329
550
  }
3330
3331
550
  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3332
550
    using namespace llvm::support;
3333
550
3334
550
    endian::Writer LE(Out, little);
3335
550
    uint64_t Start = Out.tell();
3336
550
    assert((Start >> 32) == 0 && "Selector key offset too large");
3337
550
    Writer.SetSelectorOffset(Sel, Start);
3338
550
    unsigned N = Sel.getNumArgs();
3339
550
    LE.write<uint16_t>(N);
3340
550
    if (N == 0)
3341
393
      N = 1;
3342
1.13k
    for (unsigned I = 0; I != N; 
++I581
)
3343
581
      LE.write<uint32_t>(
3344
581
          Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3345
550
  }
3346
3347
  void EmitData(raw_ostream& Out, key_type_ref,
3348
550
                data_type_ref Methods, unsigned DataLen) {
3349
550
    using namespace llvm::support;
3350
550
3351
550
    endian::Writer LE(Out, little);
3352
550
    uint64_t Start = Out.tell(); (void)Start;
3353
550
    LE.write<uint32_t>(Methods.ID);
3354
550
    unsigned NumInstanceMethods = 0;
3355
1.13k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3356
583
         Method = Method->getNext())
3357
583
      if (Method->getMethod())
3358
381
        ++NumInstanceMethods;
3359
550
3360
550
    unsigned NumFactoryMethods = 0;
3361
1.10k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3362
556
         Method = Method->getNext())
3363
556
      if (Method->getMethod())
3364
202
        ++NumFactoryMethods;
3365
550
3366
550
    unsigned InstanceBits = Methods.Instance.getBits();
3367
550
    assert(InstanceBits < 4);
3368
550
    unsigned InstanceHasMoreThanOneDeclBit =
3369
550
        Methods.Instance.hasMoreThanOneDecl();
3370
550
    unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3371
550
                                (InstanceHasMoreThanOneDeclBit << 2) |
3372
550
                                InstanceBits;
3373
550
    unsigned FactoryBits = Methods.Factory.getBits();
3374
550
    assert(FactoryBits < 4);
3375
550
    unsigned FactoryHasMoreThanOneDeclBit =
3376
550
        Methods.Factory.hasMoreThanOneDecl();
3377
550
    unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3378
550
                               (FactoryHasMoreThanOneDeclBit << 2) |
3379
550
                               FactoryBits;
3380
550
    LE.write<uint16_t>(FullInstanceBits);
3381
550
    LE.write<uint16_t>(FullFactoryBits);
3382
1.13k
    for (const ObjCMethodList *Method = &Methods.Instance; Method;
3383
583
         Method = Method->getNext())
3384
583
      if (Method->getMethod())
3385
381
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3386
1.10k
    for (const ObjCMethodList *Method = &Methods.Factory; Method;
3387
556
         Method = Method->getNext())
3388
556
      if (Method->getMethod())
3389
202
        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3390
550
3391
550
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3392
550
  }
3393
};
3394
3395
} // namespace
3396
3397
/// Write ObjC data: selectors and the method pool.
3398
///
3399
/// The method pool contains both instance and factory methods, stored
3400
/// in an on-disk hash table indexed by the selector. The hash table also
3401
/// contains an empty entry for every other selector known to Sema.
3402
3.61k
void ASTWriter::WriteSelectors(Sema &SemaRef) {
3403
3.61k
  using namespace llvm;
3404
3.61k
3405
3.61k
  // Do we have to do anything at all?
3406
3.61k
  if (SemaRef.MethodPool.empty() && 
SelectorIDs.empty()3.44k
)
3407
3.44k
    return;
3408
176
  unsigned NumTableEntries = 0;
3409
176
  // Create and write out the blob that contains selectors and the method pool.
3410
176
  {
3411
176
    llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3412
176
    ASTMethodPoolTrait Trait(*this);
3413
176
3414
176
    // Create the on-disk hash table representation. We walk through every
3415
176
    // selector we've seen and look it up in the method pool.
3416
176
    SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3417
555
    for (auto &SelectorAndID : SelectorIDs) {
3418
555
      Selector S = SelectorAndID.first;
3419
555
      SelectorID ID = SelectorAndID.second;
3420
555
      Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3421
555
      ASTMethodPoolTrait::data_type Data = {
3422
555
        ID,
3423
555
        ObjCMethodList(),
3424
555
        ObjCMethodList()
3425
555
      };
3426
555
      if (F != SemaRef.MethodPool.end()) {
3427
539
        Data.Instance = F->second.first;
3428
539
        Data.Factory = F->second.second;
3429
539
      }
3430
555
      // Only write this selector if it's not in an existing AST or something
3431
555
      // changed.
3432
555
      if (Chain && 
ID < FirstSelectorID300
) {
3433
14
        // Selector already exists. Did it change?
3434
14
        bool changed = false;
3435
14
        for (ObjCMethodList *M = &Data.Instance;
3436
32
             !changed && 
M23
&&
M->getMethod()21
;
M = M->getNext()18
) {
3437
18
          if (!M->getMethod()->isFromASTFile())
3438
9
            changed = true;
3439
18
        }
3440
14
        for (ObjCMethodList *M = &Data.Factory; !changed && 
M5
&&
M->getMethod()5
;
3441
14
             
M = M->getNext()0
) {
3442
0
          if (!M->getMethod()->isFromASTFile())
3443
0
            changed = true;
3444
0
        }
3445
14
        if (!changed)
3446
5
          continue;
3447
541
      } else if (Data.Instance.getMethod() || 
Data.Factory.getMethod()202
) {
3448
528
        // A new method pool entry.
3449
528
        ++NumTableEntries;
3450
528
      }
3451
555
      Generator.insert(S, Data, Trait);
3452
550
    }
3453
176
3454
176
    // Create the on-disk hash table in a buffer.
3455
176
    SmallString<4096> MethodPool;
3456
176
    uint32_t BucketOffset;
3457
176
    {
3458
176
      using namespace llvm::support;
3459
176
3460
176
      ASTMethodPoolTrait Trait(*this);
3461
176
      llvm::raw_svector_ostream Out(MethodPool);
3462
176
      // Make sure that no bucket is at offset 0
3463
176
      endian::write<uint32_t>(Out, 0, little);
3464
176
      BucketOffset = Generator.Emit(Out, Trait);
3465
176
    }
3466
176
3467
176
    // Create a blob abbreviation
3468
176
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3469
176
    Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3470
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3471
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3472
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3473
176
    unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3474
176
3475
176
    // Write the method pool
3476
176
    {
3477
176
      RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3478
176
                                         NumTableEntries};
3479
176
      Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3480
176
    }
3481
176
3482
176
    // Create a blob abbreviation for the selector table offsets.
3483
176
    Abbrev = std::make_shared<BitCodeAbbrev>();
3484
176
    Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3485
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3486
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3487
176
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3488
176
    unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3489
176
3490
176
    // Write the selector offsets table.
3491
176
    {
3492
176
      RecordData::value_type Record[] = {
3493
176
          SELECTOR_OFFSETS, SelectorOffsets.size(),
3494
176
          FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3495
176
      Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3496
176
                                bytes(SelectorOffsets));
3497
176
    }
3498
176
  }
3499
176
}
3500
3501
/// Write the selectors referenced in @selector expression into AST file.
3502
3.61k
void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3503
3.61k
  using namespace llvm;
3504
3.61k
3505
3.61k
  if (SemaRef.ReferencedSelectors.empty())
3506
3.61k
    return;
3507
2
3508
2
  RecordData Record;
3509
2
  ASTRecordWriter Writer(*this, Record);
3510
2
3511
2
  // Note: this writes out all references even for a dependent AST. But it is
3512
2
  // very tricky to fix, and given that @selector shouldn't really appear in
3513
2
  // headers, probably not worth it. It's not a correctness issue.
3514
2
  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3515
2
    Selector Sel = SelectorAndLocation.first;
3516
2
    SourceLocation Loc = SelectorAndLocation.second;
3517
2
    Writer.AddSelectorRef(Sel);
3518
2
    Writer.AddSourceLocation(Loc);
3519
2
  }
3520
2
  Writer.Emit(REFERENCED_SELECTOR_POOL);
3521
2
}
3522
3523
//===----------------------------------------------------------------------===//
3524
// Identifier Table Serialization
3525
//===----------------------------------------------------------------------===//
3526
3527
/// Determine the declaration that should be put into the name lookup table to
3528
/// represent the given declaration in this module. This is usually D itself,
3529
/// but if D was imported and merged into a local declaration, we want the most
3530
/// recent local declaration instead. The chosen declaration will be the most
3531
/// recent declaration in any module that imports this one.
3532
static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3533
180k
                                        NamedDecl *D) {
3534
180k
  if (!LangOpts.Modules || 
!D->isFromASTFile()124k
)
3535
174k
    return D;
3536
6.67k
3537
6.67k
  if (Decl *Redecl = D->getPreviousDecl()) {
3538
3.81k
    // For Redeclarable decls, a prior declaration might be local.
3539
22.5k
    for (; Redecl; 
Redecl = Redecl->getPreviousDecl()18.7k
) {
3540
19.0k
      // If we find a local decl, we're done.
3541
19.0k
      if (!Redecl->isFromASTFile()) {
3542
340
        // Exception: in very rare cases (for injected-class-names), not all
3543
340
        // redeclarations are in the same semantic context. Skip ones in a
3544
340
        // different context. They don't go in this lookup table at all.
3545
340
        if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3546
340
                D->getDeclContext()->getRedeclContext()))
3547
11
          continue;
3548
329
        return cast<NamedDecl>(Redecl);
3549
329
      }
3550
18.7k
3551
18.7k
      // If we find a decl from a (chained-)PCH stop since we won't find a
3552
18.7k
      // local one.
3553
18.7k
      if (Redecl->getOwningModuleID() == 0)
3554
3
        break;
3555
18.7k
    }
3556
3.81k
  } else 
if (Decl *2.86k
First2.86k
= D->getCanonicalDecl()) {
3557
2.86k
    // For Mergeable decls, the first decl might be local.
3558
2.86k
    if (!First->isFromASTFile())
3559
84
      return cast<NamedDecl>(First);
3560
6.26k
  }
3561
6.26k
3562
6.26k
  // All declarations are imported. Our most recent declaration will also be
3563
6.26k
  // the most recent one in anyone who imports us.
3564
6.26k
  return D;
3565
6.26k
}
3566
3567
namespace {
3568
3569
class ASTIdentifierTableTrait {
3570
  ASTWriter &Writer;
3571
  Preprocessor &PP;
3572
  IdentifierResolver &IdResolver;
3573
  bool IsModule;
3574
  bool NeedDecls;
3575
  ASTWriter::RecordData *InterestingIdentifierOffsets;
3576
3577
  /// Determines whether this is an "interesting" identifier that needs a
3578
  /// full IdentifierInfo structure written into the hash table. Notably, this
3579
  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3580
  /// to check that.
3581
22.5M
  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3582
22.5M
    if (MacroOffset ||
3583
22.5M
        
II->isPoisoned()21.0M
||
3584
22.5M
        
(IsModule 21.0M
?
II->hasRevertedBuiltin()5.28M
:
II->getObjCOrBuiltinID()15.7M
) ||
3585
22.5M
        
II->hasRevertedTokenIDToIdentifier()6.81M
||
3586
22.5M
        
(6.81M
NeedDecls6.81M
&&
II->getFETokenInfo()3.69M
))
3587
15.9M
      return true;
3588
6.57M
3589
6.57M
    return false;
3590
6.57M
  }
3591
3592
public:
3593
  using key_type = IdentifierInfo *;
3594
  using key_type_ref = key_type;
3595
3596
  using data_type = IdentID;
3597
  using data_type_ref = data_type;
3598
3599
  using hash_value_type = unsigned;
3600
  using offset_type = unsigned;
3601
3602
  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3603
                          IdentifierResolver &IdResolver, bool IsModule,
3604
                          ASTWriter::RecordData *InterestingIdentifierOffsets)
3605
      : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3606
        NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3607
3.61k
        InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3608
3609
14.3k
  bool needDecls() const { return NeedDecls; }
3610
3611
5.65M
  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3612
5.65M
    return llvm::djbHash(II->getName());
3613
5.65M
  }
3614
3615
10.5k
  bool isInterestingIdentifier(const IdentifierInfo *II) {
3616
10.5k
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3617
10.5k
    return isInterestingIdentifier(II, MacroOffset);
3618
10.5k
  }
3619
3620
11.2M
  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3621
11.2M
    return isInterestingIdentifier(II, 0);
3622
11.2M
  }
3623
3624
  std::pair<unsigned, unsigned>
3625
5.65M
  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3626
5.65M
    unsigned KeyLen = II->getLength() + 1;
3627
5.65M
    unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3628
5.65M
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3629
5.65M
    if (isInterestingIdentifier(II, MacroOffset)) {
3630
5.56M
      DataLen += 2; // 2 bytes for builtin ID
3631
5.56M
      DataLen += 2; // 2 bytes for flags
3632
5.56M
      if (MacroOffset)
3633
753k
        DataLen += 4; // MacroDirectives offset.
3634
5.56M
3635
5.56M
      if (NeedDecls) {
3636
5.56M
        for (IdentifierResolver::iterator D = IdResolver.begin(II),
3637
5.56M
                                       DEnd = IdResolver.end();
3638
5.68M
             D != DEnd; 
++D121k
)
3639
121k
          DataLen += 4;
3640
5.56M
      }
3641
5.56M
    }
3642
5.65M
3643
5.65M
    using namespace llvm::support;
3644
5.65M
3645
5.65M
    endian::Writer LE(Out, little);
3646
5.65M
3647
5.65M
    assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3648
5.65M
    LE.write<uint16_t>(DataLen);
3649
5.65M
    // We emit the key length after the data length so that every
3650
5.65M
    // string is preceded by a 16-bit length. This matches the PTH
3651
5.65M
    // format for storing identifiers.
3652
5.65M
    LE.write<uint16_t>(KeyLen);
3653
5.65M
    return std::make_pair(KeyLen, DataLen);
3654
5.65M
  }
3655
3656
  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3657
5.65M
               unsigned KeyLen) {
3658
5.65M
    // Record the location of the key data.  This is used when generating
3659
5.65M
    // the mapping from persistent IDs to strings.
3660
5.65M
    Writer.SetIdentifierOffset(II, Out.tell());
3661
5.65M
3662
5.65M
    // Emit the offset of the key/data length information to the interesting
3663
5.65M
    // identifiers table if necessary.
3664
5.65M
    if (InterestingIdentifierOffsets && 
isInterestingIdentifier(II)10.5k
)
3665
1.69k
      InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3666
5.65M
3667
5.65M
    Out.write(II->getNameStart(), KeyLen);
3668
5.65M
  }
3669
3670
  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3671
5.65M
                IdentID ID, unsigned) {
3672
5.65M
    using namespace llvm::support;
3673
5.65M
3674
5.65M
    endian::Writer LE(Out, little);
3675
5.65M
3676
5.65M
    auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3677
5.65M
    if (!isInterestingIdentifier(II, MacroOffset)) {
3678
93.6k
      LE.write<uint32_t>(ID << 1);
3679
93.6k
      return;
3680
93.6k
    }
3681
5.56M
3682
5.56M
    LE.write<uint32_t>((ID << 1) | 0x01);
3683
5.56M
    uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3684
5.56M
    assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3685
5.56M
    LE.write<uint16_t>(Bits);
3686
5.56M
    Bits = 0;
3687
5.56M
    bool HadMacroDefinition = MacroOffset != 0;
3688
5.56M
    Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3689
5.56M
    Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3690
5.56M
    Bits = (Bits << 1) | unsigned(II->isPoisoned());
3691
5.56M
    Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3692
5.56M
    Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3693
5.56M
    Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3694
5.56M
    LE.write<uint16_t>(Bits);
3695
5.56M
3696
5.56M
    if (HadMacroDefinition)
3697
753k
      LE.write<uint32_t>(MacroOffset);
3698
5.56M
3699
5.56M
    if (NeedDecls) {
3700
5.56M
      // Emit the declaration IDs in reverse order, because the
3701
5.56M
      // IdentifierResolver provides the declarations as they would be
3702
5.56M
      // visible (e.g., the function "stat" would come before the struct
3703
5.56M
      // "stat"), but the ASTReader adds declarations to the end of the list
3704
5.56M
      // (so we need to see the struct "stat" before the function "stat").
3705
5.56M
      // Only emit declarations that aren't from a chained PCH, though.
3706
5.56M
      SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3707
5.56M
                                         IdResolver.end());
3708
5.56M
      for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3709
5.56M
                                                          DEnd = Decls.rend();
3710
5.68M
           D != DEnd; 
++D121k
)
3711
121k
        LE.write<uint32_t>(
3712
121k
            Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3713
5.56M
    }
3714
5.56M
  }
3715
};
3716
3717
} // namespace
3718
3719
/// Write the identifier table into the AST file.
3720
///
3721
/// The identifier table consists of a blob containing string data
3722
/// (the actual identifiers themselves) and a separate "offsets" index
3723
/// that maps identifier IDs to locations within the blob.
3724
void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3725
                                     IdentifierResolver &IdResolver,
3726
3.61k
                                     bool IsModule) {
3727
3.61k
  using namespace llvm;
3728
3.61k
3729
3.61k
  RecordData InterestingIdents;
3730
3.61k
3731
3.61k
  // Create and write out the blob that contains the identifier
3732
3.61k
  // strings.
3733
3.61k
  {
3734
3.61k
    llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3735
3.61k
    ASTIdentifierTableTrait Trait(
3736
3.61k
        *this, PP, IdResolver, IsModule,
3737
3.61k
        (getLangOpts().CPlusPlus && 
IsModule2.67k
) ?
&InterestingIdents897
:
nullptr2.72k
);
3738
3.61k
3739
3.61k
    // Look for any identifiers that were named while processing the
3740
3.61k
    // headers, but are otherwise not needed. We add these to the hash
3741
3.61k
    // table to enable checking of the predefines buffer in the case
3742
3.61k
    // where the user adds new macro definitions when building the AST
3743
3.61k
    // file.
3744
3.61k
    SmallVector<const IdentifierInfo *, 128> IIs;
3745
3.61k
    for (const auto &ID : PP.getIdentifierTable())
3746
11.2M
      IIs.push_back(ID.second);
3747
3.61k
    // Sort the identifiers lexicographically before getting them references so
3748
3.61k
    // that their order is stable.
3749
3.61k
    llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
3750
3.61k
    for (const IdentifierInfo *II : IIs)
3751
11.2M
      if (Trait.isInterestingNonMacroIdentifier(II))
3752
4.81M
        getIdentifierRef(II);
3753
3.61k
3754
3.61k
    // Create the on-disk hash table representation. We only store offsets
3755
3.61k
    // for identifiers that appear here for the first time.
3756
3.61k
    IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3757
5.66M
    for (auto IdentIDPair : IdentifierIDs) {
3758
5.66M
      auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3759
5.66M
      IdentID ID = IdentIDPair.second;
3760
5.66M
      assert(II && "NULL identifier in identifier table");
3761
5.66M
      // Write out identifiers if either the ID is local or the identifier has
3762
5.66M
      // changed since it was loaded.
3763
5.66M
      if (ID >= FirstIdentID || 
!Chain22.5k
||
!II->isFromAST()22.5k
3764
5.66M
          || 
II->hasChangedSinceDeserialization()22.5k
||
3765
5.66M
          
(14.3k
Trait.needDecls()14.3k
&&
3766
14.3k
           
II->hasFETokenInfoChangedSinceDeserialization()11.5k
))
3767
5.65M
        Generator.insert(II, ID, Trait);
3768
5.66M
    }
3769
3.61k
3770
3.61k
    // Create the on-disk hash table in a buffer.
3771
3.61k
    SmallString<4096> IdentifierTable;
3772
3.61k
    uint32_t BucketOffset;
3773
3.61k
    {
3774
3.61k
      using namespace llvm::support;
3775
3.61k
3776
3.61k
      llvm::raw_svector_ostream Out(IdentifierTable);
3777
3.61k
      // Make sure that no bucket is at offset 0
3778
3.61k
      endian::write<uint32_t>(Out, 0, little);
3779
3.61k
      BucketOffset = Generator.Emit(Out, Trait);
3780
3.61k
    }
3781
3.61k
3782
3.61k
    // Create a blob abbreviation
3783
3.61k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
3784
3.61k
    Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3785
3.61k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3786
3.61k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3787
3.61k
    unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3788
3.61k
3789
3.61k
    // Write the identifier table
3790
3.61k
    RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3791
3.61k
    Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3792
3.61k
  }
3793
3.61k
3794
3.61k
  // Write the offsets table for identifier IDs.
3795
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3796
3.61k
  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3797
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3798
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3799
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3800
3.61k
  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3801
3.61k
3802
#ifndef NDEBUG
3803
  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3804
    assert(IdentifierOffsets[I] && "Missing identifier offset?");
3805
#endif
3806
3807
3.61k
  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3808
3.61k
                                     IdentifierOffsets.size(),
3809
3.61k
                                     FirstIdentID - NUM_PREDEF_IDENT_IDS};
3810
3.61k
  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3811
3.61k
                            bytes(IdentifierOffsets));
3812
3.61k
3813
3.61k
  // In C++, write the list of interesting identifiers (those that are
3814
3.61k
  // defined as macros, poisoned, or similar unusual things).
3815
3.61k
  if (!InterestingIdents.empty())
3816
897
    Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3817
3.61k
}
3818
3819
//===----------------------------------------------------------------------===//
3820
// DeclContext's Name Lookup Table Serialization
3821
//===----------------------------------------------------------------------===//
3822
3823
namespace {
3824
3825
// Trait used for the on-disk hash table used in the method pool.
3826
class ASTDeclContextNameLookupTrait {
3827
  ASTWriter &Writer;
3828
  llvm::SmallVector<DeclID, 64> DeclIDs;
3829
3830
public:
3831
  using key_type = DeclarationNameKey;
3832
  using key_type_ref = key_type;
3833
3834
  /// A start and end index into DeclIDs, representing a sequence of decls.
3835
  using data_type = std::pair<unsigned, unsigned>;
3836
  using data_type_ref = const data_type &;
3837
3838
  using hash_value_type = unsigned;
3839
  using offset_type = unsigned;
3840
3841
11.0k
  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3842
3843
  template<typename Coll>
3844
50.3k
  data_type getData(const Coll &Decls) {
3845
50.3k
    unsigned Start = DeclIDs.size();
3846
59.6k
    for (NamedDecl *D : Decls) {
3847
59.6k
      DeclIDs.push_back(
3848
59.6k
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3849
59.6k
    }
3850
50.3k
    return std::make_pair(Start, DeclIDs.size());
3851
50.3k
  }
ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<clang::DeclContextLookupResult>(clang::DeclContextLookupResult const&)
Line
Count
Source
3844
46.7k
  data_type getData(const Coll &Decls) {
3845
46.7k
    unsigned Start = DeclIDs.size();
3846
51.5k
    for (NamedDecl *D : Decls) {
3847
51.5k
      DeclIDs.push_back(
3848
51.5k
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3849
51.5k
    }
3850
46.7k
    return std::make_pair(Start, DeclIDs.size());
3851
46.7k
  }
ASTWriter.cpp:std::__1::pair<unsigned int, unsigned int> (anonymous namespace)::ASTDeclContextNameLookupTrait::getData<llvm::SmallVector<clang::NamedDecl*, 8u> >(llvm::SmallVector<clang::NamedDecl*, 8u> const&)
Line
Count
Source
3844
3.68k
  data_type getData(const Coll &Decls) {
3845
3.68k
    unsigned Start = DeclIDs.size();
3846
8.06k
    for (NamedDecl *D : Decls) {
3847
8.06k
      DeclIDs.push_back(
3848
8.06k
          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3849
8.06k
    }
3850
3.68k
    return std::make_pair(Start, DeclIDs.size());
3851
3.68k
  }
3852
3853
13
  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3854
13
    unsigned Start = DeclIDs.size();
3855
13
    for (auto ID : FromReader)
3856
53
      DeclIDs.push_back(ID);
3857
13
    return std::make_pair(Start, DeclIDs.size());
3858
13
  }
3859
3860
115
  static bool EqualKey(key_type_ref a, key_type_ref b) {
3861
115
    return a == b;
3862
115
  }
3863
3864
50.5k
  hash_value_type ComputeHash(DeclarationNameKey Name) {
3865
50.5k
    return Name.getHash();
3866
50.5k
  }
3867
3868
102
  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3869
102
    assert(Writer.hasChain() &&
3870
102
           "have reference to loaded module file but no chain?");
3871
102
3872
102
    using namespace llvm::support;
3873
102
3874
102
    endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3875
102
  }
3876
3877
  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3878
                                                  DeclarationNameKey Name,
3879
50.4k
                                                  data_type_ref Lookup) {
3880
50.4k
    using namespace llvm::support;
3881
50.4k
3882
50.4k
    endian::Writer LE(Out, little);
3883
50.4k
    unsigned KeyLen = 1;
3884
50.4k
    switch (Name.getKind()) {
3885
50.4k
    case DeclarationName::Identifier:
3886
42.7k
    case DeclarationName::ObjCZeroArgSelector:
3887
42.7k
    case DeclarationName::ObjCOneArgSelector:
3888
42.7k
    case DeclarationName::ObjCMultiArgSelector:
3889
42.7k
    case DeclarationName::CXXLiteralOperatorName:
3890
42.7k
    case DeclarationName::CXXDeductionGuideName:
3891
42.7k
      KeyLen += 4;
3892
42.7k
      break;
3893
42.7k
    case DeclarationName::CXXOperatorName:
3894
1.46k
      KeyLen += 1;
3895
1.46k
      break;
3896
42.7k
    case DeclarationName::CXXConstructorName:
3897
6.19k
    case DeclarationName::CXXDestructorName:
3898
6.19k
    case DeclarationName::CXXConversionFunctionName:
3899
6.19k
    case DeclarationName::CXXUsingDirective:
3900
6.19k
      break;
3901
50.4k
    }
3902
50.4k
    LE.write<uint16_t>(KeyLen);
3903
50.4k
3904
50.4k
    // 4 bytes for each DeclID.
3905
50.4k
    unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3906
50.4k
    assert(uint16_t(DataLen) == DataLen &&
3907
50.4k
           "too many decls for serialized lookup result");
3908
50.4k
    LE.write<uint16_t>(DataLen);
3909
50.4k
3910
50.4k
    return std::make_pair(KeyLen, DataLen);
3911
50.4k
  }
3912
3913
50.4k
  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3914
50.4k
    using namespace llvm::support;
3915
50.4k
3916
50.4k
    endian::Writer LE(Out, little);
3917
50.4k
    LE.write<uint8_t>(Name.getKind());
3918
50.4k
    switch (Name.getKind()) {
3919
50.4k
    case DeclarationName::Identifier:
3920
42.1k
    case DeclarationName::CXXLiteralOperatorName:
3921
42.1k
    case DeclarationName::CXXDeductionGuideName:
3922
42.1k
      LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3923
42.1k
      return;
3924
42.1k
    case DeclarationName::ObjCZeroArgSelector:
3925
582
    case DeclarationName::ObjCOneArgSelector:
3926
582
    case DeclarationName::ObjCMultiArgSelector:
3927
582
      LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3928
582
      return;
3929
1.46k
    case DeclarationName::CXXOperatorName:
3930
1.46k
      assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3931
1.46k
             "Invalid operator?");
3932
1.46k
      LE.write<uint8_t>(Name.getOperatorKind());
3933
1.46k
      return;
3934
6.19k
    case DeclarationName::CXXConstructorName:
3935
6.19k
    case DeclarationName::CXXDestructorName:
3936
6.19k
    case DeclarationName::CXXConversionFunctionName:
3937
6.19k
    case DeclarationName::CXXUsingDirective:
3938
6.19k
      return;
3939
0
    }
3940
0
3941
0
    llvm_unreachable("Invalid name kind?");
3942
0
  }
3943
3944
  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3945
50.4k
                unsigned DataLen) {
3946
50.4k
    using namespace llvm::support;
3947
50.4k
3948
50.4k
    endian::Writer LE(Out, little);
3949
50.4k
    uint64_t Start = Out.tell(); (void)Start;
3950
110k
    for (unsigned I = Lookup.first, N = Lookup.second; I != N; 
++I59.6k
)
3951
59.6k
      LE.write<uint32_t>(DeclIDs[I]);
3952
50.4k
    assert(Out.tell() - Start == DataLen && "Data length is wrong");
3953
50.4k
  }
3954
};
3955
3956
} // namespace
3957
3958
bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3959
51.0k
                                       DeclContext *DC) {
3960
51.0k
  return Result.hasExternalDecls() &&
3961
51.0k
         
DC->hasNeedToReconcileExternalVisibleStorage()987
;
3962
51.0k
}
3963
3964
bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3965
31
                                               DeclContext *DC) {
3966
31
  for (auto *D : Result.getLookupResult())
3967
31
    if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3968
21
      return false;
3969
31
3970
31
  
return true10
;
3971
31
}
3972
3973
void
3974
ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3975
11.0k
                                   llvm::SmallVectorImpl<char> &LookupTable) {
3976
11.0k
  assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3977
11.0k
         !ConstDC->hasLazyExternalLexicalLookups() &&
3978
11.0k
         "must call buildLookups first");
3979
11.0k
3980
11.0k
  // FIXME: We need to build the lookups table, which is logically const.
3981
11.0k
  auto *DC = const_cast<DeclContext*>(ConstDC);
3982
11.0k
  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3983
11.0k
3984
11.0k
  // Create the on-disk hash table representation.
3985
11.0k
  MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3986
11.0k
                                ASTDeclContextNameLookupTrait> Generator;
3987
11.0k
  ASTDeclContextNameLookupTrait Trait(*this);
3988
11.0k
3989
11.0k
  // The first step is to collect the declaration names which we need to
3990
11.0k
  // serialize into the name lookup table, and to collect them in a stable
3991
11.0k
  // order.
3992
11.0k
  SmallVector<DeclarationName, 16> Names;
3993
11.0k
3994
11.0k
  // We also build up small sets of the constructor and conversion function
3995
11.0k
  // names which are visible.
3996
11.0k
  llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3997
11.0k
3998
51.0k
  for (auto &Lookup : *DC->buildLookup()) {
3999
51.0k
    auto &Name = Lookup.first;
4000
51.0k
    auto &Result = Lookup.second;
4001
51.0k
4002
51.0k
    // If there are no local declarations in our lookup result, we
4003
51.0k
    // don't need to write an entry for the name at all. If we can't
4004
51.0k
    // write out a lookup set without performing more deserialization,
4005
51.0k
    // just skip this entry.
4006
51.0k
    if (isLookupResultExternal(Result, DC) &&
4007
51.0k
        
isLookupResultEntirelyExternal(Result, DC)31
)
4008
10
      continue;
4009
51.0k
4010
51.0k
    // We also skip empty results. If any of the results could be external and
4011
51.0k
    // the currently available results are empty, then all of the results are
4012
51.0k
    // external and we skip it above. So the only way we get here with an empty
4013
51.0k
    // results is when no results could have been external *and* we have
4014
51.0k
    // external results.
4015
51.0k
    //
4016
51.0k
    // FIXME: While we might want to start emitting on-disk entries for negative
4017
51.0k
    // lookups into a decl context as an optimization, today we *have* to skip
4018
51.0k
    // them because there are names with empty lookup results in decl contexts
4019
51.0k
    // which we can't emit in any stable ordering: we lookup constructors and
4020
51.0k
    // conversion functions in the enclosing namespace scope creating empty
4021
51.0k
    // results for them. This in almost certainly a bug in Clang's name lookup,
4022
51.0k
    // but that is likely to be hard or impossible to fix and so we tolerate it
4023
51.0k
    // here by omitting lookups with empty results.
4024
51.0k
    if (Lookup.second.getLookupResult().empty())
4025
666
      continue;
4026
50.4k
4027
50.4k
    switch (Lookup.first.getNameKind()) {
4028
50.4k
    default:
4029
46.7k
      Names.push_back(Lookup.first);
4030
46.7k
      break;
4031
50.4k
4032
50.4k
    case DeclarationName::CXXConstructorName:
4033
2.97k
      assert(isa<CXXRecordDecl>(DC) &&
4034
2.97k
             "Cannot have a constructor name outside of a class!");
4035
2.97k
      ConstructorNameSet.insert(Name);
4036
2.97k
      break;
4037
50.4k
4038
50.4k
    case DeclarationName::CXXConversionFunctionName:
4039
733
      assert(isa<CXXRecordDecl>(DC) &&
4040
733
             "Cannot have a conversion function name outside of a class!");
4041
733
      ConversionNameSet.insert(Name);
4042
733
      break;
4043
50.4k
    }
4044
50.4k
  }
4045
11.0k
4046
11.0k
  // Sort the names into a stable order.
4047
11.0k
  llvm::sort(Names);
4048
11.0k
4049
11.0k
  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4050
6.35k
    // We need to establish an ordering of constructor and conversion function
4051
6.35k
    // names, and they don't have an intrinsic ordering.
4052
6.35k
4053
6.35k
    // First we try the easy case by forming the current context's constructor
4054
6.35k
    // name and adding that name first. This is a very useful optimization to
4055
6.35k
    // avoid walking the lexical declarations in many cases, and it also
4056
6.35k
    // handles the only case where a constructor name can come from some other
4057
6.35k
    // lexical context -- when that name is an implicit constructor merged from
4058
6.35k
    // another declaration in the redecl chain. Any non-implicit constructor or
4059
6.35k
    // conversion function which doesn't occur in all the lexical contexts
4060
6.35k
    // would be an ODR violation.
4061
6.35k
    auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4062
6.35k
        Context->getCanonicalType(Context->getRecordType(D)));
4063
6.35k
    if (ConstructorNameSet.erase(ImplicitCtorName))
4064
2.97k
      Names.push_back(ImplicitCtorName);
4065
6.35k
4066
6.35k
    // If we still have constructors or conversion functions, we walk all the
4067
6.35k
    // names in the decl and add the constructors and conversion functions
4068
6.35k
    // which are visible in the order they lexically occur within the context.
4069
6.35k
    if (!ConstructorNameSet.empty() || 
!ConversionNameSet.empty()6.35k
)
4070
712
      for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4071
3.76k
        if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4072
3.76k
          auto Name = ChildND->getDeclName();
4073
3.76k
          switch (Name.getNameKind()) {
4074
3.76k
          default:
4075
1.48k
            continue;
4076
3.76k
4077
3.76k
          case DeclarationName::CXXConstructorName:
4078
1.54k
            if (ConstructorNameSet.erase(Name))
4079
2
              Names.push_back(Name);
4080
1.54k
            break;
4081
3.76k
4082
3.76k
          case DeclarationName::CXXConversionFunctionName:
4083
733
            if (ConversionNameSet.erase(Name))
4084
733
              Names.push_back(Name);
4085
733
            break;
4086
2.27k
          }
4087
2.27k
4088
2.27k
          if (ConstructorNameSet.empty() && 
ConversionNameSet.empty()2.26k
)
4089
712
            break;
4090
2.27k
        }
4091
6.35k
4092
6.35k
    assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4093
6.35k
                                         "constructors by walking all the "
4094
6.35k
                                         "lexical members of the context.");
4095
6.35k
    assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4096
6.35k
                                        "conversion functions by walking all "
4097
6.35k
                                        "the lexical members of the context.");
4098
6.35k
  }
4099
11.0k
4100
11.0k
  // Next we need to do a lookup with each name into this decl context to fully
4101
11.0k
  // populate any results from external sources. We don't actually use the
4102
11.0k
  // results of these lookups because we only want to use the results after all
4103
11.0k
  // results have been loaded and the pointers into them will be stable.
4104
11.0k
  for (auto &Name : Names)
4105
50.4k
    DC->lookup(Name);
4106
11.0k
4107
11.0k
  // Now we need to insert the results for each name into the hash table. For
4108
11.0k
  // constructor names and conversion function names, we actually need to merge
4109
11.0k
  // all of the results for them into one list of results each and insert
4110
11.0k
  // those.
4111
11.0k
  SmallVector<NamedDecl *, 8> ConstructorDecls;
4112
11.0k
  SmallVector<NamedDecl *, 8> ConversionDecls;
4113
11.0k
4114
11.0k
  // Now loop over the names, either inserting them or appending for the two
4115
11.0k
  // special cases.
4116
50.4k
  for (auto &Name : Names) {
4117
50.4k
    DeclContext::lookup_result Result = DC->noload_lookup(Name);
4118
50.4k
4119
50.4k
    switch (Name.getNameKind()) {
4120
50.4k
    default:
4121
46.7k
      Generator.insert(Name, Trait.getData(Result), Trait);
4122
46.7k
      break;
4123
50.4k
4124
50.4k
    case DeclarationName::CXXConstructorName:
4125
2.97k
      ConstructorDecls.append(Result.begin(), Result.end());
4126
2.97k
      break;
4127
50.4k
4128
50.4k
    case DeclarationName::CXXConversionFunctionName:
4129
733
      ConversionDecls.append(Result.begin(), Result.end());
4130
733
      break;
4131
50.4k
    }
4132
50.4k
  }
4133
11.0k
4134
11.0k
  // Handle our two special cases if we ended up having any. We arbitrarily use
4135
11.0k
  // the first declaration's name here because the name itself isn't part of
4136
11.0k
  // the key, only the kind of name is used.
4137
11.0k
  if (!ConstructorDecls.empty())
4138
2.97k
    Generator.insert(ConstructorDecls.front()->getDeclName(),
4139
2.97k
                     Trait.getData(ConstructorDecls), Trait);
4140
11.0k
  if (!ConversionDecls.empty())
4141
710
    Generator.insert(ConversionDecls.front()->getDeclName(),
4142
710
                     Trait.getData(ConversionDecls), Trait);
4143
11.0k
4144
11.0k
  // Create the on-disk hash table. Also emit the existing imported and
4145
11.0k
  // merged table if there is one.
4146
11.0k
  auto *Lookups = Chain ? 
Chain->getLoadedLookupTables(DC)4.57k
:
nullptr6.51k
;
4147
11.0k
  Generator.emit(LookupTable, Trait, Lookups ? 
&Lookups->Table431
:
nullptr10.6k
);
4148
11.0k
}
4149
4150
/// Write the block containing all of the declaration IDs
4151
/// visible from the given DeclContext.
4152
///
4153
/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4154
/// bitstream, or 0 if no block was written.
4155
uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4156
164k
                                                 DeclContext *DC) {
4157
164k
  // If we imported a key declaration of this namespace, write the visible
4158
164k
  // lookup results as an update record for it rather than including them
4159
164k
  // on this declaration. We will only look at key declarations on reload.
4160
164k
  if (isa<NamespaceDecl>(DC) && 
Chain762
&&
4161
164k
      
Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()596
) {
4162
86
    // Only do this once, for the first local declaration of the namespace.
4163
175
    for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4164
89
         Prev = Prev->getPreviousDecl())
4165
103
      if (!Prev->isFromASTFile())
4166
14
        return 0;
4167
86
4168
86
    // Note that we need to emit an update record for the primary context.
4169
86
    UpdatedDeclContexts.insert(DC->getPrimaryContext());
4170
72
4171
72
    // Make sure all visible decls are written. They will be recorded later. We
4172
72
    // do this using a side data structure so we can sort the names into
4173
72
    // a deterministic order.
4174
72
    StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4175
72
    SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4176
72
        LookupResults;
4177
72
    if (Map) {
4178
70
      LookupResults.reserve(Map->size());
4179
70
      for (auto &Entry : *Map)
4180
301
        LookupResults.push_back(
4181
301
            std::make_pair(Entry.first, Entry.second.getLookupResult()));
4182
70
    }
4183
72
4184
72
    llvm::sort(LookupResults, llvm::less_first());
4185
301
    for (auto &NameAndResult : LookupResults) {
4186
301
      DeclarationName Name = NameAndResult.first;
4187
301
      DeclContext::lookup_result Result = NameAndResult.second;
4188
301
      if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4189
301
          Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4190
0
        // We have to work around a name lookup bug here where negative lookup
4191
0
        // results for these names get cached in namespace lookup tables (these
4192
0
        // names should never be looked up in a namespace).
4193
0
        assert(Result.empty() && "Cannot have a constructor or conversion "
4194
0
                                 "function name in a namespace!");
4195
0
        continue;
4196
0
      }
4197
301
4198
301
      for (NamedDecl *ND : Result)
4199
273
        if (!ND->isFromASTFile())
4200
145
          GetDeclRef(ND);
4201
301
    }
4202
72
4203
72
    return 0;
4204
164k
  }
4205
164k
4206
164k
  if (DC->getPrimaryContext() != DC)
4207
1.80k
    return 0;
4208
163k
4209
163k
  // Skip contexts which don't support name lookup.
4210
163k
  if (!DC->isLookupContext())
4211
127k
    return 0;
4212
35.7k
4213
35.7k
  // If not in C++, we perform name lookup for the translation unit via the
4214
35.7k
  // IdentifierInfo chains, don't bother to build a visible-declarations table.
4215
35.7k
  if (DC->isTranslationUnit() && 
!Context.getLangOpts().CPlusPlus0
)
4216
0
    return 0;
4217
35.7k
4218
35.7k
  // Serialize the contents of the mapping used for lookup. Note that,
4219
35.7k
  // although we have two very different code paths, the serialized
4220
35.7k
  // representation is the same for both cases: a declaration name,
4221
35.7k
  // followed by a size, followed by references to the visible
4222
35.7k
  // declarations that have that name.
4223
35.7k
  uint64_t Offset = Stream.GetCurrentBitNo();
4224
35.7k
  StoredDeclsMap *Map = DC->buildLookup();
4225
35.7k
  if (!Map || 
Map->empty()8.54k
)
4226
27.1k
    return 0;
4227
8.54k
4228
8.54k
  // Create the on-disk hash table in a buffer.
4229
8.54k
  SmallString<4096> LookupTable;
4230
8.54k
  GenerateNameLookupTable(DC, LookupTable);
4231
8.54k
4232
8.54k
  // Write the lookup table
4233
8.54k
  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4234
8.54k
  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4235
8.54k
                            LookupTable);
4236
8.54k
  ++NumVisibleDeclContexts;
4237
8.54k
  return Offset;
4238
8.54k
}
4239
4240
/// Write an UPDATE_VISIBLE block for the given context.
4241
///
4242
/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4243
/// DeclContext in a dependent AST file. As such, they only exist for the TU
4244
/// (in C++), for namespaces, and for classes with forward-declared unscoped
4245
/// enumeration members (in C++11).
4246
6.25k
void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4247
6.25k
  StoredDeclsMap *Map = DC->getLookupPtr();
4248
6.25k
  if (!Map || 
Map->empty()2.54k
)
4249
3.70k
    return;
4250
2.54k
4251
2.54k
  // Create the on-disk hash table in a buffer.
4252
2.54k
  SmallString<4096> LookupTable;
4253
2.54k
  GenerateNameLookupTable(DC, LookupTable);
4254
2.54k
4255
2.54k
  // If we're updating a namespace, select a key declaration as the key for the
4256
2.54k
  // update record; those are the only ones that will be checked on reload.
4257
2.54k
  if (isa<NamespaceDecl>(DC))
4258
80
    DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4259
2.54k
4260
2.54k
  // Write the lookup table
4261
2.54k
  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4262
2.54k
  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4263
2.54k
}
4264
4265
/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4266
3.61k
void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4267
3.61k
  RecordData::value_type Record[] = {Opts.getInt()};
4268
3.61k
  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4269
3.61k
}
4270
4271
/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4272
3.61k
void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4273
3.61k
  if (!SemaRef.Context.getLangOpts().OpenCL)
4274
3.60k
    return;
4275
11
4276
11
  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4277
11
  RecordData Record;
4278
455
  for (const auto &I:Opts.OptMap) {
4279
455
    AddString(I.getKey(), Record);
4280
455
    auto V = I.getValue();
4281
455
    Record.push_back(V.Supported ? 
1405
:
050
);
4282
455
    Record.push_back(V.Enabled ? 
155
:
0400
);
4283
455
    Record.push_back(V.Avail);
4284
455
    Record.push_back(V.Core);
4285
455
  }
4286
11
  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4287
11
}
4288
4289
3.61k
void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4290
3.61k
  if (!SemaRef.Context.getLangOpts().OpenCL)
4291
3.60k
    return;
4292
11
4293
11
  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
4294
11
  // without copying them.
4295
11
  const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
4296
11
      SemaRef.OpenCLTypeExtMap;
4297
11
  using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
4298
11
  llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
4299
11
  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
4300
11
4301
11
  for (const auto &I : OpenCLTypeExtMap)
4302
304
    StableOpenCLTypeExtMap.emplace_back(
4303
304
        getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
4304
11
4305
1.35k
  auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4306
1.35k
    return E1.first < E2.first;
4307
1.35k
  };
4308
11
  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
4309
11
4310
11
  RecordData Record;
4311
304
  for (const ElementTy &E : StableOpenCLTypeExtMap) {
4312
304
    Record.push_back(E.first); // TypeID
4313
304
    const std::set<std::string> *ExtSet = E.second;
4314
304
    Record.push_back(static_cast<unsigned>(ExtSet->size()));
4315
304
    for (const std::string &Ext : *ExtSet)
4316
328
      AddString(Ext, Record);
4317
304
  }
4318
11
4319
11
  Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4320
11
}
4321
4322
3.61k
void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4323
3.61k
  if (!SemaRef.Context.getLangOpts().OpenCL)
4324
3.60k
    return;
4325
11
4326
11
  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
4327
11
  // without copying them.
4328
11
  const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
4329
11
      SemaRef.OpenCLDeclExtMap;
4330
11
  using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
4331
11
  llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
4332
11
  StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
4333
11
4334
11
  for (const auto &I : OpenCLDeclExtMap)
4335
317
    StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4336
11
4337
2.33k
  auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4338
2.33k
    return E1.first < E2.first;
4339
2.33k
  };
4340
11
  llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4341
11
4342
11
  RecordData Record;
4343
317
  for (const ElementTy &E : StableOpenCLDeclExtMap) {
4344
317
    Record.push_back(E.first); // DeclID
4345
317
    const std::set<std::string> *ExtSet = E.second;
4346
317
    Record.push_back(static_cast<unsigned>(ExtSet->size()));
4347
317
    for (const std::string &Ext : *ExtSet)
4348
317
      AddString(Ext, Record);
4349
317
  }
4350
11
4351
11
  Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4352
11
}
4353
4354
3.61k
void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4355
3.61k
  if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4356
1
    RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4357
1
    Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4358
1
  }
4359
3.61k
}
4360
4361
3.61k
void ASTWriter::WriteObjCCategories() {
4362
3.61k
  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4363
3.61k
  RecordData Categories;
4364
3.61k
4365
3.66k
  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; 
++I48
) {
4366
48
    unsigned Size = 0;
4367
48
    unsigned StartIndex = Categories.size();
4368
48
4369
48
    ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4370
48
4371
48
    // Allocate space for the size.
4372
48
    Categories.push_back(0);
4373
48
4374
48
    // Add the categories.
4375
48
    for (ObjCInterfaceDecl::known_categories_iterator
4376
48
           Cat = Class->known_categories_begin(),
4377
48
           CatEnd = Class->known_categories_end();
4378
192
         Cat != CatEnd; 
++Cat, ++Size144
) {
4379
144
      assert(getDeclID(*Cat) != 0 && "Bogus category");
4380
144
      AddDeclRef(*Cat, Categories);
4381
144
    }
4382
48
4383
48
    // Update the size.
4384
48
    Categories[StartIndex] = Size;
4385
48
4386
48
    // Record this interface -> category map.
4387
48
    ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4388
48
    CategoriesMap.push_back(CatInfo);
4389
48
  }
4390
3.61k
4391
3.61k
  // Sort the categories map by the definition ID, since the reader will be
4392
3.61k
  // performing binary searches on this information.
4393
3.61k
  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4394
3.61k
4395
3.61k
  // Emit the categories map.
4396
3.61k
  using namespace llvm;
4397
3.61k
4398
3.61k
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
4399
3.61k
  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4400
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4401
3.61k
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4402
3.61k
  unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4403
3.61k
4404
3.61k
  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4405
3.61k
  Stream.EmitRecordWithBlob(AbbrevID, Record,
4406
3.61k
                            reinterpret_cast<char *>(CategoriesMap.data()),
4407
3.61k
                            CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4408
3.61k
4409
3.61k
  // Emit the category lists.
4410
3.61k
  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4411
3.61k
}
4412
4413
3.61k
void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4414
3.61k
  Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4415
3.61k
4416
3.61k
  if (LPTMap.empty())
4417
3.61k
    return;
4418
4
4419
4
  RecordData Record;
4420
35
  for (auto &LPTMapEntry : LPTMap) {
4421
35
    const FunctionDecl *FD = LPTMapEntry.first;
4422
35
    LateParsedTemplate &LPT = *LPTMapEntry.second;
4423
35
    AddDeclRef(FD, Record);
4424
35
    AddDeclRef(LPT.D, Record);
4425
35
    Record.push_back(LPT.Toks.size());
4426
35
4427
352
    for (const auto &Tok : LPT.Toks) {
4428
352
      AddToken(Tok, Record);
4429
352
    }
4430
35
  }
4431
4
  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4432
4
}
4433
4434
/// Write the state of 'pragma clang optimize' at the end of the module.
4435
2.13k
void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4436
2.13k
  RecordData Record;
4437
2.13k
  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4438
2.13k
  AddSourceLocation(PragmaLoc, Record);
4439
2.13k
  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4440
2.13k
}
4441
4442
/// Write the state of 'pragma ms_struct' at the end of the module.
4443
2.13k
void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4444
2.13k
  RecordData Record;
4445
2.13k
  Record.push_back(SemaRef.MSStructPragmaOn ? 
PMSST_ON1
:
PMSST_OFF2.13k
);
4446
2.13k
  Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4447
2.13k
}
4448
4449
/// Write the state of 'pragma pointers_to_members' at the end of the
4450
//module.
4451
2.13k
void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4452
2.13k
  RecordData Record;
4453
2.13k
  Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4454
2.13k
  AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4455
2.13k
  Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4456
2.13k
}
4457
4458
/// Write the state of 'pragma pack' at the end of the module.
4459
3.61k
void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4460
3.61k
  // Don't serialize pragma pack state for modules, since it should only take
4461
3.61k
  // effect on a per-submodule basis.
4462
3.61k
  if (WritingModule)
4463
1.48k
    return;
4464
2.13k
4465
2.13k
  RecordData Record;
4466
2.13k
  Record.push_back(SemaRef.PackStack.CurrentValue);
4467
2.13k
  AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4468
2.13k
  Record.push_back(SemaRef.PackStack.Stack.size());
4469
2.13k
  for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4470
4
    Record.push_back(StackEntry.Value);
4471
4
    AddSourceLocation(StackEntry.PragmaLocation, Record);
4472
4
    AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4473
4
    AddString(StackEntry.StackSlotLabel, Record);
4474
4
  }
4475
2.13k
  Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4476
2.13k
}
4477
4478
void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4479
12
                                         ModuleFileExtensionWriter &Writer) {
4480
12
  // Enter the extension block.
4481
12
  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4482
12
4483
12
  // Emit the metadata record abbreviation.
4484
12
  auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4485
12
  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4486
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4487
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4488
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4489
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4490
12
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4491
12
  unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4492
12
4493
12
  // Emit the metadata record.
4494
12
  RecordData Record;
4495
12
  auto Metadata = Writer.getExtension()->getExtensionMetadata();
4496
12
  Record.push_back(EXTENSION_METADATA);
4497
12
  Record.push_back(Metadata.MajorVersion);
4498
12
  Record.push_back(Metadata.MinorVersion);
4499
12
  Record.push_back(Metadata.BlockName.size());
4500
12
  Record.push_back(Metadata.UserInfo.size());
4501
12
  SmallString<64> Buffer;
4502
12
  Buffer += Metadata.BlockName;
4503
12
  Buffer += Metadata.UserInfo;
4504
12
  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4505
12
4506
12
  // Emit the contents of the extension block.
4507
12
  Writer.writeExtensionContents(SemaRef, Stream);
4508
12
4509
12
  // Exit the extension block.
4510
12
  Stream.ExitBlock();
4511
12
}
4512
4513
//===----------------------------------------------------------------------===//
4514
// General Serialization Routines
4515
//===----------------------------------------------------------------------===//
4516
4517
261k
void ASTRecordWriter::AddAttr(const Attr *A) {
4518
261k
  auto &Record = *this;
4519
261k
  if (!A)
4520
10
    return Record.push_back(0);
4521
261k
  Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4522
261k
  Record.AddSourceRange(A->getRange());
4523
261k
4524
261k
#include "clang/Serialization/AttrPCHWrite.inc"
4525
261k
}
4526
4527
/// Emit the list of attributes to the specified record.
4528
139k
void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4529
139k
  push_back(Attrs.size());
4530
139k
  for (const auto *A : Attrs)
4531
261k
    AddAttr(A);
4532
139k
}
4533
4534
1.26M
void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4535
1.26M
  AddSourceLocation(Tok.getLocation(), Record);
4536
1.26M
  Record.push_back(Tok.getLength());
4537
1.26M
4538
1.26M
  // FIXME: When reading literal tokens, reconstruct the literal pointer
4539
1.26M
  // if it is needed.
4540
1.26M
  AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4541
1.26M
  // FIXME: Should translate token kind to a stable encoding.
4542
1.26M
  Record.push_back(Tok.getKind());
4543
1.26M
  // FIXME: Should translate token flags to a stable encoding.
4544
1.26M
  Record.push_back(Tok.getFlags());
4545
1.26M
}
4546
4547
108k
void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4548
108k
  Record.push_back(Str.size());
4549
108k
  Record.insert(Record.end(), Str.begin(), Str.end());
4550
108k
}
4551
4552
24.3k
bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4553
24.3k
  assert(Context && "should have context when outputting path");
4554
24.3k
4555
24.3k
  bool Changed =
4556
24.3k
      cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4557
24.3k
4558
24.3k
  // Remove a prefix to make the path relative, if relevant.
4559
24.3k
  const char *PathBegin = Path.data();
4560
24.3k
  const char *PathPtr =
4561
24.3k
      adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4562
24.3k
  if (PathPtr != PathBegin) {
4563
9.42k
    Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4564
9.42k
    Changed = true;
4565
9.42k
  }
4566
24.3k
4567
24.3k
  return Changed;
4568
24.3k
}
4569
4570
9.43k
void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4571
9.43k
  SmallString<128> FilePath(Path);
4572
9.43k
  PreparePathForOutput(FilePath);
4573
9.43k
  AddString(FilePath, Record);
4574
9.43k
}
4575
4576
void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4577
9.26k
                                   StringRef Path) {
4578
9.26k
  SmallString<128> FilePath(Path);
4579
9.26k
  PreparePathForOutput(FilePath);
4580
9.26k
  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4581
9.26k
}
4582
4583
void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4584
3.63k
                                RecordDataImpl &Record) {
4585
3.63k
  Record.push_back(Version.getMajor());
4586
3.63k
  if (Optional<unsigned> Minor = Version.getMinor())
4587
119
    Record.push_back(*Minor + 1);
4588
3.51k
  else
4589
3.51k
    Record.push_back(0);
4590
3.63k
  if (Optional<unsigned> Subminor = Version.getSubminor())
4591
115
    Record.push_back(*Subminor + 1);
4592
3.51k
  else
4593
3.51k
    Record.push_back(0);
4594
3.63k
}
4595
4596
/// Note that the identifier II occurs at the given offset
4597
/// within the identifier table.
4598
5.65M
void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4599
5.65M
  IdentID ID = IdentifierIDs[II];
4600
5.65M
  // Only store offsets new to this AST file. Other identifier names are looked
4601
5.65M
  // up earlier in the chain and thus don't need an offset.
4602
5.65M
  if (ID >= FirstIdentID)
4603
5.64M
    IdentifierOffsets[ID - FirstIdentID] = Offset;
4604
5.65M
}
4605
4606
/// Note that the selector Sel occurs at the given offset
4607
/// within the method pool/selector table.
4608
550
void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4609
550
  unsigned ID = SelectorIDs[Sel];
4610
550
  assert(ID && "Unknown selector");
4611
550
  // Don't record offsets for selectors that are also available in a different
4612
550
  // file.
4613
550
  if (ID < FirstSelectorID)
4614
9
    return;
4615
541
  SelectorOffsets[ID - FirstSelectorID] = Offset;
4616
541
}
4617
4618
ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4619
                     SmallVectorImpl<char> &Buffer,
4620
                     InMemoryModuleCache &ModuleCache,
4621
                     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4622
                     bool IncludeTimestamps)
4623
    : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4624
3.65k
      IncludeTimestamps(IncludeTimestamps) {
4625
3.65k
  for (const auto &Ext : Extensions) {
4626
12
    if (auto Writer = Ext->createExtensionWriter(*this))
4627
12
      ModuleFileExtensionWriters.push_back(std::move(Writer));
4628
12
  }
4629
3.65k
}
4630
4631
3.65k
ASTWriter::~ASTWriter() {
4632
3.65k
  llvm::DeleteContainerSeconds(FileDeclIDs);
4633
3.65k
}
4634
4635
66.6k
const LangOptions &ASTWriter::getLangOpts() const {
4636
66.6k
  assert(WritingAST && "can't determine lang opts when not writing AST");
4637
66.6k
  return Context->getLangOpts();
4638
66.6k
}
4639
4640
12.8k
time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4641
12.8k
  return IncludeTimestamps ? 
E->getModificationTime()11.8k
:
01.00k
;
4642
12.8k
}
4643
4644
ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4645
                                     const std::string &OutputFile,
4646
                                     Module *WritingModule, StringRef isysroot,
4647
                                     bool hasErrors,
4648
3.61k
                                     bool ShouldCacheASTInMemory) {
4649
3.61k
  WritingAST = true;
4650
3.61k
4651
3.61k
  ASTHasCompilerErrors = hasErrors;
4652
3.61k
4653
3.61k
  // Emit the file header.
4654
3.61k
  Stream.Emit((unsigned)'C', 8);
4655
3.61k
  Stream.Emit((unsigned)'P', 8);
4656
3.61k
  Stream.Emit((unsigned)'C', 8);
4657
3.61k
  Stream.Emit((unsigned)'H', 8);
4658
3.61k
4659
3.61k
  WriteBlockInfoBlock();
4660
3.61k
4661
3.61k
  Context = &SemaRef.Context;
4662
3.61k
  PP = &SemaRef.PP;
4663
3.61k
  this->WritingModule = WritingModule;
4664
3.61k
  ASTFileSignature Signature =
4665
3.61k
      WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4666
3.61k
  Context = nullptr;
4667
3.61k
  PP = nullptr;
4668
3.61k
  this->WritingModule = nullptr;
4669
3.61k
  this->BaseDirectory.clear();
4670
3.61k
4671
3.61k
  WritingAST = false;
4672
3.61k
  if (ShouldCacheASTInMemory) {
4673
1.25k
    // Construct MemoryBuffer and update buffer manager.
4674
1.25k
    ModuleCache.addBuiltPCM(OutputFile,
4675
1.25k
                            llvm::MemoryBuffer::getMemBufferCopy(
4676
1.25k
                                StringRef(Buffer.begin(), Buffer.size())));
4677
1.25k
  }
4678
3.61k
  return Signature;
4679
3.61k
}
4680
4681
template<typename Vector>
4682
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4683
11.5k
                               ASTWriter::RecordData &Record) {
4684
11.5k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4685
12.6k
       I != E; 
++I1.11k
) {
4686
1.11k
    Writer.AddDeclRef(*I, Record);
4687
1.11k
  }
4688
11.5k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadTentativeDefinitions(llvm::SmallVectorImpl<clang::VarDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::VarDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadTentativeDefinitions(llvm::SmallVectorImpl<clang::VarDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4683
3.61k
                               ASTWriter::RecordData &Record) {
4684
3.61k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4685
4.47k
       I != E; 
++I858
) {
4686
858
    Writer.AddDeclRef(*I, Record);
4687
858
  }
4688
3.61k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadUnusedFileScopedDecls(llvm::SmallVectorImpl<clang::DeclaratorDecl const*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::DeclaratorDecl const*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadUnusedFileScopedDecls(llvm::SmallVectorImpl<clang::DeclaratorDecl const*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4683
2.13k
                               ASTWriter::RecordData &Record) {
4684
2.13k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4685
2.14k
       I != E; 
++I13
) {
4686
13
    Writer.AddDeclRef(*I, Record);
4687
13
  }
4688
2.13k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadDelegatingConstructors(llvm::SmallVectorImpl<clang::CXXConstructorDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::CXXConstructorDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadDelegatingConstructors(llvm::SmallVectorImpl<clang::CXXConstructorDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4683
2.13k
                               ASTWriter::RecordData &Record) {
4684
2.13k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4685
2.13k
       I != E; 
++I3
) {
4686
3
    Writer.AddDeclRef(*I, Record);
4687
3
  }
4688
2.13k
}
ASTWriter.cpp:void AddLazyVectorDecls<clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadExtVectorDecls(llvm::SmallVectorImpl<clang::TypedefNameDecl*>&)), 2u, 2u> >(clang::ASTWriter&, clang::LazyVector<clang::TypedefNameDecl*, clang::ExternalSemaSource, &(clang::ExternalSemaSource::ReadExtVectorDecls(llvm::SmallVectorImpl<clang::TypedefNameDecl*>&)), 2u, 2u>&, llvm::SmallVector<unsigned long long, 64u>&)
Line
Count
Source
4683
3.61k
                               ASTWriter::RecordData &Record) {
4684
3.61k
  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4685
3.86k
       I != E; 
++I242
) {
4686
242
    Writer.AddDeclRef(*I, Record);
4687
242
  }
4688
3.61k
}
4689
4690
ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4691
                                         const std::string &OutputFile,
4692
3.61k
                                         Module *WritingModule) {
4693
3.61k
  using namespace llvm;
4694
3.61k
4695
3.61k
  bool isModule = WritingModule != nullptr;
4696
3.61k
4697
3.61k
  // Make sure that the AST reader knows to finalize itself.
4698
3.61k
  if (Chain)
4699
1.61k
    Chain->finalizeForWriting();
4700
3.61k
4701
3.61k
  ASTContext &Context = SemaRef.Context;
4702
3.61k
  Preprocessor &PP = SemaRef.PP;
4703
3.61k
4704
3.61k
  // Set up predefined declaration IDs.
4705
57.8k
  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4706
57.8k
    if (D) {
4707
31.2k
      assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4708
31.2k
      DeclIDs[D] = ID;
4709
31.2k
    }
4710
57.8k
  };
4711
3.61k
  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4712
3.61k
                     PREDEF_DECL_TRANSLATION_UNIT_ID);
4713
3.61k
  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4714
3.61k
  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4715
3.61k
  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4716
3.61k
  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4717
3.61k
                     PREDEF_DECL_OBJC_PROTOCOL_ID);
4718
3.61k
  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4719
3.61k
  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4720
3.61k
  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4721
3.61k
                     PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4722
3.61k
  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4723
3.61k
  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4724
3.61k
  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4725
3.61k
                     PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4726
3.61k
  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4727
3.61k
  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4728
3.61k
                     PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4729
3.61k
  RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4730
3.61k
                     PREDEF_DECL_CF_CONSTANT_STRING_ID);
4731
3.61k
  RegisterPredefDecl(Context.CFConstantStringTagDecl,
4732
3.61k
                     PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4733
3.61k
  RegisterPredefDecl(Context.TypePackElementDecl,
4734
3.61k
                     PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4735
3.61k
4736
3.61k
  // Build a record containing all of the tentative definitions in this file, in
4737
3.61k
  // TentativeDefinitions order.  Generally, this record will be empty for
4738
3.61k
  // headers.
4739
3.61k
  RecordData TentativeDefinitions;
4740
3.61k
  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4741
3.61k
4742
3.61k
  // Build a record containing all of the file scoped decls in this file.
4743
3.61k
  RecordData UnusedFileScopedDecls;
4744
3.61k
  if (!isModule)
4745
2.13k
    AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4746
2.13k
                       UnusedFileScopedDecls);
4747
3.61k
4748
3.61k
  // Build a record containing all of the delegating constructors we still need
4749
3.61k
  // to resolve.
4750
3.61k
  RecordData DelegatingCtorDecls;
4751
3.61k
  if (!isModule)
4752
2.13k
    AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4753
3.61k
4754
3.61k
  // Write the set of weak, undeclared identifiers. We always write the
4755
3.61k
  // entire table, since later PCH files in a PCH chain are only interested in
4756
3.61k
  // the results at the end of the chain.
4757
3.61k
  RecordData WeakUndeclaredIdentifiers;
4758
3.61k
  for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4759
63
    IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4760
63
    WeakInfo &WI = WeakUndeclaredIdentifier.second;
4761
63
    AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4762
63
    AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4763
63
    AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4764
63
    WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4765
63
  }
4766
3.61k
4767
3.61k
  // Build a record containing all of the ext_vector declarations.
4768
3.61k
  RecordData ExtVectorDecls;
4769
3.61k
  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4770
3.61k
4771
3.61k
  // Build a record containing all of the VTable uses information.
4772
3.61k
  RecordData VTableUses;
4773
3.61k
  if (!SemaRef.VTableUses.empty()) {
4774
27
    for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; 
++I19
) {
4775
19
      AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4776
19
      AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4777
19
      VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4778
19
    }
4779
8
  }
4780
3.61k
4781
3.61k
  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4782
3.61k
  RecordData UnusedLocalTypedefNameCandidates;
4783
3.61k
  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4784
3
    AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4785
3.61k
4786
3.61k
  // Build a record containing all of pending implicit instantiations.
4787
3.61k
  RecordData PendingInstantiations;
4788
3.61k
  for (const auto &I : SemaRef.PendingInstantiations) {
4789
2.54k
    AddDeclRef(I.first, PendingInstantiations);
4790
2.54k
    AddSourceLocation(I.second, PendingInstantiations);
4791
2.54k
  }
4792
3.61k
  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4793
3.61k
         "There are local ones at end of translation unit!");
4794
3.61k
4795
3.61k
  // Build a record containing some declaration references.
4796
3.61k
  RecordData SemaDeclRefs;
4797
3.61k
  if (SemaRef.StdNamespace || 
SemaRef.StdBadAlloc3.58k
||
SemaRef.StdAlignValT3.58k
) {
4798
32
    AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4799
32
    AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4800
32
    AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4801
32
  }
4802
3.61k
4803
3.61k
  RecordData CUDASpecialDeclRefs;
4804
3.61k
  if (Context.getcudaConfigureCallDecl()) {
4805
1
    AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4806
1
  }
4807
3.61k
4808
3.61k
  // Build a record containing all of the known namespaces.
4809
3.61k
  RecordData KnownNamespaces;
4810
3.61k
  for (const auto &I : SemaRef.KnownNamespaces) {
4811
600
    if (!I.second)
4812
600
      AddDeclRef(I.first, KnownNamespaces);
4813
600
  }
4814
3.61k
4815
3.61k
  // Build a record of all used, undefined objects that require definitions.
4816
3.61k
  RecordData UndefinedButUsed;
4817
3.61k
4818
3.61k
  SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4819
3.61k
  SemaRef.getUndefinedButUsed(Undefined);
4820
3.61k
  for (const auto &I : Undefined) {
4821
1.64k
    AddDeclRef(I.first, UndefinedButUsed);
4822
1.64k
    AddSourceLocation(I.second, UndefinedButUsed);
4823
1.64k
  }
4824
3.61k
4825
3.61k
  // Build a record containing all delete-expressions that we would like to
4826
3.61k
  // analyze later in AST.
4827
3.61k
  RecordData DeleteExprsToAnalyze;
4828
3.61k
4829
3.61k
  if (!isModule) {
4830
2.13k
    for (const auto &DeleteExprsInfo :
4831
2.13k
         SemaRef.getMismatchingDeleteExpressions()) {
4832
1
      AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4833
1
      DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4834
1
      for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4835
1
        AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4836
1
        DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4837
1
      }
4838
1
    }
4839
2.13k
  }
4840
3.61k
4841
3.61k
  // Write the control block
4842
3.61k
  WriteControlBlock(PP, Context, isysroot, OutputFile);
4843
3.61k
4844
3.61k
  // Write the remaining AST contents.
4845
3.61k
  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4846
3.61k
4847
3.61k
  // This is so that older clang versions, before the introduction
4848
3.61k
  // of the control block, can read and reject the newer PCH format.
4849
3.61k
  {
4850
3.61k
    RecordData Record = {VERSION_MAJOR};
4851
3.61k
    Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4852
3.61k
  }
4853
3.61k
4854
3.61k
  // Create a lexical update block containing all of the declarations in the
4855
3.61k
  // translation unit that do not come from other AST files.
4856
3.61k
  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4857
3.61k
  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4858
129k
  for (const auto *D : TU->noload_decls()) {
4859
129k
    if (!D->isFromASTFile()) {
4860
129k
      NewGlobalKindDeclPairs.push_back(D->getKind());
4861
129k
      NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4862
129k
    }
4863
129k
  }
4864
3.61k
4865
3.61k
  auto Abv = std::make_shared<BitCodeAbbrev>();
4866
3.61k
  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4867
3.61k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4868
3.61k
  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4869
3.61k
  {
4870
3.61k
    RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4871
3.61k
    Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4872
3.61k
                              bytes(NewGlobalKindDeclPairs));
4873
3.61k
  }
4874
3.61k
4875
3.61k
  // And a visible updates block for the translation unit.
4876
3.61k
  Abv = std::make_shared<BitCodeAbbrev>();
4877
3.61k
  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4878
3.61k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4879
3.61k
  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4880
3.61k
  UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4881
3.61k
  WriteDeclContextVisibleUpdate(TU);
4882
3.61k
4883
3.61k
  // If we have any extern "C" names, write out a visible update for them.
4884
3.61k
  if (Context.ExternCContext)
4885
2.48k
    WriteDeclContextVisibleUpdate(Context.ExternCContext);
4886
3.61k
4887
3.61k
  // If the translation unit has an anonymous namespace, and we don't already
4888
3.61k
  // have an update block for it, write it as an update block.
4889
3.61k
  // FIXME: Why do we not do this if there's already an update block?
4890
3.61k
  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4891
7
    ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4892
7
    if (Record.empty())
4893
7
      Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4894
7
  }
4895
3.61k
4896
3.61k
  // Add update records for all mangling numbers and static local numbers.
4897
3.61k
  // These aren't really update records, but this is a convenient way of
4898
3.61k
  // tagging this rare extra data onto the declarations.
4899
3.61k
  for (const auto &Number : Context.MangleNumbers)
4900
58
    if (!Number.first->isFromASTFile())
4901
40
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4902
40
                                                     Number.second));
4903
3.61k
  for (const auto &Number : Context.StaticLocalNumbers)
4904
0
    if (!Number.first->isFromASTFile())
4905
0
      DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4906
0
                                                     Number.second));
4907
3.61k
4908
3.61k
  // Make sure visible decls, added to DeclContexts previously loaded from
4909
3.61k
  // an AST file, are registered for serialization. Likewise for template
4910
3.61k
  // specializations added to imported templates.
4911
3.61k
  for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4912
338
    GetDeclRef(I);
4913
338
  }
4914
3.61k
4915
3.61k
  // Make sure all decls associated with an identifier are registered for
4916
3.61k
  // serialization, if we're storing decls with identifiers.
4917
3.61k
  if (!WritingModule || 
!getLangOpts().CPlusPlus1.48k
) {
4918
2.72k
    llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4919
8.10M
    for (const auto &ID : PP.getIdentifierTable()) {
4920
8.10M
      const IdentifierInfo *II = ID.second;
4921
8.10M
      if (!Chain || 
!II->isFromAST()2.24M
||
II->hasChangedSinceDeserialization()6.71k
)
4922
8.09M
        IIs.push_back(II);
4923
8.10M
    }
4924
2.72k
    // Sort the identifiers to visit based on their name.
4925
2.72k
    llvm::sort(IIs, llvm::less_ptr<IdentifierInfo>());
4926
8.09M
    for (const IdentifierInfo *II : IIs) {
4927
8.09M
      for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4928
8.09M
                                     DEnd = SemaRef.IdResolver.end();
4929
8.21M
           D != DEnd; 
++D116k
) {
4930
116k
        GetDeclRef(*D);
4931
116k
      }
4932
8.09M
    }
4933
2.72k
  }
4934
3.61k
4935
3.61k
  // For method pool in the module, if it contains an entry for a selector,
4936
3.61k
  // the entry should be complete, containing everything introduced by that
4937
3.61k
  // module and all modules it imports. It's possible that the entry is out of
4938
3.61k
  // date, so we need to pull in the new content here.
4939
3.61k
4940
3.61k
  // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4941
3.61k
  // safe, we copy all selectors out.
4942
3.61k
  llvm::SmallVector<Selector, 256> AllSelectors;
4943
3.61k
  for (auto &SelectorAndID : SelectorIDs)
4944
14
    AllSelectors.push_back(SelectorAndID.first);
4945
3.61k
  for (auto &Selector : AllSelectors)
4946
14
    SemaRef.updateOutOfDateSelector(Selector);
4947
3.61k
4948
3.61k
  // Form the record of special types.
4949
3.61k
  RecordData SpecialTypes;
4950
3.61k
  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4951
3.61k
  AddTypeRef(Context.getFILEType(), SpecialTypes);
4952
3.61k
  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4953
3.61k
  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4954
3.61k
  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4955
3.61k
  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4956
3.61k
  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4957
3.61k
  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4958
3.61k
4959
3.61k
  if (Chain) {
4960
1.61k
    // Write the mapping information describing our module dependencies and how
4961
1.61k
    // each of those modules were mapped into our own offset/ID space, so that
4962
1.61k
    // the reader can build the appropriate mapping to its own offset/ID space.
4963
1.61k
    // The map consists solely of a blob with the following format:
4964
1.61k
    // *(module-kind:i8
4965
1.61k
    //   module-name-len:i16 module-name:len*i8
4966
1.61k
    //   source-location-offset:i32
4967
1.61k
    //   identifier-id:i32
4968
1.61k
    //   preprocessed-entity-id:i32
4969
1.61k
    //   macro-definition-id:i32
4970
1.61k
    //   submodule-id:i32
4971
1.61k
    //   selector-id:i32
4972
1.61k
    //   declaration-id:i32
4973
1.61k
    //   c++-base-specifiers-id:i32
4974
1.61k
    //   type-id:i32)
4975
1.61k
    //
4976
1.61k
    // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4977
1.61k
    // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4978
1.61k
    // it is the module file name.
4979
1.61k
    auto Abbrev = std::make_shared<BitCodeAbbrev>();
4980
1.61k
    Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4981
1.61k
    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4982
1.61k
    unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4983
1.61k
    SmallString<2048> Buffer;
4984
1.61k
    {
4985
1.61k
      llvm::raw_svector_ostream Out(Buffer);
4986
1.69k
      for (ModuleFile &M : Chain->ModuleMgr) {
4987
1.69k
        using namespace llvm::support;
4988
1.69k
4989
1.69k
        endian::Writer LE(Out, little);
4990
1.69k
        LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4991
1.69k
        StringRef Name =
4992
1.69k
          M.Kind == MK_PrebuiltModule || 
M.Kind == MK_ExplicitModule1.68k
4993
1.69k
          ? 
M.ModuleName919
4994
1.69k
          : 
M.FileName778
;
4995
1.69k
        LE.write<uint16_t>(Name.size());
4996
1.69k
        Out.write(Name.data(), Name.size());
4997
1.69k
4998
1.69k
        // Note: if a base ID was uint max, it would not be possible to load
4999
1.69k
        // another module after it or have more than one entity inside it.
5000
1.69k
        uint32_t None = std::numeric_limits<uint32_t>::max();
5001
1.69k
5002
13.5k
        auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
5003
13.5k
          assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
5004
13.5k
          if (ShouldWrite)
5005
8.23k
            LE.write<uint32_t>(BaseID);
5006
5.34k
          else
5007
5.34k
            LE.write<uint32_t>(None);
5008
13.5k
        };
5009
1.69k
5010
1.69k
        // These values should be unique within a chain, since they will be read
5011
1.69k
        // as keys into ContinuousRangeMaps.
5012
1.69k
        writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
5013
1.69k
        writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
5014
1.69k
        writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
5015
1.69k
        writeBaseIDOrNone(M.BasePreprocessedEntityID,
5016
1.69k
                          M.NumPreprocessedEntities);
5017
1.69k
        writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
5018
1.69k
        writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
5019
1.69k
        writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
5020
1.69k
        writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
5021
1.69k
      }
5022
1.61k
    }
5023
1.61k
    RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
5024
1.61k
    Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
5025
1.61k
                              Buffer.data(), Buffer.size());
5026
1.61k
  }
5027
3.61k
5028
3.61k
  RecordData DeclUpdatesOffsetsRecord;
5029
3.61k
5030
3.61k
  // Keep writing types, declarations, and declaration update records
5031
3.61k
  // until we've emitted all of them.
5032
3.61k
  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
5033
3.61k
  WriteTypeAbbrevs();
5034
3.61k
  WriteDeclAbbrevs();
5035
3.67k
  do {
5036
3.67k
    WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
5037
686k
    while (!DeclTypesToEmit.empty()) {
5038
682k
      DeclOrType DOT = DeclTypesToEmit.front();
5039
682k
      DeclTypesToEmit.pop();
5040
682k
      if (DOT.isType())
5041
155k
        WriteType(DOT.getType());
5042
526k
      else
5043
526k
        WriteDecl(Context, DOT.getDecl());
5044
682k
    }
5045
3.67k
  } while (!DeclUpdates.empty());
5046
3.61k
  Stream.ExitBlock();
5047
3.61k
5048
3.61k
  DoneWritingDeclsAndTypes = true;
5049
3.61k
5050
3.61k
  // These things can only be done once we've written out decls and types.
5051
3.61k
  WriteTypeDeclOffsets();
5052
3.61k
  if (!DeclUpdatesOffsetsRecord.empty())
5053
173
    Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5054
3.61k
  WriteFileDeclIDsMap();
5055
3.61k
  WriteSourceManagerBlock(Context.getSourceManager(), PP);
5056
3.61k
  WriteComments();
5057
3.61k
  WritePreprocessor(PP, isModule);
5058
3.61k
  WriteHeaderSearch(PP.getHeaderSearchInfo());
5059
3.61k
  WriteSelectors(SemaRef);
5060
3.61k
  WriteReferencedSelectorsPool(SemaRef);