Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include/llvm/Bitstream/BitstreamWriter.h
Warning:line 493, column 9
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTWriter.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Serialization/ASTWriter.cpp

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Serialization/ASTWriter.cpp

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 "ASTCommon.h"
14#include "ASTReaderInternals.h"
15#include "MultiOnDiskHashTable.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTUnresolvedSet.h"
18#include "clang/AST/AbstractTypeWriter.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/OpenMPClause.h"
33#include "clang/AST/RawCommentList.h"
34#include "clang/AST/TemplateName.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLocVisitor.h"
37#include "clang/Basic/Diagnostic.h"
38#include "clang/Basic/DiagnosticOptions.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/FileSystemOptions.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Lambda.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/Module.h"
46#include "clang/Basic/ObjCRuntime.h"
47#include "clang/Basic/OpenCLOptions.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/SourceManagerInternals.h"
51#include "clang/Basic/Specifiers.h"
52#include "clang/Basic/TargetInfo.h"
53#include "clang/Basic/TargetOptions.h"
54#include "clang/Basic/Version.h"
55#include "clang/Lex/HeaderSearch.h"
56#include "clang/Lex/HeaderSearchOptions.h"
57#include "clang/Lex/MacroInfo.h"
58#include "clang/Lex/ModuleMap.h"
59#include "clang/Lex/PreprocessingRecord.h"
60#include "clang/Lex/Preprocessor.h"
61#include "clang/Lex/PreprocessorOptions.h"
62#include "clang/Lex/Token.h"
63#include "clang/Sema/IdentifierResolver.h"
64#include "clang/Sema/ObjCMethodList.h"
65#include "clang/Sema/Sema.h"
66#include "clang/Sema/Weak.h"
67#include "clang/Serialization/ASTBitCodes.h"
68#include "clang/Serialization/ASTReader.h"
69#include "clang/Serialization/ASTRecordWriter.h"
70#include "clang/Serialization/InMemoryModuleCache.h"
71#include "clang/Serialization/ModuleFile.h"
72#include "clang/Serialization/ModuleFileExtension.h"
73#include "clang/Serialization/SerializationDiagnostic.h"
74#include "llvm/ADT/APFloat.h"
75#include "llvm/ADT/APInt.h"
76#include "llvm/ADT/APSInt.h"
77#include "llvm/ADT/ArrayRef.h"
78#include "llvm/ADT/DenseMap.h"
79#include "llvm/ADT/Hashing.h"
80#include "llvm/ADT/Optional.h"
81#include "llvm/ADT/PointerIntPair.h"
82#include "llvm/ADT/STLExtras.h"
83#include "llvm/ADT/ScopeExit.h"
84#include "llvm/ADT/SmallPtrSet.h"
85#include "llvm/ADT/SmallString.h"
86#include "llvm/ADT/SmallVector.h"
87#include "llvm/ADT/StringMap.h"
88#include "llvm/ADT/StringRef.h"
89#include "llvm/Bitstream/BitCodes.h"
90#include "llvm/Bitstream/BitstreamWriter.h"
91#include "llvm/Support/Casting.h"
92#include "llvm/Support/Compression.h"
93#include "llvm/Support/DJB.h"
94#include "llvm/Support/Endian.h"
95#include "llvm/Support/EndianStream.h"
96#include "llvm/Support/Error.h"
97#include "llvm/Support/ErrorHandling.h"
98#include "llvm/Support/LEB128.h"
99#include "llvm/Support/MemoryBuffer.h"
100#include "llvm/Support/OnDiskHashTable.h"
101#include "llvm/Support/Path.h"
102#include "llvm/Support/SHA1.h"
103#include "llvm/Support/VersionTuple.h"
104#include "llvm/Support/raw_ostream.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <cstdlib>
109#include <cstring>
110#include <ctime>
111#include <limits>
112#include <memory>
113#include <queue>
114#include <tuple>
115#include <utility>
116#include <vector>
117
118using namespace clang;
119using namespace clang::serialization;
120
121template <typename T, typename Allocator>
122static StringRef bytes(const std::vector<T, Allocator> &v) {
123 if (v.empty()) return StringRef();
124 return StringRef(reinterpret_cast<const char*>(&v[0]),
125 sizeof(T) * v.size());
126}
127
128template <typename T>
129static StringRef bytes(const SmallVectorImpl<T> &v) {
130 return StringRef(reinterpret_cast<const char*>(v.data()),
131 sizeof(T) * v.size());
132}
133
134static std::string bytes(const std::vector<bool> &V) {
135 std::string Str;
136 Str.reserve(V.size() / 8);
137 for (unsigned I = 0, E = V.size(); I < E;) {
138 char Byte = 0;
139 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
140 Byte |= V[I] << Bit;
141 Str += Byte;
142 }
143 return Str;
144}
145
146//===----------------------------------------------------------------------===//
147// Type serialization
148//===----------------------------------------------------------------------===//
149
150static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
151 switch (id) {
152#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
153 case Type::CLASS_ID: return TYPE_##CODE_ID;
154#include "clang/Serialization/TypeBitCodes.def"
155 case Type::Builtin:
156 llvm_unreachable("shouldn't be serializing a builtin type this way")::llvm::llvm_unreachable_internal("shouldn't be serializing a builtin type this way"
, "clang/lib/Serialization/ASTWriter.cpp", 156)
;
157 }
158 llvm_unreachable("bad type kind")::llvm::llvm_unreachable_internal("bad type kind", "clang/lib/Serialization/ASTWriter.cpp"
, 158)
;
159}
160
161namespace {
162
163std::set<const FileEntry *> GetAllModuleMaps(const HeaderSearch &HS,
164 Module *RootModule) {
165 std::set<const FileEntry *> ModuleMaps{};
166 std::set<const Module *> ProcessedModules;
167 SmallVector<const Module *> ModulesToProcess{RootModule};
168
169 SmallVector<const FileEntry *, 16> FilesByUID;
170 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
171
172 if (FilesByUID.size() > HS.header_file_size())
173 FilesByUID.resize(HS.header_file_size());
174
175 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
176 const FileEntry *File = FilesByUID[UID];
177 if (!File)
178 continue;
179
180 const HeaderFileInfo *HFI =
181 HS.getExistingFileInfo(File, /*WantExternal*/ false);
182 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
183 continue;
184
185 for (const auto &KH : HS.findAllModulesForHeader(File)) {
186 if (!KH.getModule())
187 continue;
188 ModulesToProcess.push_back(KH.getModule());
189 }
190 }
191
192 while (!ModulesToProcess.empty()) {
193 auto *CurrentModule = ModulesToProcess.pop_back_val();
194 ProcessedModules.insert(CurrentModule);
195
196 auto *ModuleMapFile =
197 HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
198 if (!ModuleMapFile) {
199 continue;
200 }
201
202 ModuleMaps.insert(ModuleMapFile);
203
204 for (auto *ImportedModule : (CurrentModule)->Imports) {
205 if (!ImportedModule ||
206 ProcessedModules.find(ImportedModule) != ProcessedModules.end()) {
207 continue;
208 }
209 ModulesToProcess.push_back(ImportedModule);
210 }
211
212 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
213 if (UndeclaredModule &&
214 ProcessedModules.find(UndeclaredModule) == ProcessedModules.end())
215 ModulesToProcess.push_back(UndeclaredModule);
216 }
217
218 return ModuleMaps;
219}
220
221class ASTTypeWriter {
222 ASTWriter &Writer;
223 ASTWriter::RecordData Record;
224 ASTRecordWriter BasicWriter;
225
226public:
227 ASTTypeWriter(ASTWriter &Writer)
228 : Writer(Writer), BasicWriter(Writer, Record) {}
229
230 uint64_t write(QualType T) {
231 if (T.hasLocalNonFastQualifiers()) {
232 Qualifiers Qs = T.getLocalQualifiers();
233 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
234 BasicWriter.writeQualifiers(Qs);
235 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
236 }
237
238 const Type *typePtr = T.getTypePtr();
239 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
240 atw.write(typePtr);
241 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
242 /*abbrev*/ 0);
243 }
244};
245
246class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
247 using LocSeq = SourceLocationSequence;
248
249 ASTRecordWriter &Record;
250 LocSeq *Seq;
251
252 void addSourceLocation(SourceLocation Loc) {
253 Record.AddSourceLocation(Loc, Seq);
254 }
255 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
256
257public:
258 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
259 : Record(Record), Seq(Seq) {}
260
261#define ABSTRACT_TYPELOC(CLASS, PARENT)
262#define TYPELOC(CLASS, PARENT) \
263 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
264#include "clang/AST/TypeLocNodes.def"
265
266 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
267 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
268};
269
270} // namespace
271
272void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
273 // nothing to do
274}
275
276void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
277 addSourceLocation(TL.getBuiltinLoc());
278 if (TL.needsExtraLocalData()) {
279 Record.push_back(TL.getWrittenTypeSpec());
280 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
281 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
282 Record.push_back(TL.hasModeAttr());
283 }
284}
285
286void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
287 addSourceLocation(TL.getNameLoc());
288}
289
290void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
291 addSourceLocation(TL.getStarLoc());
292}
293
294void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
295 // nothing to do
296}
297
298void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
299 // nothing to do
300}
301
302void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
303 addSourceLocation(TL.getCaretLoc());
304}
305
306void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
307 addSourceLocation(TL.getAmpLoc());
308}
309
310void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
311 addSourceLocation(TL.getAmpAmpLoc());
312}
313
314void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
315 addSourceLocation(TL.getStarLoc());
316 Record.AddTypeSourceInfo(TL.getClassTInfo());
317}
318
319void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
320 addSourceLocation(TL.getLBracketLoc());
321 addSourceLocation(TL.getRBracketLoc());
322 Record.push_back(TL.getSizeExpr() ? 1 : 0);
323 if (TL.getSizeExpr())
324 Record.AddStmt(TL.getSizeExpr());
325}
326
327void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
328 VisitArrayTypeLoc(TL);
329}
330
331void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
332 VisitArrayTypeLoc(TL);
333}
334
335void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
336 VisitArrayTypeLoc(TL);
337}
338
339void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
340 DependentSizedArrayTypeLoc TL) {
341 VisitArrayTypeLoc(TL);
342}
343
344void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
345 DependentAddressSpaceTypeLoc TL) {
346 addSourceLocation(TL.getAttrNameLoc());
347 SourceRange range = TL.getAttrOperandParensRange();
348 addSourceLocation(range.getBegin());
349 addSourceLocation(range.getEnd());
350 Record.AddStmt(TL.getAttrExprOperand());
351}
352
353void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
354 DependentSizedExtVectorTypeLoc TL) {
355 addSourceLocation(TL.getNameLoc());
356}
357
358void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
359 addSourceLocation(TL.getNameLoc());
360}
361
362void TypeLocWriter::VisitDependentVectorTypeLoc(
363 DependentVectorTypeLoc TL) {
364 addSourceLocation(TL.getNameLoc());
365}
366
367void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
368 addSourceLocation(TL.getNameLoc());
369}
370
371void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
372 addSourceLocation(TL.getAttrNameLoc());
373 SourceRange range = TL.getAttrOperandParensRange();
374 addSourceLocation(range.getBegin());
375 addSourceLocation(range.getEnd());
376 Record.AddStmt(TL.getAttrRowOperand());
377 Record.AddStmt(TL.getAttrColumnOperand());
378}
379
380void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
381 DependentSizedMatrixTypeLoc TL) {
382 addSourceLocation(TL.getAttrNameLoc());
383 SourceRange range = TL.getAttrOperandParensRange();
384 addSourceLocation(range.getBegin());
385 addSourceLocation(range.getEnd());
386 Record.AddStmt(TL.getAttrRowOperand());
387 Record.AddStmt(TL.getAttrColumnOperand());
388}
389
390void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
391 addSourceLocation(TL.getLocalRangeBegin());
392 addSourceLocation(TL.getLParenLoc());
393 addSourceLocation(TL.getRParenLoc());
394 addSourceRange(TL.getExceptionSpecRange());
395 addSourceLocation(TL.getLocalRangeEnd());
396 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
397 Record.AddDeclRef(TL.getParam(i));
398}
399
400void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
401 VisitFunctionTypeLoc(TL);
402}
403
404void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
405 VisitFunctionTypeLoc(TL);
406}
407
408void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
409 addSourceLocation(TL.getNameLoc());
410}
411
412void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
413 addSourceLocation(TL.getNameLoc());
414}
415
416void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
417 addSourceLocation(TL.getNameLoc());
418}
419
420void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
421 if (TL.getNumProtocols()) {
422 addSourceLocation(TL.getProtocolLAngleLoc());
423 addSourceLocation(TL.getProtocolRAngleLoc());
424 }
425 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
426 addSourceLocation(TL.getProtocolLoc(i));
427}
428
429void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
430 addSourceLocation(TL.getTypeofLoc());
431 addSourceLocation(TL.getLParenLoc());
432 addSourceLocation(TL.getRParenLoc());
433}
434
435void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
436 addSourceLocation(TL.getTypeofLoc());
437 addSourceLocation(TL.getLParenLoc());
438 addSourceLocation(TL.getRParenLoc());
439 Record.AddTypeSourceInfo(TL.getUnmodifiedTInfo());
440}
441
442void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
443 addSourceLocation(TL.getDecltypeLoc());
444 addSourceLocation(TL.getRParenLoc());
445}
446
447void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
448 addSourceLocation(TL.getKWLoc());
449 addSourceLocation(TL.getLParenLoc());
450 addSourceLocation(TL.getRParenLoc());
451 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
452}
453
454void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
455 addSourceLocation(TL.getNameLoc());
456 Record.push_back(TL.isConstrained());
457 if (TL.isConstrained()) {
458 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
459 addSourceLocation(TL.getTemplateKWLoc());
460 addSourceLocation(TL.getConceptNameLoc());
461 Record.AddDeclRef(TL.getFoundDecl());
462 addSourceLocation(TL.getLAngleLoc());
463 addSourceLocation(TL.getRAngleLoc());
464 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
465 Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
466 TL.getArgLocInfo(I));
467 }
468 Record.push_back(TL.isDecltypeAuto());
469 if (TL.isDecltypeAuto())
470 addSourceLocation(TL.getRParenLoc());
471}
472
473void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
474 DeducedTemplateSpecializationTypeLoc TL) {
475 addSourceLocation(TL.getTemplateNameLoc());
476}
477
478void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
479 addSourceLocation(TL.getNameLoc());
480}
481
482void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
483 addSourceLocation(TL.getNameLoc());
484}
485
486void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
487 Record.AddAttr(TL.getAttr());
488}
489
490void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
491 // Nothing to do.
492}
493
494void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
495 addSourceLocation(TL.getNameLoc());
496}
497
498void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
499 SubstTemplateTypeParmTypeLoc TL) {
500 addSourceLocation(TL.getNameLoc());
501}
502
503void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
504 SubstTemplateTypeParmPackTypeLoc TL) {
505 addSourceLocation(TL.getNameLoc());
506}
507
508void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
509 TemplateSpecializationTypeLoc TL) {
510 addSourceLocation(TL.getTemplateKeywordLoc());
511 addSourceLocation(TL.getTemplateNameLoc());
512 addSourceLocation(TL.getLAngleLoc());
513 addSourceLocation(TL.getRAngleLoc());
514 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
515 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
516 TL.getArgLoc(i).getLocInfo());
517}
518
519void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
520 addSourceLocation(TL.getLParenLoc());
521 addSourceLocation(TL.getRParenLoc());
522}
523
524void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
525 addSourceLocation(TL.getExpansionLoc());
526}
527
528void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
529 addSourceLocation(TL.getElaboratedKeywordLoc());
530 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
531}
532
533void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
534 addSourceLocation(TL.getNameLoc());
535}
536
537void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
538 addSourceLocation(TL.getElaboratedKeywordLoc());
539 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
540 addSourceLocation(TL.getNameLoc());
541}
542
543void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
544 DependentTemplateSpecializationTypeLoc TL) {
545 addSourceLocation(TL.getElaboratedKeywordLoc());
546 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
547 addSourceLocation(TL.getTemplateKeywordLoc());
548 addSourceLocation(TL.getTemplateNameLoc());
549 addSourceLocation(TL.getLAngleLoc());
550 addSourceLocation(TL.getRAngleLoc());
551 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
552 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
553 TL.getArgLoc(I).getLocInfo());
554}
555
556void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
557 addSourceLocation(TL.getEllipsisLoc());
558}
559
560void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
561 addSourceLocation(TL.getNameLoc());
562}
563
564void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
565 Record.push_back(TL.hasBaseTypeAsWritten());
566 addSourceLocation(TL.getTypeArgsLAngleLoc());
567 addSourceLocation(TL.getTypeArgsRAngleLoc());
568 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
569 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
570 addSourceLocation(TL.getProtocolLAngleLoc());
571 addSourceLocation(TL.getProtocolRAngleLoc());
572 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
573 addSourceLocation(TL.getProtocolLoc(i));
574}
575
576void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
577 addSourceLocation(TL.getStarLoc());
578}
579
580void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
581 addSourceLocation(TL.getKWLoc());
582 addSourceLocation(TL.getLParenLoc());
583 addSourceLocation(TL.getRParenLoc());
584}
585
586void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
587 addSourceLocation(TL.getKWLoc());
588}
589
590void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
591 addSourceLocation(TL.getNameLoc());
592}
593void TypeLocWriter::VisitDependentBitIntTypeLoc(
594 clang::DependentBitIntTypeLoc TL) {
595 addSourceLocation(TL.getNameLoc());
596}
597
598void ASTWriter::WriteTypeAbbrevs() {
599 using namespace llvm;
600
601 std::shared_ptr<BitCodeAbbrev> Abv;
602
603 // Abbreviation for TYPE_EXT_QUAL
604 Abv = std::make_shared<BitCodeAbbrev>();
605 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
606 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
607 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
608 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
609}
610
611//===----------------------------------------------------------------------===//
612// ASTWriter Implementation
613//===----------------------------------------------------------------------===//
614
615static void EmitBlockID(unsigned ID, const char *Name,
616 llvm::BitstreamWriter &Stream,
617 ASTWriter::RecordDataImpl &Record) {
618 Record.clear();
619 Record.push_back(ID);
620 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
621
622 // Emit the block name if present.
623 if (!Name || Name[0] == 0)
624 return;
625 Record.clear();
626 while (*Name)
627 Record.push_back(*Name++);
628 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
629}
630
631static void EmitRecordID(unsigned ID, const char *Name,
632 llvm::BitstreamWriter &Stream,
633 ASTWriter::RecordDataImpl &Record) {
634 Record.clear();
635 Record.push_back(ID);
636 while (*Name)
637 Record.push_back(*Name++);
638 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
639}
640
641static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
642 ASTWriter::RecordDataImpl &Record) {
643#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
644 RECORD(STMT_STOP);
645 RECORD(STMT_NULL_PTR);
646 RECORD(STMT_REF_PTR);
647 RECORD(STMT_NULL);
648 RECORD(STMT_COMPOUND);
649 RECORD(STMT_CASE);
650 RECORD(STMT_DEFAULT);
651 RECORD(STMT_LABEL);
652 RECORD(STMT_ATTRIBUTED);
653 RECORD(STMT_IF);
654 RECORD(STMT_SWITCH);
655 RECORD(STMT_WHILE);
656 RECORD(STMT_DO);
657 RECORD(STMT_FOR);
658 RECORD(STMT_GOTO);
659 RECORD(STMT_INDIRECT_GOTO);
660 RECORD(STMT_CONTINUE);
661 RECORD(STMT_BREAK);
662 RECORD(STMT_RETURN);
663 RECORD(STMT_DECL);
664 RECORD(STMT_GCCASM);
665 RECORD(STMT_MSASM);
666 RECORD(EXPR_PREDEFINED);
667 RECORD(EXPR_DECL_REF);
668 RECORD(EXPR_INTEGER_LITERAL);
669 RECORD(EXPR_FIXEDPOINT_LITERAL);
670 RECORD(EXPR_FLOATING_LITERAL);
671 RECORD(EXPR_IMAGINARY_LITERAL);
672 RECORD(EXPR_STRING_LITERAL);
673 RECORD(EXPR_CHARACTER_LITERAL);
674 RECORD(EXPR_PAREN);
675 RECORD(EXPR_PAREN_LIST);
676 RECORD(EXPR_UNARY_OPERATOR);
677 RECORD(EXPR_SIZEOF_ALIGN_OF);
678 RECORD(EXPR_ARRAY_SUBSCRIPT);
679 RECORD(EXPR_CALL);
680 RECORD(EXPR_MEMBER);
681 RECORD(EXPR_BINARY_OPERATOR);
682 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
683 RECORD(EXPR_CONDITIONAL_OPERATOR);
684 RECORD(EXPR_IMPLICIT_CAST);
685 RECORD(EXPR_CSTYLE_CAST);
686 RECORD(EXPR_COMPOUND_LITERAL);
687 RECORD(EXPR_EXT_VECTOR_ELEMENT);
688 RECORD(EXPR_INIT_LIST);
689 RECORD(EXPR_DESIGNATED_INIT);
690 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
691 RECORD(EXPR_IMPLICIT_VALUE_INIT);
692 RECORD(EXPR_NO_INIT);
693 RECORD(EXPR_VA_ARG);
694 RECORD(EXPR_ADDR_LABEL);
695 RECORD(EXPR_STMT);
696 RECORD(EXPR_CHOOSE);
697 RECORD(EXPR_GNU_NULL);
698 RECORD(EXPR_SHUFFLE_VECTOR);
699 RECORD(EXPR_BLOCK);
700 RECORD(EXPR_GENERIC_SELECTION);
701 RECORD(EXPR_OBJC_STRING_LITERAL);
702 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
703 RECORD(EXPR_OBJC_ARRAY_LITERAL);
704 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
705 RECORD(EXPR_OBJC_ENCODE);
706 RECORD(EXPR_OBJC_SELECTOR_EXPR);
707 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
708 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
709 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
710 RECORD(EXPR_OBJC_KVC_REF_EXPR);
711 RECORD(EXPR_OBJC_MESSAGE_EXPR);
712 RECORD(STMT_OBJC_FOR_COLLECTION);
713 RECORD(STMT_OBJC_CATCH);
714 RECORD(STMT_OBJC_FINALLY);
715 RECORD(STMT_OBJC_AT_TRY);
716 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
717 RECORD(STMT_OBJC_AT_THROW);
718 RECORD(EXPR_OBJC_BOOL_LITERAL);
719 RECORD(STMT_CXX_CATCH);
720 RECORD(STMT_CXX_TRY);
721 RECORD(STMT_CXX_FOR_RANGE);
722 RECORD(EXPR_CXX_OPERATOR_CALL);
723 RECORD(EXPR_CXX_MEMBER_CALL);
724 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
725 RECORD(EXPR_CXX_CONSTRUCT);
726 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
727 RECORD(EXPR_CXX_STATIC_CAST);
728 RECORD(EXPR_CXX_DYNAMIC_CAST);
729 RECORD(EXPR_CXX_REINTERPRET_CAST);
730 RECORD(EXPR_CXX_CONST_CAST);
731 RECORD(EXPR_CXX_ADDRSPACE_CAST);
732 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
733 RECORD(EXPR_USER_DEFINED_LITERAL);
734 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
735 RECORD(EXPR_CXX_BOOL_LITERAL);
736 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
737 RECORD(EXPR_CXX_TYPEID_EXPR);
738 RECORD(EXPR_CXX_TYPEID_TYPE);
739 RECORD(EXPR_CXX_THIS);
740 RECORD(EXPR_CXX_THROW);
741 RECORD(EXPR_CXX_DEFAULT_ARG);
742 RECORD(EXPR_CXX_DEFAULT_INIT);
743 RECORD(EXPR_CXX_BIND_TEMPORARY);
744 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
745 RECORD(EXPR_CXX_NEW);
746 RECORD(EXPR_CXX_DELETE);
747 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
748 RECORD(EXPR_EXPR_WITH_CLEANUPS);
749 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
750 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
751 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
752 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
753 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
754 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
755 RECORD(EXPR_CXX_NOEXCEPT);
756 RECORD(EXPR_OPAQUE_VALUE);
757 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
758 RECORD(EXPR_TYPE_TRAIT);
759 RECORD(EXPR_ARRAY_TYPE_TRAIT);
760 RECORD(EXPR_PACK_EXPANSION);
761 RECORD(EXPR_SIZEOF_PACK);
762 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
763 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
764 RECORD(EXPR_FUNCTION_PARM_PACK);
765 RECORD(EXPR_MATERIALIZE_TEMPORARY);
766 RECORD(EXPR_CUDA_KERNEL_CALL);
767 RECORD(EXPR_CXX_UUIDOF_EXPR);
768 RECORD(EXPR_CXX_UUIDOF_TYPE);
769 RECORD(EXPR_LAMBDA);
770#undef RECORD
771}
772
773void ASTWriter::WriteBlockInfoBlock() {
774 RecordData Record;
775 Stream.EnterBlockInfoBlock();
776
777#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
778#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
779
780 // Control Block.
781 BLOCK(CONTROL_BLOCK);
782 RECORD(METADATA);
783 RECORD(MODULE_NAME);
784 RECORD(MODULE_DIRECTORY);
785 RECORD(MODULE_MAP_FILE);
786 RECORD(IMPORTS);
787 RECORD(ORIGINAL_FILE);
788 RECORD(ORIGINAL_FILE_ID);
789 RECORD(INPUT_FILE_OFFSETS);
790
791 BLOCK(OPTIONS_BLOCK);
792 RECORD(LANGUAGE_OPTIONS);
793 RECORD(TARGET_OPTIONS);
794 RECORD(FILE_SYSTEM_OPTIONS);
795 RECORD(HEADER_SEARCH_OPTIONS);
796 RECORD(PREPROCESSOR_OPTIONS);
797
798 BLOCK(INPUT_FILES_BLOCK);
799 RECORD(INPUT_FILE);
800 RECORD(INPUT_FILE_HASH);
801
802 // AST Top-Level Block.
803 BLOCK(AST_BLOCK);
804 RECORD(TYPE_OFFSET);
805 RECORD(DECL_OFFSET);
806 RECORD(IDENTIFIER_OFFSET);
807 RECORD(IDENTIFIER_TABLE);
808 RECORD(EAGERLY_DESERIALIZED_DECLS);
809 RECORD(MODULAR_CODEGEN_DECLS);
810 RECORD(SPECIAL_TYPES);
811 RECORD(STATISTICS);
812 RECORD(TENTATIVE_DEFINITIONS);
813 RECORD(SELECTOR_OFFSETS);
814 RECORD(METHOD_POOL);
815 RECORD(PP_COUNTER_VALUE);
816 RECORD(SOURCE_LOCATION_OFFSETS);
817 RECORD(SOURCE_LOCATION_PRELOADS);
818 RECORD(EXT_VECTOR_DECLS);
819 RECORD(UNUSED_FILESCOPED_DECLS);
820 RECORD(PPD_ENTITIES_OFFSETS);
821 RECORD(VTABLE_USES);
822 RECORD(PPD_SKIPPED_RANGES);
823 RECORD(REFERENCED_SELECTOR_POOL);
824 RECORD(TU_UPDATE_LEXICAL);
825 RECORD(SEMA_DECL_REFS);
826 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
827 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
828 RECORD(UPDATE_VISIBLE);
829 RECORD(DECL_UPDATE_OFFSETS);
830 RECORD(DECL_UPDATES);
831 RECORD(CUDA_SPECIAL_DECL_REFS);
832 RECORD(HEADER_SEARCH_TABLE);
833 RECORD(FP_PRAGMA_OPTIONS);
834 RECORD(OPENCL_EXTENSIONS);
835 RECORD(OPENCL_EXTENSION_TYPES);
836 RECORD(OPENCL_EXTENSION_DECLS);
837 RECORD(DELEGATING_CTORS);
838 RECORD(KNOWN_NAMESPACES);
839 RECORD(MODULE_OFFSET_MAP);
840 RECORD(SOURCE_MANAGER_LINE_TABLE);
841 RECORD(OBJC_CATEGORIES_MAP);
842 RECORD(FILE_SORTED_DECLS);
843 RECORD(IMPORTED_MODULES);
844 RECORD(OBJC_CATEGORIES);
845 RECORD(MACRO_OFFSET);
846 RECORD(INTERESTING_IDENTIFIERS);
847 RECORD(UNDEFINED_BUT_USED);
848 RECORD(LATE_PARSED_TEMPLATE);
849 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
850 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
851 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
852 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
853 RECORD(DELETE_EXPRS_TO_ANALYZE);
854 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
855 RECORD(PP_CONDITIONAL_STACK);
856 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
857 RECORD(PP_INCLUDED_FILES);
858 RECORD(PP_ASSUME_NONNULL_LOC);
859
860 // SourceManager Block.
861 BLOCK(SOURCE_MANAGER_BLOCK);
862 RECORD(SM_SLOC_FILE_ENTRY);
863 RECORD(SM_SLOC_BUFFER_ENTRY);
864 RECORD(SM_SLOC_BUFFER_BLOB);
865 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
866 RECORD(SM_SLOC_EXPANSION_ENTRY);
867
868 // Preprocessor Block.
869 BLOCK(PREPROCESSOR_BLOCK);
870 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
871 RECORD(PP_MACRO_FUNCTION_LIKE);
872 RECORD(PP_MACRO_OBJECT_LIKE);
873 RECORD(PP_MODULE_MACRO);
874 RECORD(PP_TOKEN);
875
876 // Submodule Block.
877 BLOCK(SUBMODULE_BLOCK);
878 RECORD(SUBMODULE_METADATA);
879 RECORD(SUBMODULE_DEFINITION);
880 RECORD(SUBMODULE_UMBRELLA_HEADER);
881 RECORD(SUBMODULE_HEADER);
882 RECORD(SUBMODULE_TOPHEADER);
883 RECORD(SUBMODULE_UMBRELLA_DIR);
884 RECORD(SUBMODULE_IMPORTS);
885 RECORD(SUBMODULE_AFFECTING_MODULES);
886 RECORD(SUBMODULE_EXPORTS);
887 RECORD(SUBMODULE_REQUIRES);
888 RECORD(SUBMODULE_EXCLUDED_HEADER);
889 RECORD(SUBMODULE_LINK_LIBRARY);
890 RECORD(SUBMODULE_CONFIG_MACRO);
891 RECORD(SUBMODULE_CONFLICT);
892 RECORD(SUBMODULE_PRIVATE_HEADER);
893 RECORD(SUBMODULE_TEXTUAL_HEADER);
894 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
895 RECORD(SUBMODULE_INITIALIZERS);
896 RECORD(SUBMODULE_EXPORT_AS);
897
898 // Comments Block.
899 BLOCK(COMMENTS_BLOCK);
900 RECORD(COMMENTS_RAW_COMMENT);
901
902 // Decls and Types block.
903 BLOCK(DECLTYPES_BLOCK);
904 RECORD(TYPE_EXT_QUAL);
905 RECORD(TYPE_COMPLEX);
906 RECORD(TYPE_POINTER);
907 RECORD(TYPE_BLOCK_POINTER);
908 RECORD(TYPE_LVALUE_REFERENCE);
909 RECORD(TYPE_RVALUE_REFERENCE);
910 RECORD(TYPE_MEMBER_POINTER);
911 RECORD(TYPE_CONSTANT_ARRAY);
912 RECORD(TYPE_INCOMPLETE_ARRAY);
913 RECORD(TYPE_VARIABLE_ARRAY);
914 RECORD(TYPE_VECTOR);
915 RECORD(TYPE_EXT_VECTOR);
916 RECORD(TYPE_FUNCTION_NO_PROTO);
917 RECORD(TYPE_FUNCTION_PROTO);
918 RECORD(TYPE_TYPEDEF);
919 RECORD(TYPE_TYPEOF_EXPR);
920 RECORD(TYPE_TYPEOF);
921 RECORD(TYPE_RECORD);
922 RECORD(TYPE_ENUM);
923 RECORD(TYPE_OBJC_INTERFACE);
924 RECORD(TYPE_OBJC_OBJECT_POINTER);
925 RECORD(TYPE_DECLTYPE);
926 RECORD(TYPE_ELABORATED);
927 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
928 RECORD(TYPE_UNRESOLVED_USING);
929 RECORD(TYPE_INJECTED_CLASS_NAME);
930 RECORD(TYPE_OBJC_OBJECT);
931 RECORD(TYPE_TEMPLATE_TYPE_PARM);
932 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
933 RECORD(TYPE_DEPENDENT_NAME);
934 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
935 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
936 RECORD(TYPE_PAREN);
937 RECORD(TYPE_MACRO_QUALIFIED);
938 RECORD(TYPE_PACK_EXPANSION);
939 RECORD(TYPE_ATTRIBUTED);
940 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
941 RECORD(TYPE_AUTO);
942 RECORD(TYPE_UNARY_TRANSFORM);
943 RECORD(TYPE_ATOMIC);
944 RECORD(TYPE_DECAYED);
945 RECORD(TYPE_ADJUSTED);
946 RECORD(TYPE_OBJC_TYPE_PARAM);
947 RECORD(LOCAL_REDECLARATIONS);
948 RECORD(DECL_TYPEDEF);
949 RECORD(DECL_TYPEALIAS);
950 RECORD(DECL_ENUM);
951 RECORD(DECL_RECORD);
952 RECORD(DECL_ENUM_CONSTANT);
953 RECORD(DECL_FUNCTION);
954 RECORD(DECL_OBJC_METHOD);
955 RECORD(DECL_OBJC_INTERFACE);
956 RECORD(DECL_OBJC_PROTOCOL);
957 RECORD(DECL_OBJC_IVAR);
958 RECORD(DECL_OBJC_AT_DEFS_FIELD);
959 RECORD(DECL_OBJC_CATEGORY);
960 RECORD(DECL_OBJC_CATEGORY_IMPL);
961 RECORD(DECL_OBJC_IMPLEMENTATION);
962 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
963 RECORD(DECL_OBJC_PROPERTY);
964 RECORD(DECL_OBJC_PROPERTY_IMPL);
965 RECORD(DECL_FIELD);
966 RECORD(DECL_MS_PROPERTY);
967 RECORD(DECL_VAR);
968 RECORD(DECL_IMPLICIT_PARAM);
969 RECORD(DECL_PARM_VAR);
970 RECORD(DECL_FILE_SCOPE_ASM);
971 RECORD(DECL_BLOCK);
972 RECORD(DECL_CONTEXT_LEXICAL);
973 RECORD(DECL_CONTEXT_VISIBLE);
974 RECORD(DECL_NAMESPACE);
975 RECORD(DECL_NAMESPACE_ALIAS);
976 RECORD(DECL_USING);
977 RECORD(DECL_USING_SHADOW);
978 RECORD(DECL_USING_DIRECTIVE);
979 RECORD(DECL_UNRESOLVED_USING_VALUE);
980 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
981 RECORD(DECL_LINKAGE_SPEC);
982 RECORD(DECL_CXX_RECORD);
983 RECORD(DECL_CXX_METHOD);
984 RECORD(DECL_CXX_CONSTRUCTOR);
985 RECORD(DECL_CXX_DESTRUCTOR);
986 RECORD(DECL_CXX_CONVERSION);
987 RECORD(DECL_ACCESS_SPEC);
988 RECORD(DECL_FRIEND);
989 RECORD(DECL_FRIEND_TEMPLATE);
990 RECORD(DECL_CLASS_TEMPLATE);
991 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
992 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
993 RECORD(DECL_VAR_TEMPLATE);
994 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
995 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
996 RECORD(DECL_FUNCTION_TEMPLATE);
997 RECORD(DECL_TEMPLATE_TYPE_PARM);
998 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
999 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1000 RECORD(DECL_CONCEPT);
1001 RECORD(DECL_REQUIRES_EXPR_BODY);
1002 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1003 RECORD(DECL_STATIC_ASSERT);
1004 RECORD(DECL_CXX_BASE_SPECIFIERS);
1005 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1006 RECORD(DECL_INDIRECTFIELD);
1007 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1008 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1009 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1010 RECORD(DECL_IMPORT);
1011 RECORD(DECL_OMP_THREADPRIVATE);
1012 RECORD(DECL_EMPTY);
1013 RECORD(DECL_OBJC_TYPE_PARAM);
1014 RECORD(DECL_OMP_CAPTUREDEXPR);
1015 RECORD(DECL_PRAGMA_COMMENT);
1016 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1017 RECORD(DECL_OMP_DECLARE_REDUCTION);
1018 RECORD(DECL_OMP_ALLOCATE);
1019 RECORD(DECL_HLSL_BUFFER);
1020
1021 // Statements and Exprs can occur in the Decls and Types block.
1022 AddStmtsExprs(Stream, Record);
1023
1024 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1025 RECORD(PPD_MACRO_EXPANSION);
1026 RECORD(PPD_MACRO_DEFINITION);
1027 RECORD(PPD_INCLUSION_DIRECTIVE);
1028
1029 // Decls and Types block.
1030 BLOCK(EXTENSION_BLOCK);
1031 RECORD(EXTENSION_METADATA);
1032
1033 BLOCK(UNHASHED_CONTROL_BLOCK);
1034 RECORD(SIGNATURE);
1035 RECORD(AST_BLOCK_HASH);
1036 RECORD(DIAGNOSTIC_OPTIONS);
1037 RECORD(DIAG_PRAGMA_MAPPINGS);
1038
1039#undef RECORD
1040#undef BLOCK
1041 Stream.ExitBlock();
1042}
1043
1044/// Prepares a path for being written to an AST file by converting it
1045/// to an absolute path and removing nested './'s.
1046///
1047/// \return \c true if the path was changed.
1048static bool cleanPathForOutput(FileManager &FileMgr,
1049 SmallVectorImpl<char> &Path) {
1050 bool Changed = FileMgr.makeAbsolutePath(Path);
1051 return Changed | llvm::sys::path::remove_dots(Path);
1052}
1053
1054/// Adjusts the given filename to only write out the portion of the
1055/// filename that is not part of the system root directory.
1056///
1057/// \param Filename the file name to adjust.
1058///
1059/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1060/// the returned filename will be adjusted by this root directory.
1061///
1062/// \returns either the original filename (if it needs no adjustment) or the
1063/// adjusted filename (which points into the @p Filename parameter).
1064static const char *
1065adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1066 assert(Filename && "No file name to adjust?")(static_cast <bool> (Filename && "No file name to adjust?"
) ? void (0) : __assert_fail ("Filename && \"No file name to adjust?\""
, "clang/lib/Serialization/ASTWriter.cpp", 1066, __extension__
__PRETTY_FUNCTION__))
;
1067
1068 if (BaseDir.empty())
1069 return Filename;
1070
1071 // Verify that the filename and the system root have the same prefix.
1072 unsigned Pos = 0;
1073 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1074 if (Filename[Pos] != BaseDir[Pos])
1075 return Filename; // Prefixes don't match.
1076
1077 // We hit the end of the filename before we hit the end of the system root.
1078 if (!Filename[Pos])
1079 return Filename;
1080
1081 // If there's not a path separator at the end of the base directory nor
1082 // immediately after it, then this isn't within the base directory.
1083 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1084 if (!llvm::sys::path::is_separator(BaseDir.back()))
1085 return Filename;
1086 } else {
1087 // If the file name has a '/' at the current position, skip over the '/'.
1088 // We distinguish relative paths from absolute paths by the
1089 // absence of '/' at the beginning of relative paths.
1090 //
1091 // FIXME: This is wrong. We distinguish them by asking if the path is
1092 // absolute, which isn't the same thing. And there might be multiple '/'s
1093 // in a row. Use a better mechanism to indicate whether we have emitted an
1094 // absolute or relative path.
1095 ++Pos;
1096 }
1097
1098 return Filename + Pos;
1099}
1100
1101std::pair<ASTFileSignature, ASTFileSignature>
1102ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
1103 llvm::SHA1 Hasher;
1104 Hasher.update(ASTBlockBytes);
1105 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1106
1107 // Add the remaining bytes (i.e. bytes before the unhashed control block that
1108 // are not part of the AST block).
1109 Hasher.update(
1110 AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1111 Hasher.update(
1112 AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1113 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1114
1115 return std::make_pair(ASTBlockHash, Signature);
1116}
1117
1118ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1119 ASTContext &Context) {
1120 using namespace llvm;
1121
1122 // Flush first to prepare the PCM hash (signature).
1123 Stream.FlushToWord();
1124 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1125
1126 // Enter the block and prepare to write records.
1127 RecordData Record;
1128 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1129
1130 // For implicit modules, write the hash of the PCM as its signature.
1131 ASTFileSignature Signature;
1132 if (WritingModule &&
1133 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1134 ASTFileSignature ASTBlockHash;
1135 auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1136 auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1137 std::tie(ASTBlockHash, Signature) = createSignature(
1138 StringRef(Buffer.begin(), StartOfUnhashedControl),
1139 StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1140
1141 Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1142 Stream.EmitRecord(AST_BLOCK_HASH, Record);
1143 Record.clear();
1144 Record.append(Signature.begin(), Signature.end());
1145 Stream.EmitRecord(SIGNATURE, Record);
1146 Record.clear();
1147 }
1148
1149 // Diagnostic options.
1150 const auto &Diags = Context.getDiagnostics();
1151 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1152#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1153#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1154 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1155#include "clang/Basic/DiagnosticOptions.def"
1156 Record.push_back(DiagOpts.Warnings.size());
1157 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1158 AddString(DiagOpts.Warnings[I], Record);
1159 Record.push_back(DiagOpts.Remarks.size());
1160 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1161 AddString(DiagOpts.Remarks[I], Record);
1162 // Note: we don't serialize the log or serialization file names, because they
1163 // are generally transient files and will almost always be overridden.
1164 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1165 Record.clear();
1166
1167 // Write out the diagnostic/pragma mappings.
1168 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1169
1170 // Header search entry usage.
1171 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1172 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1173 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1176 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1177 {
1178 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1179 HSEntryUsage.size()};
1180 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1181 }
1182
1183 // Leave the options block.
1184 Stream.ExitBlock();
1185 return Signature;
1186}
1187
1188/// Write the control block.
1189void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1190 StringRef isysroot) {
1191 using namespace llvm;
1192
1193 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1194 RecordData Record;
1195
1196 // Metadata
1197 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1198 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1199 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1200 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1201 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1202 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1203 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1205 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1206 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1207 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1208 assert((!WritingModule || isysroot.empty()) &&(static_cast <bool> ((!WritingModule || isysroot.empty(
)) && "writing module as a relocatable PCH?") ? void (
0) : __assert_fail ("(!WritingModule || isysroot.empty()) && \"writing module as a relocatable PCH?\""
, "clang/lib/Serialization/ASTWriter.cpp", 1209, __extension__
__PRETTY_FUNCTION__))
1209 "writing module as a relocatable PCH?")(static_cast <bool> ((!WritingModule || isysroot.empty(
)) && "writing module as a relocatable PCH?") ? void (
0) : __assert_fail ("(!WritingModule || isysroot.empty()) && \"writing module as a relocatable PCH?\""
, "clang/lib/Serialization/ASTWriter.cpp", 1209, __extension__
__PRETTY_FUNCTION__))
;
1210 {
1211 RecordData::value_type Record[] = {
1212 METADATA,
1213 VERSION_MAJOR,
1214 VERSION_MINOR,
1215 CLANG_VERSION_MAJOR16,
1216 CLANG_VERSION_MINOR0,
1217 !isysroot.empty(),
1218 IncludeTimestamps,
1219 ASTHasCompilerErrors};
1220 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1221 getClangFullRepositoryVersion());
1222 }
1223
1224 if (WritingModule) {
1225 // Module name
1226 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1227 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1229 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1230 RecordData::value_type Record[] = {MODULE_NAME};
1231 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1232 }
1233
1234 if (WritingModule && WritingModule->Directory) {
1235 SmallString<128> BaseDir;
1236 if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1237 // Use the current working directory as the base path for all inputs.
1238 auto *CWD =
1239 Context.getSourceManager().getFileManager().getDirectory(".").get();
1240 BaseDir.assign(CWD->getName());
1241 } else {
1242 BaseDir.assign(WritingModule->Directory->getName());
1243 }
1244 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1245
1246 // If the home of the module is the current working directory, then we
1247 // want to pick up the cwd of the build process loading the module, not
1248 // our cwd, when we load this module.
1249 if (!(PP.getHeaderSearchInfo()
1250 .getHeaderSearchOpts()
1251 .ModuleMapFileHomeIsCwd ||
1252 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) ||
1253 WritingModule->Directory->getName() != StringRef(".")) {
1254 // Module directory.
1255 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1256 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1258 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1259
1260 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1261 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1262 }
1263
1264 // Write out all other paths relative to the base directory if possible.
1265 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1266 } else if (!isysroot.empty()) {
1267 // Write out paths relative to the sysroot if possible.
1268 BaseDirectory = std::string(isysroot);
1269 }
1270
1271 // Module map file
1272 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1273 Record.clear();
1274
1275 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1276 AddPath(WritingModule->PresumedModuleMapFile.empty()
1277 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1278 : StringRef(WritingModule->PresumedModuleMapFile),
1279 Record);
1280
1281 // Additional module map files.
1282 if (auto *AdditionalModMaps =
1283 Map.getAdditionalModuleMapFiles(WritingModule)) {
1284 Record.push_back(AdditionalModMaps->size());
1285 SmallVector<const FileEntry *, 1> ModMaps(AdditionalModMaps->begin(),
1286 AdditionalModMaps->end());
1287 llvm::sort(ModMaps, [](const FileEntry *A, const FileEntry *B) {
1288 return A->getName() < B->getName();
1289 });
1290 for (const FileEntry *F : ModMaps)
1291 AddPath(F->getName(), Record);
1292 } else {
1293 Record.push_back(0);
1294 }
1295
1296 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1297 }
1298
1299 // Imports
1300 if (Chain) {
1301 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1302 Record.clear();
1303
1304 for (ModuleFile &M : Mgr) {
1305 // Skip modules that weren't directly imported.
1306 if (!M.isDirectlyImported())
1307 continue;
1308
1309 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1310 AddSourceLocation(M.ImportLoc, Record);
1311
1312 // If we have calculated signature, there is no need to store
1313 // the size or timestamp.
1314 Record.push_back(M.Signature ? 0 : M.File->getSize());
1315 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1316
1317 llvm::append_range(Record, M.Signature);
1318
1319 AddString(M.ModuleName, Record);
1320 AddPath(M.FileName, Record);
1321 }
1322 Stream.EmitRecord(IMPORTS, Record);
1323 }
1324
1325 // Write the options block.
1326 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1327
1328 // Language options.
1329 Record.clear();
1330 const LangOptions &LangOpts = Context.getLangOpts();
1331#define LANGOPT(Name, Bits, Default, Description) \
1332 Record.push_back(LangOpts.Name);
1333#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1334 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1335#include "clang/Basic/LangOptions.def"
1336#define SANITIZER(NAME, ID) \
1337 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1338#include "clang/Basic/Sanitizers.def"
1339
1340 Record.push_back(LangOpts.ModuleFeatures.size());
1341 for (StringRef Feature : LangOpts.ModuleFeatures)
1342 AddString(Feature, Record);
1343
1344 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1345 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1346
1347 AddString(LangOpts.CurrentModule, Record);
1348
1349 // Comment options.
1350 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1351 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1352 AddString(I, Record);
1353 }
1354 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1355
1356 // OpenMP offloading options.
1357 Record.push_back(LangOpts.OMPTargetTriples.size());
1358 for (auto &T : LangOpts.OMPTargetTriples)
1359 AddString(T.getTriple(), Record);
1360
1361 AddString(LangOpts.OMPHostIRFile, Record);
1362
1363 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1364
1365 // Target options.
1366 Record.clear();
1367 const TargetInfo &Target = Context.getTargetInfo();
1368 const TargetOptions &TargetOpts = Target.getTargetOpts();
1369 AddString(TargetOpts.Triple, Record);
1370 AddString(TargetOpts.CPU, Record);
1371 AddString(TargetOpts.TuneCPU, Record);
1372 AddString(TargetOpts.ABI, Record);
1373 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1374 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1375 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1376 }
1377 Record.push_back(TargetOpts.Features.size());
1378 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1379 AddString(TargetOpts.Features[I], Record);
1380 }
1381 Stream.EmitRecord(TARGET_OPTIONS, Record);
1382
1383 // File system options.
1384 Record.clear();
1385 const FileSystemOptions &FSOpts =
1386 Context.getSourceManager().getFileManager().getFileSystemOpts();
1387 AddString(FSOpts.WorkingDir, Record);
1388 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1389
1390 // Header search options.
1391 Record.clear();
1392 const HeaderSearchOptions &HSOpts
1393 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1394 AddString(HSOpts.Sysroot, Record);
1395
1396 // Include entries.
1397 Record.push_back(HSOpts.UserEntries.size());
1398 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1399 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1400 AddString(Entry.Path, Record);
1401 Record.push_back(static_cast<unsigned>(Entry.Group));
1402 Record.push_back(Entry.IsFramework);
1403 Record.push_back(Entry.IgnoreSysRoot);
1404 }
1405
1406 // System header prefixes.
1407 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1408 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1409 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1410 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1411 }
1412
1413 AddString(HSOpts.ResourceDir, Record);
1414 AddString(HSOpts.ModuleCachePath, Record);
1415 AddString(HSOpts.ModuleUserBuildPath, Record);
1416 Record.push_back(HSOpts.DisableModuleHash);
1417 Record.push_back(HSOpts.ImplicitModuleMaps);
1418 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1419 Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1420 Record.push_back(HSOpts.UseBuiltinIncludes);
1421 Record.push_back(HSOpts.UseStandardSystemIncludes);
1422 Record.push_back(HSOpts.UseStandardCXXIncludes);
1423 Record.push_back(HSOpts.UseLibcxx);
1424 // Write out the specific module cache path that contains the module files.
1425 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1426 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1427
1428 // Preprocessor options.
1429 Record.clear();
1430 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1431
1432 // Macro definitions.
1433 Record.push_back(PPOpts.Macros.size());
1434 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1435 AddString(PPOpts.Macros[I].first, Record);
1436 Record.push_back(PPOpts.Macros[I].second);
1437 }
1438
1439 // Includes
1440 Record.push_back(PPOpts.Includes.size());
1441 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1442 AddString(PPOpts.Includes[I], Record);
1443
1444 // Macro includes
1445 Record.push_back(PPOpts.MacroIncludes.size());
1446 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1447 AddString(PPOpts.MacroIncludes[I], Record);
1448
1449 Record.push_back(PPOpts.UsePredefines);
1450 // Detailed record is important since it is used for the module cache hash.
1451 Record.push_back(PPOpts.DetailedRecord);
1452 AddString(PPOpts.ImplicitPCHInclude, Record);
1453 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1454 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1455
1456 // Leave the options block.
1457 Stream.ExitBlock();
1458
1459 // Original file name and file ID
1460 SourceManager &SM = Context.getSourceManager();
1461 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1462 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1463 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1464 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1465 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1466 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1467
1468 Record.clear();
1469 Record.push_back(ORIGINAL_FILE);
1470 Record.push_back(SM.getMainFileID().getOpaqueValue());
1471 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1472 }
1473
1474 Record.clear();
1475 Record.push_back(SM.getMainFileID().getOpaqueValue());
1476 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1477
1478 std::set<const FileEntry *> AffectingModuleMaps;
1479 if (WritingModule) {
1480 AffectingModuleMaps =
1481 GetAllModuleMaps(PP.getHeaderSearchInfo(), WritingModule);
1482 }
1483
1484 WriteInputFiles(Context.SourceMgr,
1485 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1486 AffectingModuleMaps);
1487 Stream.ExitBlock();
1488}
1489
1490namespace {
1491
1492/// An input file.
1493struct InputFileEntry {
1494 const FileEntry *File;
1495 bool IsSystemFile;
1496 bool IsTransient;
1497 bool BufferOverridden;
1498 bool IsTopLevelModuleMap;
1499 uint32_t ContentHash[2];
1500};
1501
1502} // namespace
1503
1504void ASTWriter::WriteInputFiles(
1505 SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
1506 std::set<const FileEntry *> &AffectingModuleMaps) {
1507 using namespace llvm;
1508
1509 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1510
1511 // Create input-file abbreviation.
1512 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1513 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1514 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1515 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1516 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1517 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1518 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1519 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1520 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1521 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1522
1523 // Create input file hash abbreviation.
1524 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1525 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1526 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1527 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1528 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1529
1530 // Get all ContentCache objects for files.
1531 std::vector<InputFileEntry> UserFiles;
1532 std::vector<InputFileEntry> SystemFiles;
1533 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1534 // Get this source location entry.
1535 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1536 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc)(static_cast <bool> (&SourceMgr.getSLocEntry(FileID
::get(I)) == SLoc) ? void (0) : __assert_fail ("&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc"
, "clang/lib/Serialization/ASTWriter.cpp", 1536, __extension__
__PRETTY_FUNCTION__))
;
1537
1538 // We only care about file entries that were not overridden.
1539 if (!SLoc->isFile())
1540 continue;
1541 const SrcMgr::FileInfo &File = SLoc->getFile();
1542 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1543 if (!Cache->OrigEntry)
1544 continue;
1545
1546 if (isModuleMap(File.getFileCharacteristic()) &&
1547 !isSystem(File.getFileCharacteristic()) &&
1548 !AffectingModuleMaps.empty() &&
1549 AffectingModuleMaps.find(Cache->OrigEntry) ==
1550 AffectingModuleMaps.end()) {
1551 SkippedModuleMaps.insert(Cache->OrigEntry);
1552 // Do not emit modulemaps that do not affect current module.
1553 continue;
1554 }
1555
1556 InputFileEntry Entry;
1557 Entry.File = Cache->OrigEntry;
1558 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1559 Entry.IsTransient = Cache->IsTransient;
1560 Entry.BufferOverridden = Cache->BufferOverridden;
1561 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1562 File.getIncludeLoc().isInvalid();
1563
1564 auto ContentHash = hash_code(-1);
1565 if (PP->getHeaderSearchInfo()
1566 .getHeaderSearchOpts()
1567 .ValidateASTInputFilesContent) {
1568 auto MemBuff = Cache->getBufferIfLoaded();
1569 if (MemBuff)
1570 ContentHash = hash_value(MemBuff->getBuffer());
1571 else
1572 // FIXME: The path should be taken from the FileEntryRef.
1573 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1574 << Entry.File->getName();
1575 }
1576 auto CH = llvm::APInt(64, ContentHash);
1577 Entry.ContentHash[0] =
1578 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1579 Entry.ContentHash[1] =
1580 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1581
1582 if (Entry.IsSystemFile)
1583 SystemFiles.push_back(Entry);
1584 else
1585 UserFiles.push_back(Entry);
1586 }
1587
1588 // User files go at the front, system files at the back.
1589 auto SortedFiles = llvm::concat<InputFileEntry>(std::move(UserFiles),
1590 std::move(SystemFiles));
1591
1592 unsigned UserFilesNum = 0;
1593 // Write out all of the input files.
1594 std::vector<uint64_t> InputFileOffsets;
1595 for (const auto &Entry : SortedFiles) {
1596 uint32_t &InputFileID = InputFileIDs[Entry.File];
1597 if (InputFileID != 0)
1598 continue; // already recorded this file.
1599
1600 // Record this entry's offset.
1601 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1602
1603 InputFileID = InputFileOffsets.size();
1604
1605 if (!Entry.IsSystemFile)
1606 ++UserFilesNum;
1607
1608 // Emit size/modification time for this file.
1609 // And whether this file was overridden.
1610 {
1611 RecordData::value_type Record[] = {
1612 INPUT_FILE,
1613 InputFileOffsets.size(),
1614 (uint64_t)Entry.File->getSize(),
1615 (uint64_t)getTimestampForOutput(Entry.File),
1616 Entry.BufferOverridden,
1617 Entry.IsTransient,
1618 Entry.IsTopLevelModuleMap};
1619
1620 // FIXME: The path should be taken from the FileEntryRef.
1621 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1622 }
1623
1624 // Emit content hash for this file.
1625 {
1626 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1627 Entry.ContentHash[1]};
1628 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1629 }
1630 }
1631
1632 Stream.ExitBlock();
1633
1634 // Create input file offsets abbreviation.
1635 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1636 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1637 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1638 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1639 // input files
1640 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1641 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1642
1643 // Write input file offsets.
1644 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1645 InputFileOffsets.size(), UserFilesNum};
1646 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1647}
1648
1649//===----------------------------------------------------------------------===//
1650// Source Manager Serialization
1651//===----------------------------------------------------------------------===//
1652
1653/// Create an abbreviation for the SLocEntry that refers to a
1654/// file.
1655static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1656 using namespace llvm;
1657
1658 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1659 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1664 // FileEntry fields.
1665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1669 return Stream.EmitAbbrev(std::move(Abbrev));
1670}
1671
1672/// Create an abbreviation for the SLocEntry that refers to a
1673/// buffer.
1674static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1675 using namespace llvm;
1676
1677 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1678 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1684 return Stream.EmitAbbrev(std::move(Abbrev));
1685}
1686
1687/// Create an abbreviation for the SLocEntry that refers to a
1688/// buffer's blob.
1689static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1690 bool Compressed) {
1691 using namespace llvm;
1692
1693 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1694 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1695 : SM_SLOC_BUFFER_BLOB));
1696 if (Compressed)
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1699 return Stream.EmitAbbrev(std::move(Abbrev));
1700}
1701
1702/// Create an abbreviation for the SLocEntry that refers to a macro
1703/// expansion.
1704static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1705 using namespace llvm;
1706
1707 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1708 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
1712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
1713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1715 return Stream.EmitAbbrev(std::move(Abbrev));
1716}
1717
1718/// Emit key length and data length as ULEB-encoded data, and return them as a
1719/// pair.
1720static std::pair<unsigned, unsigned>
1721emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1722 llvm::encodeULEB128(KeyLen, Out);
1723 llvm::encodeULEB128(DataLen, Out);
1724 return std::make_pair(KeyLen, DataLen);
1725}
1726
1727namespace {
1728
1729 // Trait used for the on-disk hash table of header search information.
1730 class HeaderFileInfoTrait {
1731 ASTWriter &Writer;
1732
1733 // Keep track of the framework names we've used during serialization.
1734 SmallString<128> FrameworkStringData;
1735 llvm::StringMap<unsigned> FrameworkNameOffset;
1736
1737 public:
1738 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1739
1740 struct key_type {
1741 StringRef Filename;
1742 off_t Size;
1743 time_t ModTime;
1744 };
1745 using key_type_ref = const key_type &;
1746
1747 using UnresolvedModule =
1748 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1749
1750 struct data_type {
1751 const HeaderFileInfo &HFI;
1752 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1753 UnresolvedModule Unresolved;
1754 };
1755 using data_type_ref = const data_type &;
1756
1757 using hash_value_type = unsigned;
1758 using offset_type = unsigned;
1759
1760 hash_value_type ComputeHash(key_type_ref key) {
1761 // The hash is based only on size/time of the file, so that the reader can
1762 // match even when symlinking or excess path elements ("foo/../", "../")
1763 // change the form of the name. However, complete path is still the key.
1764 return llvm::hash_combine(key.Size, key.ModTime);
1765 }
1766
1767 std::pair<unsigned, unsigned>
1768 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1769 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1770 unsigned DataLen = 1 + 4 + 4;
1771 for (auto ModInfo : Data.KnownHeaders)
1772 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1773 DataLen += 4;
1774 if (Data.Unresolved.getPointer())
1775 DataLen += 4;
1776 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1777 }
1778
1779 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1780 using namespace llvm::support;
1781
1782 endian::Writer LE(Out, little);
1783 LE.write<uint64_t>(key.Size);
1784 KeyLen -= 8;
1785 LE.write<uint64_t>(key.ModTime);
1786 KeyLen -= 8;
1787 Out.write(key.Filename.data(), KeyLen);
1788 }
1789
1790 void EmitData(raw_ostream &Out, key_type_ref key,
1791 data_type_ref Data, unsigned DataLen) {
1792 using namespace llvm::support;
1793
1794 endian::Writer LE(Out, little);
1795 uint64_t Start = Out.tell(); (void)Start;
1796
1797 unsigned char Flags = (Data.HFI.isImport << 5)
1798 | (Data.HFI.isPragmaOnce << 4)
1799 | (Data.HFI.DirInfo << 1)
1800 | Data.HFI.IndexHeaderMapHeader;
1801 LE.write<uint8_t>(Flags);
1802
1803 if (!Data.HFI.ControllingMacro)
1804 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1805 else
1806 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1807
1808 unsigned Offset = 0;
1809 if (!Data.HFI.Framework.empty()) {
1810 // If this header refers into a framework, save the framework name.
1811 llvm::StringMap<unsigned>::iterator Pos
1812 = FrameworkNameOffset.find(Data.HFI.Framework);
1813 if (Pos == FrameworkNameOffset.end()) {
1814 Offset = FrameworkStringData.size() + 1;
1815 FrameworkStringData.append(Data.HFI.Framework);
1816 FrameworkStringData.push_back(0);
1817
1818 FrameworkNameOffset[Data.HFI.Framework] = Offset;
1819 } else
1820 Offset = Pos->second;
1821 }
1822 LE.write<uint32_t>(Offset);
1823
1824 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1825 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1826 uint32_t Value = (ModID << 3) | (unsigned)Role;
1827 assert((Value >> 3) == ModID && "overflow in header module info")(static_cast <bool> ((Value >> 3) == ModID &&
"overflow in header module info") ? void (0) : __assert_fail
("(Value >> 3) == ModID && \"overflow in header module info\""
, "clang/lib/Serialization/ASTWriter.cpp", 1827, __extension__
__PRETTY_FUNCTION__))
;
1828 LE.write<uint32_t>(Value);
1829 }
1830 };
1831
1832 // FIXME: If the header is excluded, we should write out some
1833 // record of that fact.
1834 for (auto ModInfo : Data.KnownHeaders)
1835 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1836 if (Data.Unresolved.getPointer())
1837 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1838
1839 assert(Out.tell() - Start == DataLen && "Wrong data length")(static_cast <bool> (Out.tell() - Start == DataLen &&
"Wrong data length") ? void (0) : __assert_fail ("Out.tell() - Start == DataLen && \"Wrong data length\""
, "clang/lib/Serialization/ASTWriter.cpp", 1839, __extension__
__PRETTY_FUNCTION__))
;
1840 }
1841
1842 const char *strings_begin() const { return FrameworkStringData.begin(); }
1843 const char *strings_end() const { return FrameworkStringData.end(); }
1844 };
1845
1846} // namespace
1847
1848/// Write the header search block for the list of files that
1849///
1850/// \param HS The header search structure to save.
1851void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1852 HeaderFileInfoTrait GeneratorTrait(*this);
1853 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1854 SmallVector<const char *, 4> SavedStrings;
1855 unsigned NumHeaderSearchEntries = 0;
1856
1857 // Find all unresolved headers for the current module. We generally will
1858 // have resolved them before we get here, but not necessarily: we might be
1859 // compiling a preprocessed module, where there is no requirement for the
1860 // original files to exist any more.
1861 const HeaderFileInfo Empty; // So we can take a reference.
1862 if (WritingModule) {
1863 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1864 while (!Worklist.empty()) {
1865 Module *M = Worklist.pop_back_val();
1866 // We don't care about headers in unimportable submodules.
1867 if (M->isUnimportable())
1868 continue;
1869
1870 // Map to disk files where possible, to pick up any missing stat
1871 // information. This also means we don't need to check the unresolved
1872 // headers list when emitting resolved headers in the first loop below.
1873 // FIXME: It'd be preferable to avoid doing this if we were given
1874 // sufficient stat information in the module map.
1875 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/llvm::None);
1876
1877 // If the file didn't exist, we can still create a module if we were given
1878 // enough information in the module map.
1879 for (auto U : M->MissingHeaders) {
1880 // Check that we were given enough information to build a module
1881 // without this file existing on disk.
1882 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1883 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1884 << WritingModule->getFullModuleName() << U.Size.has_value()
1885 << U.FileName;
1886 continue;
1887 }
1888
1889 // Form the effective relative pathname for the file.
1890 SmallString<128> Filename(M->Directory->getName());
1891 llvm::sys::path::append(Filename, U.FileName);
1892 PreparePathForOutput(Filename);
1893
1894 StringRef FilenameDup = strdup(Filename.c_str());
1895 SavedStrings.push_back(FilenameDup.data());
1896
1897 HeaderFileInfoTrait::key_type Key = {
1898 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1899 };
1900 HeaderFileInfoTrait::data_type Data = {
1901 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
1902 };
1903 // FIXME: Deal with cases where there are multiple unresolved header
1904 // directives in different submodules for the same header.
1905 Generator.insert(Key, Data, GeneratorTrait);
1906 ++NumHeaderSearchEntries;
1907 }
1908
1909 Worklist.append(M->submodule_begin(), M->submodule_end());
1910 }
1911 }
1912
1913 SmallVector<const FileEntry *, 16> FilesByUID;
1914 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1915
1916 if (FilesByUID.size() > HS.header_file_size())
1917 FilesByUID.resize(HS.header_file_size());
1918
1919 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1920 const FileEntry *File = FilesByUID[UID];
1921 if (!File)
1922 continue;
1923
1924 // Get the file info. This will load info from the external source if
1925 // necessary. Skip emitting this file if we have no information on it
1926 // as a header file (in which case HFI will be null) or if it hasn't
1927 // changed since it was loaded. Also skip it if it's for a modular header
1928 // from a different module; in that case, we rely on the module(s)
1929 // containing the header to provide this information.
1930 const HeaderFileInfo *HFI =
1931 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1932 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1933 continue;
1934
1935 // Massage the file path into an appropriate form.
1936 StringRef Filename = File->getName();
1937 SmallString<128> FilenameTmp(Filename);
1938 if (PreparePathForOutput(FilenameTmp)) {
1939 // If we performed any translation on the file name at all, we need to
1940 // save this string, since the generator will refer to it later.
1941 Filename = StringRef(strdup(FilenameTmp.c_str()));
1942 SavedStrings.push_back(Filename.data());
1943 }
1944
1945 HeaderFileInfoTrait::key_type Key = {
1946 Filename, File->getSize(), getTimestampForOutput(File)
1947 };
1948 HeaderFileInfoTrait::data_type Data = {
1949 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
1950 };
1951 Generator.insert(Key, Data, GeneratorTrait);
1952 ++NumHeaderSearchEntries;
1953 }
1954
1955 // Create the on-disk hash table in a buffer.
1956 SmallString<4096> TableData;
1957 uint32_t BucketOffset;
1958 {
1959 using namespace llvm::support;
1960
1961 llvm::raw_svector_ostream Out(TableData);
1962 // Make sure that no bucket is at offset 0
1963 endian::write<uint32_t>(Out, 0, little);
1964 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1965 }
1966
1967 // Create a blob abbreviation
1968 using namespace llvm;
1969
1970 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1971 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1972 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1973 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1974 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1975 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1976 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1977
1978 // Write the header search table
1979 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1980 NumHeaderSearchEntries, TableData.size()};
1981 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1982 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1983
1984 // Free all of the strings we had to duplicate.
1985 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1986 free(const_cast<char *>(SavedStrings[I]));
1987}
1988
1989static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1990 unsigned SLocBufferBlobCompressedAbbrv,
1991 unsigned SLocBufferBlobAbbrv) {
1992 using RecordDataType = ASTWriter::RecordData::value_type;
1993
1994 // Compress the buffer if possible. We expect that almost all PCM
1995 // consumers will not want its contents.
1996 SmallVector<uint8_t, 0> CompressedBuffer;
1997 if (llvm::compression::zlib::isAvailable()) {
1998 llvm::compression::zlib::compress(
1999 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
2000 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2001 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2002 llvm::toStringRef(CompressedBuffer));
2003 return;
2004 }
2005
2006 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2007 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2008}
2009
2010/// Writes the block containing the serialized form of the
2011/// source manager.
2012///
2013/// TODO: We should probably use an on-disk hash table (stored in a
2014/// blob), indexed based on the file name, so that we only create
2015/// entries for files that we actually need. In the common case (no
2016/// errors), we probably won't have to create file entries for any of
2017/// the files in the AST.
2018void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2019 const Preprocessor &PP) {
2020 RecordData Record;
2021
2022 // Enter the source manager block.
2023 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2024 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2025
2026 // Abbreviations for the various kinds of source-location entries.
2027 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2028 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2029 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2030 unsigned SLocBufferBlobCompressedAbbrv =
2031 CreateSLocBufferBlobAbbrev(Stream, true);
2032 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2033
2034 // Write out the source location entry table. We skip the first
2035 // entry, which is always the same dummy entry.
2036 std::vector<uint32_t> SLocEntryOffsets;
2037 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2038 RecordData PreloadSLocs;
2039 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2040 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2041 I != N; ++I) {
2042 // Get this source location entry.
2043 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2044 FileID FID = FileID::get(I);
2045 assert(&SourceMgr.getSLocEntry(FID) == SLoc)(static_cast <bool> (&SourceMgr.getSLocEntry(FID) ==
SLoc) ? void (0) : __assert_fail ("&SourceMgr.getSLocEntry(FID) == SLoc"
, "clang/lib/Serialization/ASTWriter.cpp", 2045, __extension__
__PRETTY_FUNCTION__))
;
2046
2047 // Record the offset of this source-location entry.
2048 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2049 assert((Offset >> 32) == 0 && "SLocEntry offset too large")(static_cast <bool> ((Offset >> 32) == 0 &&
"SLocEntry offset too large") ? void (0) : __assert_fail ("(Offset >> 32) == 0 && \"SLocEntry offset too large\""
, "clang/lib/Serialization/ASTWriter.cpp", 2049, __extension__
__PRETTY_FUNCTION__))
;
2050 SLocEntryOffsets.push_back(Offset);
2051
2052 // Figure out which record code to use.
2053 unsigned Code;
2054 if (SLoc->isFile()) {
2055 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2056 if (Cache->OrigEntry) {
2057 Code = SM_SLOC_FILE_ENTRY;
2058 } else
2059 Code = SM_SLOC_BUFFER_ENTRY;
2060 } else
2061 Code = SM_SLOC_EXPANSION_ENTRY;
2062 Record.clear();
2063 Record.push_back(Code);
2064
2065 // Starting offset of this entry within this module, so skip the dummy.
2066 Record.push_back(SLoc->getOffset() - 2);
2067 if (SLoc->isFile()) {
2068 const SrcMgr::FileInfo &File = SLoc->getFile();
2069 const SrcMgr::ContentCache *Content = &File.getContentCache();
2070 if (Content->OrigEntry && !SkippedModuleMaps.empty() &&
2071 SkippedModuleMaps.find(Content->OrigEntry) !=
2072 SkippedModuleMaps.end()) {
2073 // Do not emit files that were not listed as inputs.
2074 continue;
2075 }
2076 AddSourceLocation(File.getIncludeLoc(), Record);
2077 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2078 Record.push_back(File.hasLineDirectives());
2079
2080 bool EmitBlob = false;
2081 if (Content->OrigEntry) {
2082 assert(Content->OrigEntry == Content->ContentsEntry &&(static_cast <bool> (Content->OrigEntry == Content->
ContentsEntry && "Writing to AST an overridden file is not supported"
) ? void (0) : __assert_fail ("Content->OrigEntry == Content->ContentsEntry && \"Writing to AST an overridden file is not supported\""
, "clang/lib/Serialization/ASTWriter.cpp", 2083, __extension__
__PRETTY_FUNCTION__))
2083 "Writing to AST an overridden file is not supported")(static_cast <bool> (Content->OrigEntry == Content->
ContentsEntry && "Writing to AST an overridden file is not supported"
) ? void (0) : __assert_fail ("Content->OrigEntry == Content->ContentsEntry && \"Writing to AST an overridden file is not supported\""
, "clang/lib/Serialization/ASTWriter.cpp", 2083, __extension__
__PRETTY_FUNCTION__))
;
2084
2085 // The source location entry is a file. Emit input file ID.
2086 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry")(static_cast <bool> (InputFileIDs[Content->OrigEntry
] != 0 && "Missed file entry") ? void (0) : __assert_fail
("InputFileIDs[Content->OrigEntry] != 0 && \"Missed file entry\""
, "clang/lib/Serialization/ASTWriter.cpp", 2086, __extension__
__PRETTY_FUNCTION__))
;
2087 Record.push_back(InputFileIDs[Content->OrigEntry]);
2088
2089 Record.push_back(File.NumCreatedFIDs);
2090
2091 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2092 if (FDI != FileDeclIDs.end()) {
2093 Record.push_back(FDI->second->FirstDeclIndex);
2094 Record.push_back(FDI->second->DeclIDs.size());
2095 } else {
2096 Record.push_back(0);
2097 Record.push_back(0);
2098 }
2099
2100 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2101
2102 if (Content->BufferOverridden || Content->IsTransient)
2103 EmitBlob = true;
2104 } else {
2105 // The source location entry is a buffer. The blob associated
2106 // with this entry contains the contents of the buffer.
2107
2108 // We add one to the size so that we capture the trailing NULL
2109 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2110 // the reader side).
2111 llvm::Optional<llvm::MemoryBufferRef> Buffer =
2112 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2113 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2114 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2115 StringRef(Name.data(), Name.size() + 1));
2116 EmitBlob = true;
2117
2118 if (Name == "<built-in>")
2119 PreloadSLocs.push_back(SLocEntryOffsets.size());
2120 }
2121
2122 if (EmitBlob) {
2123 // Include the implicit terminating null character in the on-disk buffer
2124 // if we're writing it uncompressed.
2125 llvm::Optional<llvm::MemoryBufferRef> Buffer =
2126 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2127 if (!Buffer)
2128 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2129 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2130 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2131 SLocBufferBlobAbbrv);
2132 }
2133 } else {
2134 // The source location entry is a macro expansion.
2135 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2136 LocSeq::State Seq;
2137 AddSourceLocation(Expansion.getSpellingLoc(), Record, Seq);
2138 AddSourceLocation(Expansion.getExpansionLocStart(), Record, Seq);
2139 AddSourceLocation(Expansion.isMacroArgExpansion()
2140 ? SourceLocation()
2141 : Expansion.getExpansionLocEnd(),
2142 Record, Seq);
2143 Record.push_back(Expansion.isExpansionTokenRange());
2144
2145 // Compute the token length for this macro expansion.
2146 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2147 if (I + 1 != N)
2148 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2149 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2150 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2151 }
2152 }
2153
2154 Stream.ExitBlock();
2155
2156 if (SLocEntryOffsets.empty())
2157 return;
2158
2159 // Write the source-location offsets table into the AST block. This
2160 // table is used for lazily loading source-location information.
2161 using namespace llvm;
2162
2163 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2164 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2166 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2167 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2169 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2170 {
2171 RecordData::value_type Record[] = {
2172 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2173 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
2174 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2175 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2176 bytes(SLocEntryOffsets));
2177 }
2178 // Write the source location entry preloads array, telling the AST
2179 // reader which source locations entries it should load eagerly.
2180 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2181
2182 // Write the line table. It depends on remapping working, so it must come
2183 // after the source location offsets.
2184 if (SourceMgr.hasLineTable()) {
2185 LineTableInfo &LineTable = SourceMgr.getLineTable();
2186
2187 Record.clear();
2188
2189 // Emit the needed file names.
2190 llvm::DenseMap<int, int> FilenameMap;
2191 FilenameMap[-1] = -1; // For unspecified filenames.
2192 for (const auto &L : LineTable) {
2193 if (L.first.ID < 0)
2194 continue;
2195 for (auto &LE : L.second) {
2196 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2197 FilenameMap.size() - 1)).second)
2198 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2199 }
2200 }
2201 Record.push_back(0);
2202
2203 // Emit the line entries
2204 for (const auto &L : LineTable) {
2205 // Only emit entries for local files.
2206 if (L.first.ID < 0)
2207 continue;
2208
2209 // Emit the file ID
2210 Record.push_back(L.first.ID);
2211
2212 // Emit the line entries
2213 Record.push_back(L.second.size());
2214 for (const auto &LE : L.second) {
2215 Record.push_back(LE.FileOffset);
2216 Record.push_back(LE.LineNo);
2217 Record.push_back(FilenameMap[LE.FilenameID]);
2218 Record.push_back((unsigned)LE.FileKind);
2219 Record.push_back(LE.IncludeOffset);
2220 }
2221 }
2222
2223 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2224 }
2225}
2226
2227//===----------------------------------------------------------------------===//
2228// Preprocessor Serialization
2229//===----------------------------------------------------------------------===//
2230
2231static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2232 const Preprocessor &PP) {
2233 if (MacroInfo *MI = MD->getMacroInfo())
2234 if (MI->isBuiltinMacro())
2235 return true;
2236
2237 if (IsModule) {
2238 SourceLocation Loc = MD->getLocation();
2239 if (Loc.isInvalid())
2240 return true;
2241 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2242 return true;
2243 }
2244
2245 return false;
2246}
2247
2248void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) {
2249 using namespace llvm::support;
2250
2251 const Preprocessor::IncludedFilesSet &IncludedFiles = PP.getIncludedFiles();
2252
2253 std::vector<uint32_t> IncludedInputFileIDs;
2254 IncludedInputFileIDs.reserve(IncludedFiles.size());
2255
2256 for (const FileEntry *File : IncludedFiles) {
2257 auto InputFileIt = InputFileIDs.find(File);
2258 if (InputFileIt == InputFileIDs.end())
2259 continue;
2260 IncludedInputFileIDs.push_back(InputFileIt->second);
2261 }
2262
2263 llvm::sort(IncludedInputFileIDs);
2264
2265 endian::Writer LE(Out, little);
2266 LE.write<uint32_t>(IncludedInputFileIDs.size());
2267 for (uint32_t ID : IncludedInputFileIDs)
2268 LE.write<uint32_t>(ID);
2269}
2270
2271/// Writes the block containing the serialized form of the
2272/// preprocessor.
2273void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2274 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2275
2276 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2277 if (PPRec)
2278 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2279
2280 RecordData Record;
2281 RecordData ModuleMacroRecord;
2282
2283 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2284 if (PP.getCounterValue() != 0) {
2285 RecordData::value_type Record[] = {PP.getCounterValue()};
2286 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2287 }
2288
2289 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2290 // replayed when the preamble terminates into the main file.
2291 SourceLocation AssumeNonNullLoc =
2292 PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2293 if (AssumeNonNullLoc.isValid()) {
2294 assert(PP.isRecordingPreamble())(static_cast <bool> (PP.isRecordingPreamble()) ? void (
0) : __assert_fail ("PP.isRecordingPreamble()", "clang/lib/Serialization/ASTWriter.cpp"
, 2294, __extension__ __PRETTY_FUNCTION__))
;
2295 AddSourceLocation(AssumeNonNullLoc, Record);
2296 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2297 Record.clear();
2298 }
2299
2300 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2301 assert(!IsModule)(static_cast <bool> (!IsModule) ? void (0) : __assert_fail
("!IsModule", "clang/lib/Serialization/ASTWriter.cpp", 2301,
__extension__ __PRETTY_FUNCTION__))
;
2302 auto SkipInfo = PP.getPreambleSkipInfo();
2303 if (SkipInfo) {
2304 Record.push_back(true);
2305 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2306 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2307 Record.push_back(SkipInfo->FoundNonSkipPortion);
2308 Record.push_back(SkipInfo->FoundElse);
2309 AddSourceLocation(SkipInfo->ElseLoc, Record);
2310 } else {
2311 Record.push_back(false);
2312 }
2313 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2314 AddSourceLocation(Cond.IfLoc, Record);
2315 Record.push_back(Cond.WasSkipping);
2316 Record.push_back(Cond.FoundNonSkip);
2317 Record.push_back(Cond.FoundElse);
2318 }
2319 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2320 Record.clear();
2321 }
2322
2323 // Enter the preprocessor block.
2324 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2325
2326 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2327 // FIXME: Include a location for the use, and say which one was used.
2328 if (PP.SawDateOrTime())
2329 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2330
2331 // Loop over all the macro directives that are live at the end of the file,
2332 // emitting each to the PP section.
2333
2334 // Construct the list of identifiers with macro directives that need to be
2335 // serialized.
2336 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2337 for (auto &Id : PP.getIdentifierTable())
2338 if (Id.second->hadMacroDefinition() &&
2339 (!Id.second->isFromAST() ||
2340 Id.second->hasChangedSinceDeserialization()))
2341 MacroIdentifiers.push_back(Id.second);
2342 // Sort the set of macro definitions that need to be serialized by the
2343 // name of the macro, to provide a stable ordering.
2344 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2345
2346 // Emit the macro directives as a list and associate the offset with the
2347 // identifier they belong to.
2348 for (const IdentifierInfo *Name : MacroIdentifiers) {
2349 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2350 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2351 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large")(static_cast <bool> ((StartOffset >> 32) == 0 &&
"Macro identifiers offset too large") ? void (0) : __assert_fail
("(StartOffset >> 32) == 0 && \"Macro identifiers offset too large\""
, "clang/lib/Serialization/ASTWriter.cpp", 2351, __extension__
__PRETTY_FUNCTION__))
;
2352
2353 // Write out any exported module macros.
2354 bool EmittedModuleMacros = false;
2355 // C+=20 Header Units are compiled module interfaces, but they preserve
2356 // macros that are live (i.e. have a defined value) at the end of the
2357 // compilation. So when writing a header unit, we preserve only the final
2358 // value of each macro (and discard any that are undefined). Header units
2359 // do not have sub-modules (although they might import other header units).
2360 // PCH files, conversely, retain the history of each macro's define/undef
2361 // and of leaf macros in sub modules.
2362 if (IsModule && WritingModule->isHeaderUnit()) {
2363 // This is for the main TU when it is a C++20 header unit.
2364 // We preserve the final state of defined macros, and we do not emit ones
2365 // that are undefined.
2366 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2367 MD->getKind() == MacroDirective::MD_Undefine)
2368 continue;
2369 AddSourceLocation(MD->getLocation(), Record);
2370 Record.push_back(MD->getKind());
2371 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2372 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2373 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2374 Record.push_back(VisMD->isPublic());
2375 }
2376 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2377 ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2378 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2379 ModuleMacroRecord.clear();
2380 EmittedModuleMacros = true;
2381 } else {
2382 // Emit the macro directives in reverse source order.
2383 for (; MD; MD = MD->getPrevious()) {
2384 // Once we hit an ignored macro, we're done: the rest of the chain
2385 // will all be ignored macros.
2386 if (shouldIgnoreMacro(MD, IsModule, PP))
2387 break;
2388 AddSourceLocation(MD->getLocation(), Record);
2389 Record.push_back(MD->getKind());
2390 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2391 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2392 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2393 Record.push_back(VisMD->isPublic());
2394 }
2395 }
2396
2397 // We write out exported module macros for PCH as well.
2398 auto Leafs = PP.getLeafModuleMacros(Name);
2399 SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end());
2400 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2401 while (!Worklist.empty()) {
2402 auto *Macro = Worklist.pop_back_val();
2403
2404 // Emit a record indicating this submodule exports this macro.
2405 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2406 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2407 for (auto *M : Macro->overrides())
2408 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2409
2410 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2411 ModuleMacroRecord.clear();
2412
2413 // Enqueue overridden macros once we've visited all their ancestors.
2414 for (auto *M : Macro->overrides())
2415 if (++Visits[M] == M->getNumOverridingMacros())
2416 Worklist.push_back(M);
2417
2418 EmittedModuleMacros = true;
2419 }
2420 }
2421 if (Record.empty() && !EmittedModuleMacros)
2422 continue;
2423
2424 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2425 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2426 Record.clear();
2427 }
2428
2429 /// Offsets of each of the macros into the bitstream, indexed by
2430 /// the local macro ID
2431 ///
2432 /// For each identifier that is associated with a macro, this map
2433 /// provides the offset into the bitstream where that macro is
2434 /// defined.
2435 std::vector<uint32_t> MacroOffsets;
2436
2437 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2438 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2439 MacroInfo *MI = MacroInfosToEmit[I].MI;
2440 MacroID ID = MacroInfosToEmit[I].ID;
2441
2442 if (ID < FirstMacroID) {
2443 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?")(static_cast <bool> (0 && "Loaded MacroInfo entered MacroInfosToEmit ?"
) ? void (0) : __assert_fail ("0 && \"Loaded MacroInfo entered MacroInfosToEmit ?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2443, __extension__
__PRETTY_FUNCTION__))
;
2444 continue;
2445 }
2446
2447 // Record the local offset of this macro.
2448 unsigned Index = ID - FirstMacroID;
2449 if (Index >= MacroOffsets.size())
2450 MacroOffsets.resize(Index + 1);
2451
2452 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2453 assert((Offset >> 32) == 0 && "Macro offset too large")(static_cast <bool> ((Offset >> 32) == 0 &&
"Macro offset too large") ? void (0) : __assert_fail ("(Offset >> 32) == 0 && \"Macro offset too large\""
, "clang/lib/Serialization/ASTWriter.cpp", 2453, __extension__
__PRETTY_FUNCTION__))
;
2454 MacroOffsets[Index] = Offset;
2455
2456 AddIdentifierRef(Name, Record);
2457 AddSourceLocation(MI->getDefinitionLoc(), Record);
2458 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2459 Record.push_back(MI->isUsed());
2460 Record.push_back(MI->isUsedForHeaderGuard());
2461 Record.push_back(MI->getNumTokens());
2462 unsigned Code;
2463 if (MI->isObjectLike()) {
2464 Code = PP_MACRO_OBJECT_LIKE;
2465 } else {
2466 Code = PP_MACRO_FUNCTION_LIKE;
2467
2468 Record.push_back(MI->isC99Varargs());
2469 Record.push_back(MI->isGNUVarargs());
2470 Record.push_back(MI->hasCommaPasting());
2471 Record.push_back(MI->getNumParams());
2472 for (const IdentifierInfo *Param : MI->params())
2473 AddIdentifierRef(Param, Record);
2474 }
2475
2476 // If we have a detailed preprocessing record, record the macro definition
2477 // ID that corresponds to this macro.
2478 if (PPRec)
2479 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2480
2481 Stream.EmitRecord(Code, Record);
2482 Record.clear();
2483
2484 // Emit the tokens array.
2485 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2486 // Note that we know that the preprocessor does not have any annotation
2487 // tokens in it because they are created by the parser, and thus can't
2488 // be in a macro definition.
2489 const Token &Tok = MI->getReplacementToken(TokNo);
2490 AddToken(Tok, Record);
2491 Stream.EmitRecord(PP_TOKEN, Record);
2492 Record.clear();
2493 }
2494 ++NumMacros;
2495 }
2496
2497 Stream.ExitBlock();
2498
2499 // Write the offsets table for macro IDs.
2500 using namespace llvm;
2501
2502 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2503 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2504 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2506 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2508
2509 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2510 {
2511 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2512 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2513 MacroOffsetsBase - ASTBlockStartOffset};
2514 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2515 }
2516
2517 {
2518 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2519 Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES));
2520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2521 unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2522
2523 SmallString<2048> Buffer;
2524 raw_svector_ostream Out(Buffer);
2525 writeIncludedFiles(Out, PP);
2526 RecordData::value_type Record[] = {PP_INCLUDED_FILES};
2527 Stream.EmitRecordWithBlob(IncludedFilesAbbrev, Record, Buffer.data(),
2528 Buffer.size());
2529 }
2530}
2531
2532void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2533 uint64_t MacroOffsetsBase) {
2534 if (PPRec.local_begin() == PPRec.local_end())
2535 return;
2536
2537 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2538
2539 // Enter the preprocessor block.
2540 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2541
2542 // If the preprocessor has a preprocessing record, emit it.
2543 unsigned NumPreprocessingRecords = 0;
2544 using namespace llvm;
2545
2546 // Set up the abbreviation for
2547 unsigned InclusionAbbrev = 0;
2548 {
2549 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2550 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2551 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2556 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2557 }
2558
2559 unsigned FirstPreprocessorEntityID
2560 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2561 + NUM_PREDEF_PP_ENTITY_IDS;
2562 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2563 RecordData Record;
2564 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2565 EEnd = PPRec.local_end();
2566 E != EEnd;
2567 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2568 Record.clear();
2569
2570 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2571 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large")(static_cast <bool> ((Offset >> 32) == 0 &&
"Preprocessed entity offset too large") ? void (0) : __assert_fail
("(Offset >> 32) == 0 && \"Preprocessed entity offset too large\""
, "clang/lib/Serialization/ASTWriter.cpp", 2571, __extension__
__PRETTY_FUNCTION__))
;
2572 PreprocessedEntityOffsets.push_back(
2573 PPEntityOffset((*E)->getSourceRange(), Offset));
2574
2575 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2576 // Record this macro definition's ID.
2577 MacroDefinitions[MD] = NextPreprocessorEntityID;
2578
2579 AddIdentifierRef(MD->getName(), Record);
2580 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2581 continue;
2582 }
2583
2584 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2585 Record.push_back(ME->isBuiltinMacro());
2586 if (ME->isBuiltinMacro())
2587 AddIdentifierRef(ME->getName(), Record);
2588 else
2589 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2590 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2591 continue;
2592 }
2593
2594 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2595 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2596 Record.push_back(ID->getFileName().size());
2597 Record.push_back(ID->wasInQuotes());
2598 Record.push_back(static_cast<unsigned>(ID->getKind()));
2599 Record.push_back(ID->importedModule());
2600 SmallString<64> Buffer;
2601 Buffer += ID->getFileName();
2602 // Check that the FileEntry is not null because it was not resolved and
2603 // we create a PCH even with compiler errors.
2604 if (ID->getFile())
2605 Buffer += ID->getFile()->getName();
2606 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2607 continue;
2608 }
2609
2610 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter")::llvm::llvm_unreachable_internal("Unhandled PreprocessedEntity in ASTWriter"
, "clang/lib/Serialization/ASTWriter.cpp", 2610)
;
2611 }
2612 Stream.ExitBlock();
2613
2614 // Write the offsets table for the preprocessing record.
2615 if (NumPreprocessingRecords > 0) {
2616 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords)(static_cast <bool> (PreprocessedEntityOffsets.size() ==
NumPreprocessingRecords) ? void (0) : __assert_fail ("PreprocessedEntityOffsets.size() == NumPreprocessingRecords"
, "clang/lib/Serialization/ASTWriter.cpp", 2616, __extension__
__PRETTY_FUNCTION__))
;
2617
2618 // Write the offsets table for identifier IDs.
2619 using namespace llvm;
2620
2621 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2622 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2623 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2624 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2625 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2626
2627 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2628 FirstPreprocessorEntityID -
2629 NUM_PREDEF_PP_ENTITY_IDS};
2630 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2631 bytes(PreprocessedEntityOffsets));
2632 }
2633
2634 // Write the skipped region table for the preprocessing record.
2635 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2636 if (SkippedRanges.size() > 0) {
2637 std::vector<PPSkippedRange> SerializedSkippedRanges;
2638 SerializedSkippedRanges.reserve(SkippedRanges.size());
2639 for (auto const& Range : SkippedRanges)
2640 SerializedSkippedRanges.emplace_back(Range);
2641
2642 using namespace llvm;
2643 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2644 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2646 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2647
2648 Record.clear();
2649 Record.push_back(PPD_SKIPPED_RANGES);
2650 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2651 bytes(SerializedSkippedRanges));
2652 }
2653}
2654
2655unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2656 if (!Mod)
2657 return 0;
2658
2659 auto Known = SubmoduleIDs.find(Mod);
2660 if (Known != SubmoduleIDs.end())
2661 return Known->second;
2662
2663 auto *Top = Mod->getTopLevelModule();
2664 if (Top != WritingModule &&
2665 (getLangOpts().CompilingPCH ||
2666 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2667 return 0;
2668
2669 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2670}
2671
2672unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2673 // FIXME: This can easily happen, if we have a reference to a submodule that
2674 // did not result in us loading a module file for that submodule. For
2675 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2676 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2677 assert((ID || !Mod) &&(static_cast <bool> ((ID || !Mod) && "asked for module ID for non-local, non-imported module"
) ? void (0) : __assert_fail ("(ID || !Mod) && \"asked for module ID for non-local, non-imported module\""
, "clang/lib/Serialization/ASTWriter.cpp", 2678, __extension__
__PRETTY_FUNCTION__))
2678 "asked for module ID for non-local, non-imported module")(static_cast <bool> ((ID || !Mod) && "asked for module ID for non-local, non-imported module"
) ? void (0) : __assert_fail ("(ID || !Mod) && \"asked for module ID for non-local, non-imported module\""
, "clang/lib/Serialization/ASTWriter.cpp", 2678, __extension__
__PRETTY_FUNCTION__))
;
2679 return ID;
2680}
2681
2682/// Compute the number of modules within the given tree (including the
2683/// given module).
2684static unsigned getNumberOfModules(Module *Mod) {
2685 unsigned ChildModules = 0;
2686 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2687 Sub != SubEnd; ++Sub)
2688 ChildModules += getNumberOfModules(*Sub);
2689
2690 return ChildModules + 1;
2691}
2692
2693void ASTWriter::WriteSubmodules(Module *WritingModule) {
2694 // Enter the submodule description block.
2695 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2696
2697 // Write the abbreviations needed for the submodules block.
2698 using namespace llvm;
2699
2700 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2701 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
2705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2715 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2716
2717 Abbrev = std::make_shared<BitCodeAbbrev>();
2718 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2720 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2721
2722 Abbrev = std::make_shared<BitCodeAbbrev>();
2723 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2725 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2726
2727 Abbrev = std::make_shared<BitCodeAbbrev>();
2728 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2729 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2730 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2731
2732 Abbrev = std::make_shared<BitCodeAbbrev>();
2733 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2735 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2736
2737 Abbrev = std::make_shared<BitCodeAbbrev>();
2738 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2739 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2740 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2741 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2742
2743 Abbrev = std::make_shared<BitCodeAbbrev>();
2744 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2746 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2747
2748 Abbrev = std::make_shared<BitCodeAbbrev>();
2749 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2751 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2752
2753 Abbrev = std::make_shared<BitCodeAbbrev>();
2754 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2756 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2757
2758 Abbrev = std::make_shared<BitCodeAbbrev>();
2759 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2761 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2762
2763 Abbrev = std::make_shared<BitCodeAbbrev>();
2764 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2767 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2768
2769 Abbrev = std::make_shared<BitCodeAbbrev>();
2770 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2772 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2773
2774 Abbrev = std::make_shared<BitCodeAbbrev>();
2775 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2776 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2778 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2779
2780 Abbrev = std::make_shared<BitCodeAbbrev>();
2781 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2782 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2783 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2784
2785 // Write the submodule metadata block.
2786 RecordData::value_type Record[] = {
2787 getNumberOfModules(WritingModule),
2788 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2789 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2790
2791 // Write all of the submodules.
2792 std::queue<Module *> Q;
2793 Q.push(WritingModule);
2794 while (!Q.empty()) {
2795 Module *Mod = Q.front();
2796 Q.pop();
2797 unsigned ID = getSubmoduleID(Mod);
2798
2799 uint64_t ParentID = 0;
2800 if (Mod->Parent) {
2801 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?")(static_cast <bool> (SubmoduleIDs[Mod->Parent] &&
"Submodule parent not written?") ? void (0) : __assert_fail (
"SubmoduleIDs[Mod->Parent] && \"Submodule parent not written?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2801, __extension__
__PRETTY_FUNCTION__))
;
2802 ParentID = SubmoduleIDs[Mod->Parent];
2803 }
2804
2805 // Emit the definition of the block.
2806 {
2807 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2808 ID,
2809 ParentID,
2810 (RecordData::value_type)Mod->Kind,
2811 Mod->IsFramework,
2812 Mod->IsExplicit,
2813 Mod->IsSystem,
2814 Mod->IsExternC,
2815 Mod->InferSubmodules,
2816 Mod->InferExplicitSubmodules,
2817 Mod->InferExportWildcard,
2818 Mod->ConfigMacrosExhaustive,
2819 Mod->ModuleMapIsPrivate};
2820 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2821 }
2822
2823 // Emit the requirements.
2824 for (const auto &R : Mod->Requirements) {
2825 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2826 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2827 }
2828
2829 // Emit the umbrella header, if there is one.
2830 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2831 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2832 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2833 UmbrellaHeader.NameAsWritten);
2834 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2835 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2836 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2837 UmbrellaDir.NameAsWritten);
2838 }
2839
2840 // Emit the headers.
2841 struct {
2842 unsigned RecordKind;
2843 unsigned Abbrev;
2844 Module::HeaderKind HeaderKind;
2845 } HeaderLists[] = {
2846 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2847 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2848 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2849 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2850 Module::HK_PrivateTextual},
2851 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2852 };
2853 for (auto &HL : HeaderLists) {
2854 RecordData::value_type Record[] = {HL.RecordKind};
2855 for (auto &H : Mod->Headers[HL.HeaderKind])
2856 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2857 }
2858
2859 // Emit the top headers.
2860 {
2861 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2862 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2863 for (auto *H : TopHeaders) {
2864 SmallString<128> HeaderName(H->getName());
2865 PreparePathForOutput(HeaderName);
2866 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
2867 }
2868 }
2869
2870 // Emit the imports.
2871 if (!Mod->Imports.empty()) {
2872 RecordData Record;
2873 for (auto *I : Mod->Imports)
2874 Record.push_back(getSubmoduleID(I));
2875 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2876 }
2877
2878 // Emit the modules affecting compilation that were not imported.
2879 if (!Mod->AffectingModules.empty()) {
2880 RecordData Record;
2881 for (auto *I : Mod->AffectingModules)
2882 Record.push_back(getSubmoduleID(I));
2883 Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
2884 }
2885
2886 // Emit the exports.
2887 if (!Mod->Exports.empty()) {
2888 RecordData Record;
2889 for (const auto &E : Mod->Exports) {
2890 // FIXME: This may fail; we don't require that all exported modules
2891 // are local or imported.
2892 Record.push_back(getSubmoduleID(E.getPointer()));
2893 Record.push_back(E.getInt());
2894 }
2895 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2896 }
2897
2898 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2899 // Might be unnecessary as use declarations are only used to build the
2900 // module itself.
2901
2902 // TODO: Consider serializing undeclared uses of modules.
2903
2904 // Emit the link libraries.
2905 for (const auto &LL : Mod->LinkLibraries) {
2906 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2907 LL.IsFramework};
2908 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2909 }
2910
2911 // Emit the conflicts.
2912 for (const auto &C : Mod->Conflicts) {
2913 // FIXME: This may fail; we don't require that all conflicting modules
2914 // are local or imported.
2915 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2916 getSubmoduleID(C.Other)};
2917 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2918 }
2919
2920 // Emit the configuration macros.
2921 for (const auto &CM : Mod->ConfigMacros) {
2922 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2923 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2924 }
2925
2926 // Emit the initializers, if any.
2927 RecordData Inits;
2928 for (Decl *D : Context->getModuleInitializers(Mod))
2929 Inits.push_back(GetDeclRef(D));
2930 if (!Inits.empty())
2931 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2932
2933 // Emit the name of the re-exported module, if any.
2934 if (!Mod->ExportAsModule.empty()) {
2935 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2936 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2937 }
2938
2939 // Queue up the submodules of this module.
2940 for (auto *M : Mod->submodules())
2941 Q.push(M);
2942 }
2943
2944 Stream.ExitBlock();
2945
2946 assert((NextSubmoduleID - FirstSubmoduleID ==(static_cast <bool> ((NextSubmoduleID - FirstSubmoduleID
== getNumberOfModules(WritingModule)) && "Wrong # of submodules; found a reference to a non-local, "
"non-imported submodule?") ? void (0) : __assert_fail ("(NextSubmoduleID - FirstSubmoduleID == getNumberOfModules(WritingModule)) && \"Wrong # of submodules; found a reference to a non-local, \" \"non-imported submodule?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2949, __extension__
__PRETTY_FUNCTION__))
2947 getNumberOfModules(WritingModule)) &&(static_cast <bool> ((NextSubmoduleID - FirstSubmoduleID
== getNumberOfModules(WritingModule)) && "Wrong # of submodules; found a reference to a non-local, "
"non-imported submodule?") ? void (0) : __assert_fail ("(NextSubmoduleID - FirstSubmoduleID == getNumberOfModules(WritingModule)) && \"Wrong # of submodules; found a reference to a non-local, \" \"non-imported submodule?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2949, __extension__
__PRETTY_FUNCTION__))
2948 "Wrong # of submodules; found a reference to a non-local, "(static_cast <bool> ((NextSubmoduleID - FirstSubmoduleID
== getNumberOfModules(WritingModule)) && "Wrong # of submodules; found a reference to a non-local, "
"non-imported submodule?") ? void (0) : __assert_fail ("(NextSubmoduleID - FirstSubmoduleID == getNumberOfModules(WritingModule)) && \"Wrong # of submodules; found a reference to a non-local, \" \"non-imported submodule?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2949, __extension__
__PRETTY_FUNCTION__))
2949 "non-imported submodule?")(static_cast <bool> ((NextSubmoduleID - FirstSubmoduleID
== getNumberOfModules(WritingModule)) && "Wrong # of submodules; found a reference to a non-local, "
"non-imported submodule?") ? void (0) : __assert_fail ("(NextSubmoduleID - FirstSubmoduleID == getNumberOfModules(WritingModule)) && \"Wrong # of submodules; found a reference to a non-local, \" \"non-imported submodule?\""
, "clang/lib/Serialization/ASTWriter.cpp", 2949, __extension__
__PRETTY_FUNCTION__))
;
2950}
2951
2952void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2953 bool isModule) {
2954 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2955 DiagStateIDMap;
2956 unsigned CurrID = 0;
2957 RecordData Record;
2958
2959 auto EncodeDiagStateFlags =
2960 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2961 unsigned Result = (unsigned)DS->ExtBehavior;
2962 for (unsigned Val :
2963 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2964 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2965 (unsigned)DS->SuppressSystemWarnings})
2966 Result = (Result << 1) | Val;
2967 return Result;
2968 };
2969
2970 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2971 Record.push_back(Flags);
2972
2973 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2974 bool IncludeNonPragmaStates) {
2975 // Ensure that the diagnostic state wasn't modified since it was created.
2976 // We will not correctly round-trip this information otherwise.
2977 assert(Flags == EncodeDiagStateFlags(State) &&(static_cast <bool> (Flags == EncodeDiagStateFlags(State
) && "diag state flags vary in single AST file") ? void
(0) : __assert_fail ("Flags == EncodeDiagStateFlags(State) && \"diag state flags vary in single AST file\""
, "clang/lib/Serialization/ASTWriter.cpp", 2978, __extension__
__PRETTY_FUNCTION__))
2978 "diag state flags vary in single AST file")(static_cast <bool> (Flags == EncodeDiagStateFlags(State
) && "diag state flags vary in single AST file") ? void
(0) : __assert_fail ("Flags == EncodeDiagStateFlags(State) && \"diag state flags vary in single AST file\""
, "clang/lib/Serialization/ASTWriter.cpp", 2978, __extension__
__PRETTY_FUNCTION__))
;
2979
2980 unsigned &DiagStateID = DiagStateIDMap[State];
2981 Record.push_back(DiagStateID);
2982
2983 if (DiagStateID == 0) {
2984 DiagStateID = ++CurrID;
2985
2986 // Add a placeholder for the number of mappings.
2987 auto SizeIdx = Record.size();
2988 Record.emplace_back();
2989 for (const auto &I : *State) {
2990 if (I.second.isPragma() || IncludeNonPragmaStates) {
2991 Record.push_back(I.first);
2992 Record.push_back(I.second.serialize());
2993 }
2994 }
2995 // Update the placeholder.
2996 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
2997 }
2998 };
2999
3000 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3001
3002 // Reserve a spot for the number of locations with state transitions.
3003 auto NumLocationsIdx = Record.size();
3004 Record.emplace_back();
3005
3006 // Emit the state transitions.
3007 unsigned NumLocations = 0;
3008 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3009 if (!FileIDAndFile.first.isValid() ||
3010 !FileIDAndFile.second.HasLocalTransitions)
3011 continue;
3012 ++NumLocations;
3013
3014 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3015 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid")(static_cast <bool> (!Loc.isInvalid() && "start loc for valid FileID is invalid"
) ? void (0) : __assert_fail ("!Loc.isInvalid() && \"start loc for valid FileID is invalid\""
, "clang/lib/Serialization/ASTWriter.cpp", 3015, __extension__
__PRETTY_FUNCTION__))
;
3016 AddSourceLocation(Loc, Record);
3017
3018 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3019 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3020 Record.push_back(StatePoint.Offset);
3021 AddDiagState(StatePoint.State, false);
3022 }
3023 }
3024
3025 // Backpatch the number of locations.
3026 Record[NumLocationsIdx] = NumLocations;
3027
3028 // Emit CurDiagStateLoc. Do it last in order to match source order.
3029 //
3030 // This also protects against a hypothetical corner case with simulating
3031 // -Werror settings for implicit modules in the ASTReader, where reading
3032 // CurDiagState out of context could change whether warning pragmas are
3033 // treated as errors.
3034 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3035 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3036
3037 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3038}
3039
3040//===----------------------------------------------------------------------===//
3041// Type Serialization
3042//===----------------------------------------------------------------------===//
3043
3044/// Write the representation of a type to the AST stream.
3045void ASTWriter::WriteType(QualType T) {
3046 TypeIdx &IdxRef = TypeIdxs[T];
3047 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3048 IdxRef = TypeIdx(NextTypeID++);
3049 TypeIdx Idx = IdxRef;
3050
3051 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST")(static_cast <bool> (Idx.getIndex() >= FirstTypeID &&
"Re-writing a type from a prior AST") ? void (0) : __assert_fail
("Idx.getIndex() >= FirstTypeID && \"Re-writing a type from a prior AST\""
, "clang/lib/Serialization/ASTWriter.cpp", 3051, __extension__
__PRETTY_FUNCTION__))
;
3052
3053 // Emit the type's representation.
3054 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
3055
3056 // Record the offset for this type.
3057 unsigned Index = Idx.getIndex() - FirstTypeID;
3058 if (TypeOffsets.size() == Index)
3059 TypeOffsets.emplace_back(Offset);
3060 else if (TypeOffsets.size() < Index) {
3061 TypeOffsets.resize(Index + 1);
3062 TypeOffsets[Index].setBitOffset(Offset);
3063 } else {
3064 llvm_unreachable("Types emitted in wrong order")::llvm::llvm_unreachable_internal("Types emitted in wrong order"
, "clang/lib/Serialization/ASTWriter.cpp", 3064)
;
3065 }
3066}
3067
3068//===----------------------------------------------------------------------===//
3069// Declaration Serialization
3070//===----------------------------------------------------------------------===//
3071
3072/// Write the block containing all of the declaration IDs
3073/// lexically declared within the given DeclContext.
3074///
3075/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3076/// bitstream, or 0 if no block was written.
3077uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3078 DeclContext *DC) {
3079 if (DC->decls_empty())
3080 return 0;
3081
3082 uint64_t Offset = Stream.GetCurrentBitNo();
3083 SmallVector<uint32_t, 128> KindDeclPairs;
3084 for (const auto *D : DC->decls()) {
3085 KindDeclPairs.push_back(D->getKind());
3086 KindDeclPairs.push_back(GetDeclRef(D));
3087 }
3088
3089 ++NumLexicalDeclContexts;
3090 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3091 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3092 bytes(KindDeclPairs));
3093 return Offset;
3094}
3095
3096void ASTWriter::WriteTypeDeclOffsets() {
3097 using namespace llvm;
3098
3099 // Write the type offsets array
3100 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3101 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3102 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3103 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3104 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3105 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3106 {
3107 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3108 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3109 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3110 }
3111
3112 // Write the declaration offsets array
3113 Abbrev = std::make_shared<BitCodeAbbrev>();
3114 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3115 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3116 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3117 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3118 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3119 {
3120 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3121 FirstDeclID - NUM_PREDEF_DECL_IDS};
3122 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3123 }
3124}
3125
3126void ASTWriter::WriteFileDeclIDsMap() {
3127 using namespace llvm;
3128
3129 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3130 SortedFileDeclIDs.reserve(FileDeclIDs.size());
3131 for (const auto &P : FileDeclIDs)
3132 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3133 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3134
3135 // Join the vectors of DeclIDs from all files.
3136 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3137 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3138 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3139 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3140 llvm::stable_sort(Info.DeclIDs);
3141 for (auto &LocDeclEntry : Info.DeclIDs)
3142 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3143 }
3144
3145 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3146 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3147 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3148 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3149 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3150 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3151 FileGroupedDeclIDs.size()};
3152 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3153}
3154
3155void ASTWriter::WriteComments() {
3156 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3157 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3158 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3159 return;
3160 RecordData Record;
3161 for (const auto &FO : Context->Comments.OrderedComments) {
3162 for (const auto &OC : FO.second) {
3163 const RawComment *I = OC.second;
3164 Record.clear();
3165 AddSourceRange(I->getSourceRange(), Record);
3166 Record.push_back(I->getKind());
3167 Record.push_back(I->isTrailingComment());
3168 Record.push_back(I->isAlmostTrailingComment());
3169 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3170 }
3171 }
3172}
3173
3174//===----------------------------------------------------------------------===//
3175// Global Method Pool and Selector Serialization
3176//===----------------------------------------------------------------------===//
3177
3178namespace {
3179
3180// Trait used for the on-disk hash table used in the method pool.
3181class ASTMethodPoolTrait {
3182 ASTWriter &Writer;
3183
3184public:
3185 using key_type = Selector;
3186 using key_type_ref = key_type;
3187
3188 struct data_type {
3189 SelectorID ID;
3190 ObjCMethodList Instance, Factory;
3191 };
3192 using data_type_ref = const data_type &;
3193
3194 using hash_value_type = unsigned;
3195 using offset_type = unsigned;
3196
3197 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3198
3199 static hash_value_type ComputeHash(Selector Sel) {
3200 return serialization::ComputeHash(Sel);
3201 }
3202
3203 std::pair<unsigned, unsigned>
3204 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3205 data_type_ref Methods) {
3206 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3207 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3208 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3209 Method = Method->getNext())
3210 if (ShouldWriteMethodListNode(Method))
3211 DataLen += 4;
3212 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3213 Method = Method->getNext())
3214 if (ShouldWriteMethodListNode(Method))
3215 DataLen += 4;
3216 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3217 }
3218
3219 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3220 using namespace llvm::support;
3221
3222 endian::Writer LE(Out, little);
3223 uint64_t Start = Out.tell();
3224 assert((Start >> 32) == 0 && "Selector key offset too large")(static_cast <bool> ((Start >> 32) == 0 &&
"Selector key offset too large") ? void (0) : __assert_fail (
"(Start >> 32) == 0 && \"Selector key offset too large\""
, "clang/lib/Serialization/ASTWriter.cpp", 3224, __extension__
__PRETTY_FUNCTION__))
;
3225 Writer.SetSelectorOffset(Sel, Start);
3226 unsigned N = Sel.getNumArgs();
3227 LE.write<uint16_t>(N);
3228 if (N == 0)
3229 N = 1;
3230 for (unsigned I = 0; I != N; ++I)
3231 LE.write<uint32_t>(
3232 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3233 }
3234
3235 void EmitData(raw_ostream& Out, key_type_ref,
3236 data_type_ref Methods, unsigned DataLen) {
3237 using namespace llvm::support;
3238
3239 endian::Writer LE(Out, little);
3240 uint64_t Start = Out.tell(); (void)Start;
3241 LE.write<uint32_t>(Methods.ID);
3242 unsigned NumInstanceMethods = 0;
3243 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3244 Method = Method->getNext())
3245 if (ShouldWriteMethodListNode(Method))
3246 ++NumInstanceMethods;
3247
3248 unsigned NumFactoryMethods = 0;
3249 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3250 Method = Method->getNext())
3251 if (ShouldWriteMethodListNode(Method))
3252 ++NumFactoryMethods;
3253
3254 unsigned InstanceBits = Methods.Instance.getBits();
3255 assert(InstanceBits < 4)(static_cast <bool> (InstanceBits < 4) ? void (0) : __assert_fail
("InstanceBits < 4", "clang/lib/Serialization/ASTWriter.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
;
3256 unsigned InstanceHasMoreThanOneDeclBit =
3257 Methods.Instance.hasMoreThanOneDecl();
3258 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3259 (InstanceHasMoreThanOneDeclBit << 2) |
3260 InstanceBits;
3261 unsigned FactoryBits = Methods.Factory.getBits();
3262 assert(FactoryBits < 4)(static_cast <bool> (FactoryBits < 4) ? void (0) : __assert_fail
("FactoryBits < 4", "clang/lib/Serialization/ASTWriter.cpp"
, 3262, __extension__ __PRETTY_FUNCTION__))
;
3263 unsigned FactoryHasMoreThanOneDeclBit =
3264 Methods.Factory.hasMoreThanOneDecl();
3265 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3266 (FactoryHasMoreThanOneDeclBit << 2) |
3267 FactoryBits;
3268 LE.write<uint16_t>(FullInstanceBits);
3269 LE.write<uint16_t>(FullFactoryBits);
3270 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3271 Method = Method->getNext())
3272 if (ShouldWriteMethodListNode(Method))
3273 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3274 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3275 Method = Method->getNext())
3276 if (ShouldWriteMethodListNode(Method))
3277 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3278
3279 assert(Out.tell() - Start == DataLen && "Data length is wrong")(static_cast <bool> (Out.tell() - Start == DataLen &&
"Data length is wrong") ? void (0) : __assert_fail ("Out.tell() - Start == DataLen && \"Data length is wrong\""
, "clang/lib/Serialization/ASTWriter.cpp", 3279, __extension__
__PRETTY_FUNCTION__))
;
3280 }
3281
3282private:
3283 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3284 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3285 }
3286};
3287
3288} // namespace
3289
3290/// Write ObjC data: selectors and the method pool.
3291///
3292/// The method pool contains both instance and factory methods, stored
3293/// in an on-disk hash table indexed by the selector. The hash table also
3294/// contains an empty entry for every other selector known to Sema.
3295void ASTWriter::WriteSelectors(Sema &SemaRef) {
3296 using namespace llvm;
3297
3298 // Do we have to do anything at all?
3299 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3300 return;
3301 unsigned NumTableEntries = 0;
3302 // Create and write out the blob that contains selectors and the method pool.
3303 {
3304 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3305 ASTMethodPoolTrait Trait(*this);
3306
3307 // Create the on-disk hash table representation. We walk through every
3308 // selector we've seen and look it up in the method pool.
3309 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3310 for (auto &SelectorAndID : SelectorIDs) {
3311 Selector S = SelectorAndID.first;
3312 SelectorID ID = SelectorAndID.second;
3313 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3314 ASTMethodPoolTrait::data_type Data = {
3315 ID,
3316 ObjCMethodList(),
3317 ObjCMethodList()
3318 };
3319 if (F != SemaRef.MethodPool.end()) {
3320 Data.Instance = F->second.first;
3321 Data.Factory = F->second.second;
3322 }
3323 // Only write this selector if it's not in an existing AST or something
3324 // changed.
3325 if (Chain && ID < FirstSelectorID) {
3326 // Selector already exists. Did it change?
3327 bool changed = false;
3328 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3329 M = M->getNext()) {
3330 if (!M->getMethod()->isFromASTFile()) {
3331 changed = true;
3332 Data.Instance = *M;
3333 break;
3334 }
3335 }
3336 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3337 M = M->getNext()) {
3338 if (!M->getMethod()->isFromASTFile()) {
3339 changed = true;
3340 Data.Factory = *M;
3341 break;
3342 }
3343 }
3344 if (!changed)
3345 continue;
3346 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3347 // A new method pool entry.
3348 ++NumTableEntries;
3349 }
3350 Generator.insert(S, Data, Trait);
3351 }
3352
3353 // Create the on-disk hash table in a buffer.
3354 SmallString<4096> MethodPool;
3355 uint32_t BucketOffset;
3356 {
3357 using namespace llvm::support;
3358
3359 ASTMethodPoolTrait Trait(*this);
3360 llvm::raw_svector_ostream Out(MethodPool);
3361 // Make sure that no bucket is at offset 0
3362 endian::write<uint32_t>(Out, 0, little);
3363 BucketOffset = Generator.Emit(Out, Trait);
3364 }
3365
3366 // Create a blob abbreviation
3367 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3368 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3372 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3373
3374 // Write the method pool
3375 {
3376 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3377 NumTableEntries};
3378 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3379 }
3380
3381 // Create a blob abbreviation for the selector table offsets.
3382 Abbrev = std::make_shared<BitCodeAbbrev>();
3383 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3387 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3388
3389 // Write the selector offsets table.
3390 {
3391 RecordData::value_type Record[] = {
3392 SELECTOR_OFFSETS, SelectorOffsets.size(),
3393 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3394 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3395 bytes(SelectorOffsets));
3396 }
3397 }
3398}
3399
3400/// Write the selectors referenced in @selector expression into AST file.
3401void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3402 using namespace llvm;
3403
3404 if (SemaRef.ReferencedSelectors.empty())
3405 return;
3406
3407 RecordData Record;
3408 ASTRecordWriter Writer(*this, Record);
3409
3410 // Note: this writes out all references even for a dependent AST. But it is
3411 // very tricky to fix, and given that @selector shouldn't really appear in
3412 // headers, probably not worth it. It's not a correctness issue.
3413 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3414 Selector Sel = SelectorAndLocation.first;
3415 SourceLocation Loc = SelectorAndLocation.second;
3416 Writer.AddSelectorRef(Sel);
3417 Writer.AddSourceLocation(Loc);
3418 }
3419 Writer.Emit(REFERENCED_SELECTOR_POOL);
3420}
3421
3422//===----------------------------------------------------------------------===//
3423// Identifier Table Serialization
3424//===----------------------------------------------------------------------===//
3425
3426/// Determine the declaration that should be put into the name lookup table to
3427/// represent the given declaration in this module. This is usually D itself,
3428/// but if D was imported and merged into a local declaration, we want the most
3429/// recent local declaration instead. The chosen declaration will be the most
3430/// recent declaration in any module that imports this one.
3431static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3432 NamedDecl *D) {
3433 if (!LangOpts.Modules || !D->isFromASTFile())
3434 return D;
3435
3436 if (Decl *Redecl = D->getPreviousDecl()) {
3437 // For Redeclarable decls, a prior declaration might be local.
3438 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3439 // If we find a local decl, we're done.
3440 if (!Redecl->isFromASTFile()) {
3441 // Exception: in very rare cases (for injected-class-names), not all
3442 // redeclarations are in the same semantic context. Skip ones in a
3443 // different context. They don't go in this lookup table at all.
3444 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3445 D->getDeclContext()->getRedeclContext()))
3446 continue;
3447 return cast<NamedDecl>(Redecl);
3448 }
3449
3450 // If we find a decl from a (chained-)PCH stop since we won't find a
3451 // local one.
3452 if (Redecl->getOwningModuleID() == 0)
3453 break;
3454 }
3455 } else if (Decl *First = D->getCanonicalDecl()) {
3456 // For Mergeable decls, the first decl might be local.
3457 if (!First->isFromASTFile())
3458 return cast<NamedDecl>(First);
3459 }
3460
3461 // All declarations are imported. Our most recent declaration will also be
3462 // the most recent one in anyone who imports us.
3463 return D;
3464}
3465
3466namespace {
3467
3468class ASTIdentifierTableTrait {
3469 ASTWriter &Writer;
3470 Preprocessor &PP;
3471 IdentifierResolver &IdResolver;
3472 bool IsModule;
3473 bool NeedDecls;
3474 ASTWriter::RecordData *InterestingIdentifierOffsets;
3475
3476 /// Determines whether this is an "interesting" identifier that needs a
3477 /// full IdentifierInfo structure written into the hash table. Notably, this
3478 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3479 /// to check that.
3480 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3481 if (MacroOffset || II->isPoisoned() ||
3482 (!IsModule && II->getObjCOrBuiltinID()) ||
3483 II->hasRevertedTokenIDToIdentifier() ||
3484 (NeedDecls && II->getFETokenInfo()))
3485 return true;
3486
3487 return false;
3488 }
3489
3490public:
3491 using key_type = IdentifierInfo *;
3492 using key_type_ref = key_type;
3493
3494 using data_type = IdentID;
3495 using data_type_ref = data_type;
3496
3497 using hash_value_type = unsigned;
3498 using offset_type = unsigned;
3499
3500 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3501 IdentifierResolver &IdResolver, bool IsModule,
3502 ASTWriter::RecordData *InterestingIdentifierOffsets)
3503 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3504 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3505 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3506
3507 bool needDecls() const { return NeedDecls; }
3508
3509 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3510 return llvm::djbHash(II->getName());
3511 }
3512
3513 bool isInterestingIdentifier(const IdentifierInfo *II) {
3514 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3515 return isInterestingIdentifier(II, MacroOffset);
3516 }
3517
3518 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3519 return isInterestingIdentifier(II, 0);
3520 }
3521
3522 std::pair<unsigned, unsigned>
3523 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3524 // Record the location of the identifier data. This is used when generating
3525 // the mapping from persistent IDs to strings.
3526 Writer.SetIdentifierOffset(II, Out.tell());
3527
3528 // Emit the offset of the key/data length information to the interesting
3529 // identifiers table if necessary.
3530 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3531 InterestingIdentifierOffsets->push_back(Out.tell());
3532
3533 unsigned KeyLen = II->getLength() + 1;
3534 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3535 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3536 if (isInterestingIdentifier(II, MacroOffset)) {
3537 DataLen += 2; // 2 bytes for builtin ID
3538 DataLen += 2; // 2 bytes for flags
3539 if (MacroOffset)
3540 DataLen += 4; // MacroDirectives offset.
3541
3542 if (NeedDecls) {
3543 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3544 DEnd = IdResolver.end();
3545 D != DEnd; ++D)
3546 DataLen += 4;
3547 }
3548 }
3549 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3550 }
3551
3552 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3553 unsigned KeyLen) {
3554 Out.write(II->getNameStart(), KeyLen);
3555 }
3556
3557 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3558 IdentID ID, unsigned) {
3559 using namespace llvm::support;
3560
3561 endian::Writer LE(Out, little);
3562
3563 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3564 if (!isInterestingIdentifier(II, MacroOffset)) {
3565 LE.write<uint32_t>(ID << 1);
3566 return;
3567 }
3568
3569 LE.write<uint32_t>((ID << 1) | 0x01);
3570 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3571 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.")(static_cast <bool> ((Bits & 0xffff) == Bits &&
"ObjCOrBuiltinID too big for ASTReader.") ? void (0) : __assert_fail
("(Bits & 0xffff) == Bits && \"ObjCOrBuiltinID too big for ASTReader.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3571, __extension__
__PRETTY_FUNCTION__))
;
3572 LE.write<uint16_t>(Bits);
3573 Bits = 0;
3574 bool HadMacroDefinition = MacroOffset != 0;
3575 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3576 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3577 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3578 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3579 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3580 LE.write<uint16_t>(Bits);
3581
3582 if (HadMacroDefinition)
3583 LE.write<uint32_t>(MacroOffset);
3584
3585 if (NeedDecls) {
3586 // Emit the declaration IDs in reverse order, because the
3587 // IdentifierResolver provides the declarations as they would be
3588 // visible (e.g., the function "stat" would come before the struct
3589 // "stat"), but the ASTReader adds declarations to the end of the list
3590 // (so we need to see the struct "stat" before the function "stat").
3591 // Only emit declarations that aren't from a chained PCH, though.
3592 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3593 IdResolver.end());
3594 for (NamedDecl *D : llvm::reverse(Decls))
3595 LE.write<uint32_t>(
3596 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D)));
3597 }
3598 }
3599};
3600
3601} // namespace
3602
3603/// Write the identifier table into the AST file.
3604///
3605/// The identifier table consists of a blob containing string data
3606/// (the actual identifiers themselves) and a separate "offsets" index
3607/// that maps identifier IDs to locations within the blob.
3608void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3609 IdentifierResolver &IdResolver,
3610 bool IsModule) {
3611 using namespace llvm;
3612
3613 RecordData InterestingIdents;
3614
3615 // Create and write out the blob that contains the identifier
3616 // strings.
3617 {
3618 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3619 ASTIdentifierTableTrait Trait(
3620 *this, PP, IdResolver, IsModule,
3621 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3622
3623 // Look for any identifiers that were named while processing the
3624 // headers, but are otherwise not needed. We add these to the hash
3625 // table to enable checking of the predefines buffer in the case
3626 // where the user adds new macro definitions when building the AST
3627 // file.
3628 SmallVector<const IdentifierInfo *, 128> IIs;
3629 for (const auto &ID : PP.getIdentifierTable())
3630 IIs.push_back(ID.second);
3631 // Sort the identifiers lexicographically before getting them references so
3632 // that their order is stable.
3633 llvm::sort(IIs, llvm::deref<std::less<>>());
3634 for (const IdentifierInfo *II : IIs)
3635 if (Trait.isInterestingNonMacroIdentifier(II))
3636 getIdentifierRef(II);
3637
3638 // Create the on-disk hash table representation. We only store offsets
3639 // for identifiers that appear here for the first time.
3640 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3641 for (auto IdentIDPair : IdentifierIDs) {
3642 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3643 IdentID ID = IdentIDPair.second;
3644 assert(II && "NULL identifier in identifier table")(static_cast <bool> (II && "NULL identifier in identifier table"
) ? void (0) : __assert_fail ("II && \"NULL identifier in identifier table\""
, "clang/lib/Serialization/ASTWriter.cpp", 3644, __extension__
__PRETTY_FUNCTION__))
;
3645 // Write out identifiers if either the ID is local or the identifier has
3646 // changed since it was loaded.
3647 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3648 || II->hasChangedSinceDeserialization() ||
3649 (Trait.needDecls() &&
3650 II->hasFETokenInfoChangedSinceDeserialization()))
3651 Generator.insert(II, ID, Trait);
3652 }
3653
3654 // Create the on-disk hash table in a buffer.
3655 SmallString<4096> IdentifierTable;
3656 uint32_t BucketOffset;
3657 {
3658 using namespace llvm::support;
3659
3660 llvm::raw_svector_ostream Out(IdentifierTable);
3661 // Make sure that no bucket is at offset 0
3662 endian::write<uint32_t>(Out, 0, little);
3663 BucketOffset = Generator.Emit(Out, Trait);
3664 }
3665
3666 // Create a blob abbreviation
3667 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3668 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3671 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3672
3673 // Write the identifier table
3674 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3675 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3676 }
3677
3678 // Write the offsets table for identifier IDs.
3679 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3680 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3684 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3685
3686#ifndef NDEBUG
3687 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3688 assert(IdentifierOffsets[I] && "Missing identifier offset?")(static_cast <bool> (IdentifierOffsets[I] && "Missing identifier offset?"
) ? void (0) : __assert_fail ("IdentifierOffsets[I] && \"Missing identifier offset?\""
, "clang/lib/Serialization/ASTWriter.cpp", 3688, __extension__
__PRETTY_FUNCTION__))
;
3689#endif
3690
3691 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3692 IdentifierOffsets.size(),
3693 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3694 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3695 bytes(IdentifierOffsets));
3696
3697 // In C++, write the list of interesting identifiers (those that are
3698 // defined as macros, poisoned, or similar unusual things).
3699 if (!InterestingIdents.empty())
3700 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3701}
3702
3703//===----------------------------------------------------------------------===//
3704// DeclContext's Name Lookup Table Serialization
3705//===----------------------------------------------------------------------===//
3706
3707namespace {
3708
3709// Trait used for the on-disk hash table used in the method pool.
3710class ASTDeclContextNameLookupTrait {
3711 ASTWriter &Writer;
3712 llvm::SmallVector<DeclID, 64> DeclIDs;
3713
3714public:
3715 using key_type = DeclarationNameKey;
3716 using key_type_ref = key_type;
3717
3718 /// A start and end index into DeclIDs, representing a sequence of decls.
3719 using data_type = std::pair<unsigned, unsigned>;
3720 using data_type_ref = const data_type &;
3721
3722 using hash_value_type = unsigned;
3723 using offset_type = unsigned;
3724
3725 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3726
3727 template<typename Coll>
3728 data_type getData(const Coll &Decls) {
3729 unsigned Start = DeclIDs.size();
3730 for (NamedDecl *D : Decls) {
3731 DeclIDs.push_back(
3732 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3733 }
3734 return std::make_pair(Start, DeclIDs.size());
3735 }
3736
3737 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3738 unsigned Start = DeclIDs.size();
3739 llvm::append_range(DeclIDs, FromReader);
3740 return std::make_pair(Start, DeclIDs.size());
3741 }
3742
3743 static bool EqualKey(key_type_ref a, key_type_ref b) {
3744 return a == b;
3745 }
3746
3747 hash_value_type ComputeHash(DeclarationNameKey Name) {
3748 return Name.getHash();
3749 }
3750
3751 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3752 assert(Writer.hasChain() &&(static_cast <bool> (Writer.hasChain() && "have reference to loaded module file but no chain?"
) ? void (0) : __assert_fail ("Writer.hasChain() && \"have reference to loaded module file but no chain?\""
, "clang/lib/Serialization/ASTWriter.cpp", 3753, __extension__
__PRETTY_FUNCTION__))
3753 "have reference to loaded module file but no chain?")(static_cast <bool> (Writer.hasChain() && "have reference to loaded module file but no chain?"
) ? void (0) : __assert_fail ("Writer.hasChain() && \"have reference to loaded module file but no chain?\""
, "clang/lib/Serialization/ASTWriter.cpp", 3753, __extension__
__PRETTY_FUNCTION__))
;
3754
3755 using namespace llvm::support;
3756
3757 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3758 }
3759
3760 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3761 DeclarationNameKey Name,
3762 data_type_ref Lookup) {
3763 unsigned KeyLen = 1;
3764 switch (Name.getKind()) {
3765 case DeclarationName::Identifier:
3766 case DeclarationName::ObjCZeroArgSelector:
3767 case DeclarationName::ObjCOneArgSelector:
3768 case DeclarationName::ObjCMultiArgSelector:
3769 case DeclarationName::CXXLiteralOperatorName:
3770 case DeclarationName::CXXDeductionGuideName:
3771 KeyLen += 4;
3772 break;
3773 case DeclarationName::CXXOperatorName:
3774 KeyLen += 1;
3775 break;
3776 case DeclarationName::CXXConstructorName:
3777 case DeclarationName::CXXDestructorName:
3778 case DeclarationName::CXXConversionFunctionName:
3779 case DeclarationName::CXXUsingDirective:
3780 break;
3781 }
3782
3783 // 4 bytes for each DeclID.
3784 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3785
3786 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3787 }
3788
3789 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3790 using namespace llvm::support;
3791
3792 endian::Writer LE(Out, little);
3793 LE.write<uint8_t>(Name.getKind());
3794 switch (Name.getKind()) {
3795 case DeclarationName::Identifier:
3796 case DeclarationName::CXXLiteralOperatorName:
3797 case DeclarationName::CXXDeductionGuideName:
3798 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3799 return;
3800 case DeclarationName::ObjCZeroArgSelector:
3801 case DeclarationName::ObjCOneArgSelector:
3802 case DeclarationName::ObjCMultiArgSelector:
3803 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3804 return;
3805 case DeclarationName::CXXOperatorName:
3806 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&(static_cast <bool> (Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS
&& "Invalid operator?") ? void (0) : __assert_fail (
"Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && \"Invalid operator?\""
, "clang/lib/Serialization/ASTWriter.cpp", 3807, __extension__
__PRETTY_FUNCTION__))
3807 "Invalid operator?")(static_cast <bool> (Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS
&& "Invalid operator?") ? void (0) : __assert_fail (
"Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && \"Invalid operator?\""
, "clang/lib/Serialization/ASTWriter.cpp", 3807, __extension__
__PRETTY_FUNCTION__))
;
3808 LE.write<uint8_t>(Name.getOperatorKind());
3809 return;
3810 case DeclarationName::CXXConstructorName:
3811 case DeclarationName::CXXDestructorName:
3812 case DeclarationName::CXXConversionFunctionName:
3813 case DeclarationName::CXXUsingDirective:
3814 return;
3815 }
3816
3817 llvm_unreachable("Invalid name kind?")::llvm::llvm_unreachable_internal("Invalid name kind?", "clang/lib/Serialization/ASTWriter.cpp"
, 3817)
;
3818 }
3819
3820 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3821 unsigned DataLen) {
3822 using namespace llvm::support;
3823
3824 endian::Writer LE(Out, little);
3825 uint64_t Start = Out.tell(); (void)Start;
3826 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3827 LE.write<uint32_t>(DeclIDs[I]);
3828 assert(Out.tell() - Start == DataLen && "Data length is wrong")(static_cast <bool> (Out.tell() - Start == DataLen &&
"Data length is wrong") ? void (0) : __assert_fail ("Out.tell() - Start == DataLen && \"Data length is wrong\""
, "clang/lib/Serialization/ASTWriter.cpp", 3828, __extension__
__PRETTY_FUNCTION__))
;
3829 }
3830};
3831
3832} // namespace
3833
3834bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3835 DeclContext *DC) {
3836 return Result.hasExternalDecls() &&
3837 DC->hasNeedToReconcileExternalVisibleStorage();
3838}
3839
3840bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3841 DeclContext *DC) {
3842 for (auto *D : Result.getLookupResult())
3843 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3844 return false;
3845
3846 return true;
3847}
3848
3849void
3850ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3851 llvm::SmallVectorImpl<char> &LookupTable) {
3852 assert(!ConstDC->hasLazyLocalLexicalLookups() &&(static_cast <bool> (!ConstDC->hasLazyLocalLexicalLookups
() && !ConstDC->hasLazyExternalLexicalLookups() &&
"must call buildLookups first") ? void (0) : __assert_fail (
"!ConstDC->hasLazyLocalLexicalLookups() && !ConstDC->hasLazyExternalLexicalLookups() && \"must call buildLookups first\""
, "clang/lib/Serialization/ASTWriter.cpp", 3854, __extension__
__PRETTY_FUNCTION__))
3853 !ConstDC->hasLazyExternalLexicalLookups() &&(static_cast <bool> (!ConstDC->hasLazyLocalLexicalLookups
() && !ConstDC->hasLazyExternalLexicalLookups() &&
"must call buildLookups first") ? void (0) : __assert_fail (
"!ConstDC->hasLazyLocalLexicalLookups() && !ConstDC->hasLazyExternalLexicalLookups() && \"must call buildLookups first\""
, "clang/lib/Serialization/ASTWriter.cpp", 3854, __extension__
__PRETTY_FUNCTION__))
3854 "must call buildLookups first")(static_cast <bool> (!ConstDC->hasLazyLocalLexicalLookups
() && !ConstDC->hasLazyExternalLexicalLookups() &&
"must call buildLookups first") ? void (0) : __assert_fail (
"!ConstDC->hasLazyLocalLexicalLookups() && !ConstDC->hasLazyExternalLexicalLookups() && \"must call buildLookups first\""
, "clang/lib/Serialization/ASTWriter.cpp", 3854, __extension__
__PRETTY_FUNCTION__))
;
3855
3856 // FIXME: We need to build the lookups table, which is logically const.
3857 auto *DC = const_cast<DeclContext*>(ConstDC);
3858 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table")(static_cast <bool> (DC == DC->getPrimaryContext() &&
"only primary DC has lookup table") ? void (0) : __assert_fail
("DC == DC->getPrimaryContext() && \"only primary DC has lookup table\""
, "clang/lib/Serialization/ASTWriter.cpp", 3858, __extension__
__PRETTY_FUNCTION__))
;
3859
3860 // Create the on-disk hash table representation.
3861 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3862 ASTDeclContextNameLookupTrait> Generator;
3863 ASTDeclContextNameLookupTrait Trait(*this);
3864
3865 // The first step is to collect the declaration names which we need to
3866 // serialize into the name lookup table, and to collect them in a stable
3867 // order.
3868 SmallVector<DeclarationName, 16> Names;
3869
3870 // We also build up small sets of the constructor and conversion function
3871 // names which are visible.
3872 llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3873
3874 for (auto &Lookup : *DC->buildLookup()) {
3875 auto &Name = Lookup.first;
3876 auto &Result = Lookup.second;
3877
3878 // If there are no local declarations in our lookup result, we
3879 // don't need to write an entry for the name at all. If we can't
3880 // write out a lookup set without performing more deserialization,
3881 // just skip this entry.
3882 if (isLookupResultExternal(Result, DC) &&
3883 isLookupResultEntirelyExternal(Result, DC))
3884 continue;
3885
3886 // We also skip empty results. If any of the results could be external and
3887 // the currently available results are empty, then all of the results are
3888 // external and we skip it above. So the only way we get here with an empty
3889 // results is when no results could have been external *and* we have
3890 // external results.
3891 //
3892 // FIXME: While we might want to start emitting on-disk entries for negative
3893 // lookups into a decl context as an optimization, today we *have* to skip
3894 // them because there are names with empty lookup results in decl contexts
3895 // which we can't emit in any stable ordering: we lookup constructors and
3896 // conversion functions in the enclosing namespace scope creating empty
3897 // results for them. This in almost certainly a bug in Clang's name lookup,
3898 // but that is likely to be hard or impossible to fix and so we tolerate it
3899 // here by omitting lookups with empty results.
3900 if (Lookup.second.getLookupResult().empty())
3901 continue;
3902
3903 switch (Lookup.first.getNameKind()) {
3904 default:
3905 Names.push_back(Lookup.first);
3906 break;
3907
3908 case DeclarationName::CXXConstructorName:
3909 assert(isa<CXXRecordDecl>(DC) &&(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Cannot have a constructor name outside of a class!") ? void
(0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Cannot have a constructor name outside of a class!\""
, "clang/lib/Serialization/ASTWriter.cpp", 3910, __extension__
__PRETTY_FUNCTION__))
3910 "Cannot have a constructor name outside of a class!")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Cannot have a constructor name outside of a class!") ? void
(0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Cannot have a constructor name outside of a class!\""
, "clang/lib/Serialization/ASTWriter.cpp", 3910, __extension__
__PRETTY_FUNCTION__))
;
3911 ConstructorNameSet.insert(Name);
3912 break;
3913
3914 case DeclarationName::CXXConversionFunctionName:
3915 assert(isa<CXXRecordDecl>(DC) &&(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Cannot have a conversion function name outside of a class!"
) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Cannot have a conversion function name outside of a class!\""
, "clang/lib/Serialization/ASTWriter.cpp", 3916, __extension__
__PRETTY_FUNCTION__))
3916 "Cannot have a conversion function name outside of a class!")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Cannot have a conversion function name outside of a class!"
) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Cannot have a conversion function name outside of a class!\""
, "clang/lib/Serialization/ASTWriter.cpp", 3916, __extension__
__PRETTY_FUNCTION__))
;
3917 ConversionNameSet.insert(Name);
3918 break;
3919 }
3920 }
3921
3922 // Sort the names into a stable order.
3923 llvm::sort(Names);
3924
3925 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3926 // We need to establish an ordering of constructor and conversion function
3927 // names, and they don't have an intrinsic ordering.
3928
3929 // First we try the easy case by forming the current context's constructor
3930 // name and adding that name first. This is a very useful optimization to
3931 // avoid walking the lexical declarations in many cases, and it also
3932 // handles the only case where a constructor name can come from some other
3933 // lexical context -- when that name is an implicit constructor merged from
3934 // another declaration in the redecl chain. Any non-implicit constructor or
3935 // conversion function which doesn't occur in all the lexical contexts
3936 // would be an ODR violation.
3937 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3938 Context->getCanonicalType(Context->getRecordType(D)));
3939 if (ConstructorNameSet.erase(ImplicitCtorName))
3940 Names.push_back(ImplicitCtorName);
3941
3942 // If we still have constructors or conversion functions, we walk all the
3943 // names in the decl and add the constructors and conversion functions
3944 // which are visible in the order they lexically occur within the context.
3945 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3946 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3947 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3948 auto Name = ChildND->getDeclName();
3949 switch (Name.getNameKind()) {
3950 default:
3951 continue;
3952
3953 case DeclarationName::CXXConstructorName:
3954 if (ConstructorNameSet.erase(Name))
3955 Names.push_back(Name);
3956 break;
3957
3958 case DeclarationName::CXXConversionFunctionName:
3959 if (ConversionNameSet.erase(Name))
3960 Names.push_back(Name);
3961 break;
3962 }
3963
3964 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3965 break;
3966 }
3967
3968 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "(static_cast <bool> (ConstructorNameSet.empty() &&
"Failed to find all of the visible " "constructors by walking all the "
"lexical members of the context.") ? void (0) : __assert_fail
("ConstructorNameSet.empty() && \"Failed to find all of the visible \" \"constructors by walking all the \" \"lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3970, __extension__
__PRETTY_FUNCTION__))
3969 "constructors by walking all the "(static_cast <bool> (ConstructorNameSet.empty() &&
"Failed to find all of the visible " "constructors by walking all the "
"lexical members of the context.") ? void (0) : __assert_fail
("ConstructorNameSet.empty() && \"Failed to find all of the visible \" \"constructors by walking all the \" \"lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3970, __extension__
__PRETTY_FUNCTION__))
3970 "lexical members of the context.")(static_cast <bool> (ConstructorNameSet.empty() &&
"Failed to find all of the visible " "constructors by walking all the "
"lexical members of the context.") ? void (0) : __assert_fail
("ConstructorNameSet.empty() && \"Failed to find all of the visible \" \"constructors by walking all the \" \"lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3970, __extension__
__PRETTY_FUNCTION__))
;
3971 assert(ConversionNameSet.empty() && "Failed to find all of the visible "(static_cast <bool> (ConversionNameSet.empty() &&
"Failed to find all of the visible " "conversion functions by walking all "
"the lexical members of the context.") ? void (0) : __assert_fail
("ConversionNameSet.empty() && \"Failed to find all of the visible \" \"conversion functions by walking all \" \"the lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3973, __extension__
__PRETTY_FUNCTION__))
3972 "conversion functions by walking all "(static_cast <bool> (ConversionNameSet.empty() &&
"Failed to find all of the visible " "conversion functions by walking all "
"the lexical members of the context.") ? void (0) : __assert_fail
("ConversionNameSet.empty() && \"Failed to find all of the visible \" \"conversion functions by walking all \" \"the lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3973, __extension__
__PRETTY_FUNCTION__))
3973 "the lexical members of the context.")(static_cast <bool> (ConversionNameSet.empty() &&
"Failed to find all of the visible " "conversion functions by walking all "
"the lexical members of the context.") ? void (0) : __assert_fail
("ConversionNameSet.empty() && \"Failed to find all of the visible \" \"conversion functions by walking all \" \"the lexical members of the context.\""
, "clang/lib/Serialization/ASTWriter.cpp", 3973, __extension__
__PRETTY_FUNCTION__))
;
3974 }
3975
3976 // Next we need to do a lookup with each name into this decl context to fully
3977 // populate any results from external sources. We don't actually use the
3978 // results of these lookups because we only want to use the results after all
3979 // results have been loaded and the pointers into them will be stable.
3980 for (auto &Name : Names)
3981 DC->lookup(Name);
3982
3983 // Now we need to insert the results for each name into the hash table. For
3984 // constructor names and conversion function names, we actually need to merge
3985 // all of the results for them into one list of results each and insert
3986 // those.
3987 SmallVector<NamedDecl *, 8> ConstructorDecls;
3988 SmallVector<NamedDecl *, 8> ConversionDecls;
3989
3990 // Now loop over the names, either inserting them or appending for the two
3991 // special cases.
3992 for (auto &Name : Names) {
3993 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3994
3995 switch (Name.getNameKind()) {
3996 default:
3997 Generator.insert(Name, Trait.getData(Result), Trait);
3998 break;
3999
4000 case DeclarationName::CXXConstructorName:
4001 ConstructorDecls.append(Result.begin(), Result.end());
4002 break;
4003
4004 case DeclarationName::CXXConversionFunctionName:
4005 ConversionDecls.append(Result.begin(), Result.end());
4006 break;
4007 }
4008 }
4009
4010 // Handle our two special cases if we ended up having any. We arbitrarily use
4011 // the first declaration's name here because the name itself isn't part of
4012 // the key, only the kind of name is used.
4013 if (!ConstructorDecls.empty())
4014 Generator.insert(ConstructorDecls.front()->getDeclName(),
4015 Trait.getData(ConstructorDecls), Trait);
4016 if (!ConversionDecls.empty())
4017 Generator.insert(ConversionDecls.front()->getDeclName(),
4018 Trait.getData(ConversionDecls), Trait);
4019
4020 // Create the on-disk hash table. Also emit the existing imported and
4021 // merged table if there is one.
4022 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4023 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4024}
4025
4026/// Write the block containing all of the declaration IDs
4027/// visible from the given DeclContext.
4028///
4029/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4030/// bitstream, or 0 if no block was written.
4031uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4032 DeclContext *DC) {
4033 // If we imported a key declaration of this namespace, write the visible
4034 // lookup results as an update record for it rather than including them
4035 // on this declaration. We will only look at key declarations on reload.
4036 if (isa<NamespaceDecl>(DC) && Chain &&
4037 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4038 // Only do this once, for the first local declaration of the namespace.
4039 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4040 Prev = Prev->getPreviousDecl())
4041 if (!Prev->isFromASTFile())
4042 return 0;
4043
4044 // Note that we need to emit an update record for the primary context.
4045 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4046
4047 // Make sure all visible decls are written. They will be recorded later. We
4048 // do this using a side data structure so we can sort the names into
4049 // a deterministic order.
4050 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4051 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4052 LookupResults;
4053 if (Map) {
4054 LookupResults.reserve(Map->size());
4055 for (auto &Entry : *Map)
4056 LookupResults.push_back(
4057 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4058 }
4059
4060 llvm::sort(LookupResults, llvm::less_first());
4061 for (auto &NameAndResult : LookupResults) {
4062 DeclarationName Name = NameAndResult.first;
4063 DeclContext::lookup_result Result = NameAndResult.second;
4064 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4065 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4066 // We have to work around a name lookup bug here where negative lookup
4067 // results for these names get cached in namespace lookup tables (these
4068 // names should never be looked up in a namespace).
4069 assert(Result.empty() && "Cannot have a constructor or conversion "(static_cast <bool> (Result.empty() && "Cannot have a constructor or conversion "
"function name in a namespace!") ? void (0) : __assert_fail (
"Result.empty() && \"Cannot have a constructor or conversion \" \"function name in a namespace!\""
, "clang/lib/Serialization/ASTWriter.cpp", 4070, __extension__
__PRETTY_FUNCTION__))
4070 "function name in a namespace!")(static_cast <bool> (Result.empty() && "Cannot have a constructor or conversion "
"function name in a namespace!") ? void (0) : __assert_fail (
"Result.empty() && \"Cannot have a constructor or conversion \" \"function name in a namespace!\""
, "clang/lib/Serialization/ASTWriter.cpp", 4070, __extension__
__PRETTY_FUNCTION__))
;
4071 continue;
4072 }
4073
4074 for (NamedDecl *ND : Result)
4075 if (!ND->isFromASTFile())
4076 GetDeclRef(ND);
4077 }
4078
4079 return 0;
4080 }
4081
4082 if (DC->getPrimaryContext() != DC)
4083 return 0;
4084
4085 // Skip contexts which don't support name lookup.
4086 if (!DC->isLookupContext())
4087 return 0;
4088
4089 // If not in C++, we perform name lookup for the translation unit via the
4090 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4091 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4092 return 0;
4093
4094 // Serialize the contents of the mapping used for lookup. Note that,
4095 // although we have two very different code paths, the serialized
4096 // representation is the same for both cases: a declaration name,
4097 // followed by a size, followed by references to the visible
4098 // declarations that have that name.
4099 uint64_t Offset = Stream.GetCurrentBitNo();
4100 StoredDeclsMap *Map = DC->buildLookup();
4101 if (!Map || Map->empty())
4102 return 0;
4103
4104 // Create the on-disk hash table in a buffer.
4105 SmallString<4096> LookupTable;
4106 GenerateNameLookupTable(DC, LookupTable);
4107
4108 // Write the lookup table
4109 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4110 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4111 LookupTable);
4112 ++NumVisibleDeclContexts;
4113 return Offset;
4114}
4115
4116/// Write an UPDATE_VISIBLE block for the given context.
4117///
4118/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4119/// DeclContext in a dependent AST file. As such, they only exist for the TU
4120/// (in C++), for namespaces, and for classes with forward-declared unscoped
4121/// enumeration members (in C++11).
4122void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4123 StoredDeclsMap *Map = DC->getLookupPtr();
4124 if (!Map || Map->empty())
4125 return;
4126
4127 // Create the on-disk hash table in a buffer.
4128 SmallString<4096> LookupTable;
4129 GenerateNameLookupTable(DC, LookupTable);
4130
4131 // If we're updating a namespace, select a key declaration as the key for the
4132 // update record; those are the only ones that will be checked on reload.
4133 if (isa<NamespaceDecl>(DC))
4134 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4135
4136 // Write the lookup table
4137 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4138 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4139}
4140
4141/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4142void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4143 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4144 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
1
Calling 'BitstreamWriter::EmitRecord'
4145}
4146
4147/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4148void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4149 if (!SemaRef.Context.getLangOpts().OpenCL)
4150 return;
4151
4152 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4153 RecordData Record;
4154 for (const auto &I:Opts.OptMap) {
4155 AddString(I.getKey(), Record);
4156 auto V = I.getValue();
4157 Record.push_back(V.Supported ? 1 : 0);
4158 Record.push_back(V.Enabled ? 1 : 0);
4159 Record.push_back(V.WithPragma ? 1 : 0);
4160 Record.push_back(V.Avail);
4161 Record.push_back(V.Core);
4162 Record.push_back(V.Opt);
4163 }
4164 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4165}
4166void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4167 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4168 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4169 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4170 }
4171}
4172
4173void ASTWriter::WriteObjCCategories() {
4174 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4175 RecordData Categories;
4176
4177 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4178 unsigned Size = 0;
4179 unsigned StartIndex = Categories.size();
4180
4181 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4182
4183 // Allocate space for the size.
4184 Categories.push_back(0);
4185
4186 // Add the categories.
4187 for (ObjCInterfaceDecl::known_categories_iterator
4188 Cat = Class->known_categories_begin(),
4189 CatEnd = Class->known_categories_end();
4190 Cat != CatEnd; ++Cat, ++Size) {
4191 assert(getDeclID(*Cat) != 0 && "Bogus category")(static_cast <bool> (getDeclID(*Cat) != 0 && "Bogus category"
) ? void (0) : __assert_fail ("getDeclID(*Cat) != 0 && \"Bogus category\""
, "clang/lib/Serialization/ASTWriter.cpp", 4191, __extension__
__PRETTY_FUNCTION__))
;
4192 AddDeclRef(*Cat, Categories);
4193 }
4194
4195 // Update the size.
4196 Categories[StartIndex] = Size;
4197
4198 // Record this interface -> category map.
4199 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4200 CategoriesMap.push_back(CatInfo);
4201 }
4202
4203 // Sort the categories map by the definition ID, since the reader will be
4204 // performing binary searches on this information.
4205 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4206
4207 // Emit the categories map.
4208 using namespace llvm;
4209
4210 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4211 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4214 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4215
4216 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4217 Stream.EmitRecordWithBlob(AbbrevID, Record,
4218 reinterpret_cast<char *>(CategoriesMap.data()),
4219 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4220
4221 // Emit the category lists.
4222 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4223}
4224
4225void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4226 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4227
4228 if (LPTMap.empty())
4229 return;
4230
4231 RecordData Record;
4232 for (auto &LPTMapEntry : LPTMap) {
4233 const FunctionDecl *FD = LPTMapEntry.first;
4234 LateParsedTemplate &LPT = *LPTMapEntry.second;
4235 AddDeclRef(FD, Record);
4236 AddDeclRef(LPT.D, Record);
4237 Record.push_back(LPT.Toks.size());
4238
4239 for (const auto &Tok : LPT.Toks) {
4240 AddToken(Tok, Record);
4241 }
4242 }
4243 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4244}
4245
4246/// Write the state of 'pragma clang optimize' at the end of the module.
4247void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4248 RecordData Record;
4249 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4250 AddSourceLocation(PragmaLoc, Record);
4251 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4252}
4253
4254/// Write the state of 'pragma ms_struct' at the end of the module.
4255void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4256 RecordData Record;
4257 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4258 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4259}
4260
4261/// Write the state of 'pragma pointers_to_members' at the end of the
4262//module.
4263void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4264 RecordData Record;
4265 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4266 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4267 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4268}
4269
4270/// Write the state of 'pragma align/pack' at the end of the module.
4271void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4272 // Don't serialize pragma align/pack state for modules, since it should only
4273 // take effect on a per-submodule basis.
4274 if (WritingModule)
4275 return;
4276
4277 RecordData Record;
4278 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4279 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4280 Record.push_back(SemaRef.AlignPackStack.Stack.size());
4281 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4282 AddAlignPackInfo(StackEntry.Value, Record);
4283 AddSourceLocation(StackEntry.PragmaLocation, Record);
4284 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4285 AddString(StackEntry.StackSlotLabel, Record);
4286 }
4287 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4288}
4289
4290/// Write the state of 'pragma float_control' at the end of the module.
4291void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4292 // Don't serialize pragma float_control state for modules,
4293 // since it should only take effect on a per-submodule basis.
4294 if (WritingModule)
4295 return;
4296
4297 RecordData Record;
4298 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4299 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4300 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4301 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4302 Record.push_back(StackEntry.Value.getAsOpaqueInt());
4303 AddSourceLocation(StackEntry.PragmaLocation, Record);
4304 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4305 AddString(StackEntry.StackSlotLabel, Record);
4306 }
4307 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4308}
4309
4310void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4311 ModuleFileExtensionWriter &Writer) {
4312 // Enter the extension block.
4313 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4314
4315 // Emit the metadata record abbreviation.
4316 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4317 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4318 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4319 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4320 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4321 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4322 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4323 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4324
4325 // Emit the metadata record.
4326 RecordData Record;
4327 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4328 Record.push_back(EXTENSION_METADATA);
4329 Record.push_back(Metadata.MajorVersion);
4330 Record.push_back(Metadata.MinorVersion);
4331 Record.push_back(Metadata.BlockName.size());
4332 Record.push_back(Metadata.UserInfo.size());
4333 SmallString<64> Buffer;
4334 Buffer += Metadata.BlockName;
4335 Buffer += Metadata.UserInfo;
4336 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4337
4338 // Emit the contents of the extension block.
4339 Writer.writeExtensionContents(SemaRef, Stream);
4340
4341 // Exit the extension block.
4342 Stream.ExitBlock();
4343}
4344
4345//===----------------------------------------------------------------------===//
4346// General Serialization Routines
4347//===----------------------------------------------------------------------===//
4348
4349void ASTRecordWriter::AddAttr(const Attr *A) {
4350 auto &Record = *this;
4351 // FIXME: Clang can't handle the serialization/deserialization of
4352 // preferred_name properly now. See
4353 // https://github.com/llvm/llvm-project/issues/56490 for example.
4354 if (!A || (isa<PreferredNameAttr>(A) && Writer->isWritingNamedModules()))
4355 return Record.push_back(0);
4356
4357 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4358
4359 Record.AddIdentifierRef(A->getAttrName());
4360 Record.AddIdentifierRef(A->getScopeName());
4361 Record.AddSourceRange(A->getRange());
4362 Record.AddSourceLocation(A->getScopeLoc());
4363 Record.push_back(A->getParsedKind());
4364 Record.push_back(A->getSyntax());
4365 Record.push_back(A->getAttributeSpellingListIndexRaw());
4366
4367#include "clang/Serialization/AttrPCHWrite.inc"
4368}
4369
4370/// Emit the list of attributes to the specified record.
4371void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4372 push_back(Attrs.size());
4373 for (const auto *A : Attrs)
4374 AddAttr(A);
4375}
4376
4377void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4378 AddSourceLocation(Tok.getLocation(), Record);
4379 Record.push_back(Tok.getLength());
4380
4381 // FIXME: When reading literal tokens, reconstruct the literal pointer
4382 // if it is needed.
4383 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4384 // FIXME: Should translate token kind to a stable encoding.
4385 Record.push_back(Tok.getKind());
4386 // FIXME: Should translate token flags to a stable encoding.
4387 Record.push_back(Tok.getFlags());
4388}
4389
4390void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4391 Record.push_back(Str.size());
4392 Record.insert(Record.end(), Str.begin(), Str.end());
4393}
4394
4395bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4396 assert(Context && "should have context when outputting path")(static_cast <bool> (Context && "should have context when outputting path"
) ? void (0) : __assert_fail ("Context && \"should have context when outputting path\""
, "clang/lib/Serialization/ASTWriter.cpp", 4396, __extension__
__PRETTY_FUNCTION__))
;
4397
4398 bool Changed =
4399 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4400
4401 // Remove a prefix to make the path relative, if relevant.
4402 const char *PathBegin = Path.data();
4403 const char *PathPtr =
4404 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4405 if (PathPtr != PathBegin) {
4406 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4407 Changed = true;
4408 }
4409
4410 return Changed;
4411}
4412
4413void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4414 SmallString<128> FilePath(Path);
4415 PreparePathForOutput(FilePath);
4416 AddString(FilePath, Record);
4417}
4418
4419void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4420 StringRef Path) {
4421 SmallString<128> FilePath(Path);
4422 PreparePathForOutput(FilePath);
4423 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4424}
4425
4426void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4427 RecordDataImpl &Record) {
4428 Record.push_back(Version.getMajor());
4429 if (Optional<unsigned> Minor = Version.getMinor())
4430 Record.push_back(*Minor + 1);
4431 else
4432 Record.push_back(0);
4433 if (Optional<unsigned> Subminor = Version.getSubminor())
4434 Record.push_back(*Subminor + 1);
4435 else
4436 Record.push_back(0);
4437}
4438
4439/// Note that the identifier II occurs at the given offset
4440/// within the identifier table.
4441void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4442 IdentID ID = IdentifierIDs[II];
4443 // Only store offsets new to this AST file. Other identifier names are looked
4444 // up earlier in the chain and thus don't need an offset.
4445 if (ID >= FirstIdentID)
4446 IdentifierOffsets[ID - FirstIdentID] = Offset;
4447}
4448
4449/// Note that the selector Sel occurs at the given offset
4450/// within the method pool/selector table.
4451void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4452 unsigned ID = SelectorIDs[Sel];
4453 assert(ID && "Unknown selector")(static_cast <bool> (ID && "Unknown selector") ?
void (0) : __assert_fail ("ID && \"Unknown selector\""
, "clang/lib/Serialization/ASTWriter.cpp", 4453, __extension__
__PRETTY_FUNCTION__))
;
4454 // Don't record offsets for selectors that are also available in a different
4455 // file.
4456 if (ID < FirstSelectorID)
4457 return;
4458 SelectorOffsets[ID - FirstSelectorID] = Offset;
4459}
4460
4461ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4462 SmallVectorImpl<char> &Buffer,
4463 InMemoryModuleCache &ModuleCache,
4464 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4465 bool IncludeTimestamps)
4466 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4467 IncludeTimestamps(IncludeTimestamps) {
4468 for (const auto &Ext : Extensions) {
4469 if (auto Writer = Ext->createExtensionWriter(*this))
4470 ModuleFileExtensionWriters.push_back(std::move(Writer));
4471 }
4472}
4473
4474ASTWriter::~ASTWriter() = default;
4475
4476const LangOptions &ASTWriter::getLangOpts() const {
4477 assert(WritingAST && "can't determine lang opts when not writing AST")(static_cast <bool> (WritingAST && "can't determine lang opts when not writing AST"
) ? void (0) : __assert_fail ("WritingAST && \"can't determine lang opts when not writing AST\""
, "clang/lib/Serialization/ASTWriter.cpp", 4477, __extension__
__PRETTY_FUNCTION__))
;
4478 return Context->getLangOpts();
4479}
4480
4481time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4482 return IncludeTimestamps ? E->getModificationTime() : 0;
4483}
4484
4485ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, StringRef OutputFile,
4486 Module *WritingModule, StringRef isysroot,
4487 bool hasErrors,
4488 bool ShouldCacheASTInMemory) {
4489 WritingAST = true;
4490
4491 ASTHasCompilerErrors = hasErrors;
4492
4493 // Emit the file header.
4494 Stream.Emit((unsigned)'C', 8);
4495 Stream.Emit((unsigned)'P', 8);
4496 Stream.Emit((unsigned)'C', 8);
4497 Stream.Emit((unsigned)'H', 8);
4498
4499 WriteBlockInfoBlock();
4500
4501 Context = &SemaRef.Context;
4502 PP = &SemaRef.PP;
4503 this->WritingModule = WritingModule;
4504 ASTFileSignature Signature = WriteASTCore(SemaRef, isysroot, WritingModule);
4505 Context = nullptr;
4506 PP = nullptr;
4507 this->WritingModule = nullptr;
4508 this->BaseDirectory.clear();
4509
4510 WritingAST = false;
4511 if (ShouldCacheASTInMemory) {
4512 // Construct MemoryBuffer and update buffer manager.
4513 ModuleCache.addBuiltPCM(OutputFile,
4514 llvm::MemoryBuffer::getMemBufferCopy(
4515 StringRef(Buffer.begin(), Buffer.size())));
4516 }
4517 return Signature;
4518}
4519
4520template<typename Vector>
4521static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4522 ASTWriter::RecordData &Record) {
4523 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4524 I != E; ++I) {
4525 Writer.AddDeclRef(*I, Record);
4526 }
4527}
4528
4529ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4530 Module *WritingModule) {
4531 using namespace llvm;
4532
4533 bool isModule = WritingModule != nullptr;
4534
4535 // Make sure that the AST reader knows to finalize itself.
4536 if (Chain)
4537 Chain->finalizeForWriting();
4538
4539 ASTContext &Context = SemaRef.Context;
4540 Preprocessor &PP = SemaRef.PP;
4541
4542 // Set up predefined declaration IDs.
4543 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4544 if (D) {
4545 assert(D->isCanonicalDecl() && "predefined decl is not canonical")(static_cast <bool> (D->isCanonicalDecl() &&
"predefined decl is not canonical") ? void (0) : __assert_fail
("D->isCanonicalDecl() && \"predefined decl is not canonical\""
, "clang/lib/Serialization/ASTWriter.cpp", 4545, __extension__
__PRETTY_FUNCTION__))
;
4546 DeclIDs[D] = ID;
4547 }
4548 };
4549 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4550 PREDEF_DECL_TRANSLATION_UNIT_ID);
4551 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4552 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4553 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4554 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4555 PREDEF_DECL_OBJC_PROTOCOL_ID);
4556 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4557 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4558 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4559 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4560 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4561 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4562 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4563 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4564 RegisterPredefDecl(Context.MSGuidTagDecl,
4565 PREDEF_DECL_BUILTIN_MS_GUID_ID);
4566 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4567 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4568 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4569 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4570 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4571 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4572 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4573 RegisterPredefDecl(Context.TypePackElementDecl,
4574 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4575
4576 // Build a record containing all of the tentative definitions in this file, in
4577 // TentativeDefinitions order. Generally, this record will be empty for
4578 // headers.
4579 RecordData TentativeDefinitions;
4580 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4581
4582 // Build a record containing all of the file scoped decls in this file.
4583 RecordData UnusedFileScopedDecls;
4584 if (!isModule)
4585 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4586 UnusedFileScopedDecls);
4587
4588 // Build a record containing all of the delegating constructors we still need
4589 // to resolve.
4590 RecordData DelegatingCtorDecls;
4591 if (!isModule)
4592 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4593
4594 // Write the set of weak, undeclared identifiers. We always write the
4595 // entire table, since later PCH files in a PCH chain are only interested in
4596 // the results at the end of the chain.
4597 RecordData WeakUndeclaredIdentifiers;
4598 for (const auto &WeakUndeclaredIdentifierList :
4599 SemaRef.WeakUndeclaredIdentifiers) {
4600 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
4601 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
4602 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4603 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4604 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4605 }
4606 }
4607
4608 // Build a record containing all of the ext_vector declarations.
4609 RecordData ExtVectorDecls;
4610 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4611
4612 // Build a record containing all of the VTable uses information.
4613 RecordData VTableUses;
4614 if (!SemaRef.VTableUses.empty()) {
4615 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4616 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4617 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4618 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4619 }
4620 }
4621
4622 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4623 RecordData UnusedLocalTypedefNameCandidates;
4624 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4625 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4626
4627 // Build a record containing all of pending implicit instantiations.
4628 RecordData PendingInstantiations;
4629 for (const auto &I : SemaRef.PendingInstantiations) {
4630 AddDeclRef(I.first, PendingInstantiations);
4631 AddSourceLocation(I.second, PendingInstantiations);
4632 }
4633 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (SemaRef.PendingLocalImplicitInstantiations
.empty() && "There are local ones at end of translation unit!"
) ? void (0) : __assert_fail ("SemaRef.PendingLocalImplicitInstantiations.empty() && \"There are local ones at end of translation unit!\""
, "clang/lib/Serialization/ASTWriter.cpp", 4634, __extension__
__PRETTY_FUNCTION__))
4634 "There are local ones at end of translation unit!")(static_cast <bool> (SemaRef.PendingLocalImplicitInstantiations
.empty() && "There are local ones at end of translation unit!"
) ? void (0) : __assert_fail ("SemaRef.PendingLocalImplicitInstantiations.empty() && \"There are local ones at end of translation unit!\""
, "clang/lib/Serialization/ASTWriter.cpp", 4634, __extension__
__PRETTY_FUNCTION__))
;
4635
4636 // Build a record containing some declaration references.
4637 RecordData SemaDeclRefs;
4638 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4639 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4640 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4641 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4642 }
4643
4644 RecordData CUDASpecialDeclRefs;
4645 if (Context.getcudaConfigureCallDecl()) {
4646 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4647 }
4648
4649 // Build a record containing all of the known namespaces.
4650 RecordData KnownNamespaces;
4651 for (const auto &I : SemaRef.KnownNamespaces) {
4652 if (!I.second)
4653 AddDeclRef(I.first, KnownNamespaces);
4654 }
4655
4656 // Build a record of all used, undefined objects that require definitions.
4657 RecordData UndefinedButUsed;
4658
4659 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4660 SemaRef.getUndefinedButUsed(Undefined);
4661 for (const auto &I : Undefined) {
4662 AddDeclRef(I.first, UndefinedButUsed);
4663 AddSourceLocation(I.second, UndefinedButUsed);
4664 }
4665
4666 // Build a record containing all delete-expressions that we would like to
4667 // analyze later in AST.
4668 RecordData DeleteExprsToAnalyze;
4669
4670 if (!isModule) {
4671 for (const auto &DeleteExprsInfo :
4672 SemaRef.getMismatchingDeleteExpressions()) {
4673 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4674 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4675 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4676 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4677 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4678 }
4679 }
4680 }
4681
4682 // Write the control block
4683 WriteControlBlock(PP, Context, isysroot);
4684
4685 // Write the remaining AST contents.
4686 Stream.FlushToWord();
4687 ASTBlockRange.first = Stream.GetCurrentBitNo();
4688 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4689 ASTBlockStartOffset = Stream.GetCurrentBitNo();
4690
4691 // This is so that older clang versions, before the introduction
4692 // of the control block, can read and reject the newer PCH format.
4693 {
4694 RecordData Record = {VERSION_MAJOR};
4695 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4696 }
4697
4698 // Create a lexical update block containing all of the declarations in the
4699 // translation unit that do not come from other AST files.
4700 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4701 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4702 for (const auto *D : TU->noload_decls()) {
4703 if (!D->isFromASTFile()) {
4704 NewGlobalKindDeclPairs.push_back(D->getKind());
4705 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4706 }
4707 }
4708
4709 auto Abv = std::make_shared<BitCodeAbbrev>();
4710 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4711 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4712 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4713 {
4714 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4715 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4716 bytes(NewGlobalKindDeclPairs));
4717 }
4718
4719 // And a visible updates block for the translation unit.
4720 Abv = std::make_shared<BitCodeAbbrev>();
4721 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4722 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4723 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4724 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4725 WriteDeclContextVisibleUpdate(TU);
4726
4727 // If we have any extern "C" names, write out a visible update for them.
4728 if (Context.ExternCContext)
4729 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4730
4731 // If the translation unit has an anonymous namespace, and we don't already
4732 // have an update block for it, write it as an update block.
4733 // FIXME: Why do we not do this if there's already an update block?
4734 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4735 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4736 if (Record.empty())
4737 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4738 }
4739
4740 // Add update records for all mangling numbers and static local numbers.
4741 // These aren't really update records, but this is a convenient way of
4742 // tagging this rare extra data onto the declarations.
4743 for (const auto &Number : Context.MangleNumbers)
4744 if (!Number.first->isFromASTFile())
4745 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4746 Number.second));
4747 for (const auto &Number : Context.StaticLocalNumbers)
4748 if (!Number.first->isFromASTFile())
4749 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4750 Number.second));
4751
4752 // Make sure visible decls, added to DeclContexts previously loaded from
4753 // an AST file, are registered for serialization. Likewise for template
4754 // specializations added to imported templates.
4755 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4756 GetDeclRef(I);
4757 }
4758
4759 // Make sure all decls associated with an identifier are registered for
4760 // serialization, if we're storing decls with identifiers.
4761 if (!WritingModule || !getLangOpts().CPlusPlus) {
4762 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4763 for (const auto &ID : PP.getIdentifierTable()) {
4764 const IdentifierInfo *II = ID.second;
4765 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4766 IIs.push_back(II);
4767 }
4768 // Sort the identifiers to visit based on their name.
4769 llvm::sort(IIs, llvm::deref<std::less<>>());
4770 for (const IdentifierInfo *II : IIs) {
4771 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4772 DEnd = SemaRef.IdResolver.end();
4773 D != DEnd; ++D) {
4774 GetDeclRef(*D);
4775 }
4776 }
4777 }
4778
4779 // For method pool in the module, if it contains an entry for a selector,
4780 // the entry should be complete, containing everything introduced by that
4781 // module and all modules it imports. It's possible that the entry is out of
4782 // date, so we need to pull in the new content here.
4783
4784 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4785 // safe, we copy all selectors out.
4786 llvm::SmallVector<Selector, 256> AllSelectors;
4787 for (auto &SelectorAndID : SelectorIDs)
4788 AllSelectors.push_back(SelectorAndID.first);
4789 for (auto &Selector : AllSelectors)
4790 SemaRef.updateOutOfDateSelector(Selector);
4791
4792 // Form the record of special types.
4793 RecordData SpecialTypes;
4794 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4795 AddTypeRef(Context.getFILEType(), SpecialTypes);
4796 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4797 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4798 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4799 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4800 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4801 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4802
4803 if (Chain) {
4804 // Write the mapping information describing our module dependencies and how
4805 // each of those modules were mapped into our own offset/ID space, so that
4806 // the reader can build the appropriate mapping to its own offset/ID space.
4807 // The map consists solely of a blob with the following format:
4808 // *(module-kind:i8
4809 // module-name-len:i16 module-name:len*i8
4810 // source-location-offset:i32
4811 // identifier-id:i32
4812 // preprocessed-entity-id:i32
4813 // macro-definition-id:i32
4814 // submodule-id:i32
4815 // selector-id:i32
4816 // declaration-id:i32
4817 // c++-base-specifiers-id:i32
4818 // type-id:i32)
4819 //
4820 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4821 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4822 // module name. Otherwise, it is the module file name.
4823 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4824 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4826 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4827 SmallString<2048> Buffer;
4828 {
4829 llvm::raw_svector_ostream Out(Buffer);
4830 for (ModuleFile &M : Chain->ModuleMgr) {
4831 using namespace llvm::support;
4832
4833 endian::Writer LE(Out, little);
4834 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4835 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
4836 LE.write<uint16_t>(Name.size());
4837 Out.write(Name.data(), Name.size());
4838
4839 // Note: if a base ID was uint max, it would not be possible to load
4840 // another module after it or have more than one entity inside it.
4841 uint32_t None = std::numeric_limits<uint32_t>::max();
4842
4843 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
4844 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high")(static_cast <bool> (BaseID < std::numeric_limits<
uint32_t>::max() && "base id too high") ? void (0)
: __assert_fail ("BaseID < std::numeric_limits<uint32_t>::max() && \"base id too high\""
, "clang/lib/Serialization/ASTWriter.cpp", 4844, __extension__
__PRETTY_FUNCTION__))
;
4845 if (ShouldWrite)
4846 LE.write<uint32_t>(BaseID);
4847 else
4848 LE.write<uint32_t>(None);
4849 };
4850
4851 // These values should be unique within a chain, since they will be read
4852 // as keys into ContinuousRangeMaps.
4853 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4854 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4855 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4856 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4857 M.NumPreprocessedEntities);
4858 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4859 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4860 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4861 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4862 }
4863 }
4864 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4865 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4866 Buffer.data(), Buffer.size());
4867 }
4868
4869 // Build a record containing all of the DeclsToCheckForDeferredDiags.
4870 SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
4871 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4872 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
4873
4874 RecordData DeclUpdatesOffsetsRecord;
4875
4876 // Keep writing types, declarations, and declaration update records
4877 // until we've emitted all of them.
4878 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4879 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
4880 WriteTypeAbbrevs();
4881 WriteDeclAbbrevs();
4882 do {
4883 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4884 while (!DeclTypesToEmit.empty()) {
4885 DeclOrType DOT = DeclTypesToEmit.front();
4886 DeclTypesToEmit.pop();
4887 if (DOT.isType())
4888 WriteType(DOT.getType());
4889 else
4890 WriteDecl(Context, DOT.getDecl());
4891 }
4892 } while (!DeclUpdates.empty());
4893 Stream.ExitBlock();
4894
4895 DoneWritingDeclsAndTypes = true;
4896
4897 // These things can only be done once we've written out decls and types.
4898 WriteTypeDeclOffsets();
4899 if (!DeclUpdatesOffsetsRecord.empty())
4900 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4901 WriteFileDeclIDsMap();
4902 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4903 WriteComments();
4904 WritePreprocessor(PP, isModule);
4905 WriteHeaderSearch(PP.getHeaderSearchInfo());
4906 WriteSelectors(SemaRef);
4907 WriteReferencedSelectorsPool(SemaRef);
4908 WriteLateParsedTemplates(SemaRef);
4909 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4910 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
4911 WriteOpenCLExtensions(SemaRef);
4912 WriteCUDAPragmas(SemaRef);
4913
4914 // If we're emitting a module, write out the submodule information.
4915 if (WritingModule)
4916 WriteSubmodules(WritingModule);
4917
4918 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4919
4920 // Write the record containing external, unnamed definitions.
4921 if (!EagerlyDeserializedDecls.empty())
4922 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4923
4924 if (!ModularCodegenDecls.empty())
4925 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4926
4927 // Write the record containing tentative definitions.
4928 if (!TentativeDefinitions.empty())
4929 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4930
4931 // Write the record containing unused file scoped decls.
4932 if (!UnusedFileScopedDecls.empty())
4933 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4934
4935 // Write the record containing weak undeclared identifiers.
4936 if (!WeakUndeclaredIdentifiers.empty())
4937 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4938 WeakUndeclaredIdentifiers);
4939
4940 // Write the record containing ext_vector type names.
4941 if (!ExtVectorDecls.empty())
4942 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4943
4944 // Write the record containing VTable uses information.
4945 if (!VTableUses.empty())
4946 Stream.EmitRecord(VTABLE_USES, VTableUses);
4947
4948 // Write the record containing potentially unused local typedefs.
4949 if (!UnusedLocalTypedefNameCandidates.empty())
4950 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4951 UnusedLocalTypedefNameCandidates);
4952
4953 // Write the record containing pending implicit instantiations.
4954 if (!PendingInstantiations.empty())
4955 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4956
4957 // Write the record containing declaration references of Sema.
4958 if (!SemaDeclRefs.empty())
4959 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4960
4961 // Write the record containing decls to be checked for deferred diags.
4962 if (!DeclsToCheckForDeferredDiags.empty())
4963 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4964 DeclsToCheckForDeferredDiags);
4965
4966 // Write the record containing CUDA-specific declaration references.
4967 if (!CUDASpecialDeclRefs.empty())
4968 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4969
4970 // Write the delegating constructors.
4971 if (!DelegatingCtorDecls.empty())
4972 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4973
4974 // Write the known namespaces.
4975 if (!KnownNamespaces.empty())
4976 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4977
4978 // Write the undefined internal functions and variables, and inline functions.
4979 if (!UndefinedButUsed.empty())
4980 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4981
4982 if (!DeleteExprsToAnalyze.empty())
4983 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4984
4985 // Write the visible updates to DeclContexts.
4986 for (auto *DC : UpdatedDeclContexts)
4987 WriteDeclContextVisibleUpdate(DC);
4988
4989 if (!WritingModule) {
4990 // Write the submodules that were imported, if any.
4991 struct ModuleInfo {
4992 uint64_t ID;
4993 Module *M;
4994 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4995 };
4996 llvm::SmallVector<ModuleInfo, 64> Imports;
4997 for (const auto *I : Context.local_imports()) {
4998 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end())(static_cast <bool> (SubmoduleIDs.find(I->getImportedModule
()) != SubmoduleIDs.end()) ? void (0) : __assert_fail ("SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()"
, "clang/lib/Serialization/ASTWriter.cpp", 4998, __extension__
__PRETTY_FUNCTION__))
;
4999 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5000 I->getImportedModule()));
5001 }
5002
5003 if (!Imports.empty()) {
5004 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5005 return A.ID < B.ID;
5006 };
5007 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5008 return A.ID == B.ID;
5009 };
5010
5011 // Sort and deduplicate module IDs.
5012 llvm::sort(Imports, Cmp);
5013 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5014 Imports.end());
5015
5016 RecordData ImportedModules;
5017 for (const auto &Import : Imports) {
5018 ImportedModules.push_back(Import.ID);
5019 // FIXME: If the module has macros imported then later has declarations
5020 // imported, this location won't be the right one as a location for the
5021 // declaration imports.
5022 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5023 }
5024
5025 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5026 }
5027 }
5028
5029 WriteObjCCategories();
5030 if(!WritingModule) {
5031 WriteOptimizePragmaOptions(SemaRef);
5032 WriteMSStructPragmaOptions(SemaRef);
5033 WriteMSPointersToMembersPragmaOptions(SemaRef);
5034 }
5035 WritePackPragmaOptions(SemaRef);
5036 WriteFloatControlPragmaOptions(SemaRef);
5037
5038 // Some simple statistics
5039 RecordData::value_type Record[] = {
5040 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5041 Stream.EmitRecord(STATISTICS, Record);
5042 Stream.ExitBlock();
5043 Stream.FlushToWord();
5044 ASTBlockRange.second = Stream.GetCurrentBitNo();
5045
5046 // Write the module file extension blocks.
5047 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5048 WriteModuleFileExtension(SemaRef, *ExtWriter);
5049
5050 return writeUnhashedControlBlock(PP, Context);
5051}
5052
5053void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5054 if (DeclUpdates.empty())
5055 return;
5056
5057 DeclUpdateMap LocalUpdates;
5058 LocalUpdates.swap(DeclUpdates);
5059
5060 for (auto &DeclUpdate : LocalUpdates) {
5061 const Decl *D = DeclUpdate.first;
5062
5063 bool HasUpdatedBody = false;
5064 RecordData RecordData;
5065 ASTRecordWriter Record(*this, RecordData);
5066 for (auto &Update : DeclUpdate.second) {
5067 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5068
5069 // An updated body is emitted last, so that the reader doesn't need
5070 // to skip over the lazy body to reach statements for other records.
5071 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5072 HasUpdatedBody = true;
5073 else
5074 Record.push_back(Kind);
5075
5076 switch (Kind) {
5077 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5078 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5079 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5080 assert(Update.getDecl() && "no decl to add?")(static_cast <bool> (Update.getDecl() && "no decl to add?"
) ? void (0) : __assert_fail ("Update.getDecl() && \"no decl to add?\""
, "clang/lib/Serialization/ASTWriter.cpp", 5080, __extension__
__PRETTY_FUNCTION__))
;
5081 Record.push_back(GetDeclRef(Update.getDecl()));
5082 break;
5083
5084 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5085 break;
5086
5087 case UPD_CXX_POINT_OF_INSTANTIATION:
5088 // FIXME: Do we need to also save the template specialization kind here?
5089 Record.AddSourceLocation(Update.getLoc());
5090 break;
5091
5092 case UPD_CXX_ADDED_VAR_DEFINITION: {
5093 const VarDecl *VD = cast<VarDecl>(D);
5094 Record.push_back(VD->isInline());
5095 Record.push_back(VD->isInlineSpecified());
5096 Record.AddVarDeclInit(VD);
5097 break;
5098 }
5099
5100 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5101 Record.AddStmt(const_cast<Expr *>(
5102 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5103 break;
5104
5105 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5106 Record.AddStmt(
5107 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5108 break;
5109
5110 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5111 auto *RD = cast<CXXRecordDecl>(D);
5112 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5113 Record.push_back(RD->isParamDestroyedInCallee());
5114 Record.push_back(RD->getArgPassingRestrictions());
5115 Record.AddCXXDefinitionData(RD);
5116 Record.AddOffset(WriteDeclContextLexicalBlock(
5117 *Context, const_cast<CXXRecordDecl *>(RD)));
5118
5119 // This state is sometimes updated by template instantiation, when we
5120 // switch from the specialization referring to the template declaration
5121 // to it referring to the template definition.
5122 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5123 Record.push_back(MSInfo->getTemplateSpecializationKind());
5124 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5125 } else {
5126 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5127 Record.push_back(Spec->getTemplateSpecializationKind());
5128 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5129
5130 // The instantiation might have been resolved to a partial
5131 // specialization. If so, record which one.
5132 auto From = Spec->getInstantiatedFrom();
5133 if (auto PartialSpec =
5134 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5135 Record.push_back(true);
5136 Record.AddDeclRef(PartialSpec);
5137 Record.AddTemplateArgumentList(
5138 &Spec->getTemplateInstantiationArgs());
5139 } else {
5140 Record.push_back(false);
5141 }
5142 }
5143 Record.push_back(RD->getTagKind());
5144 Record.AddSourceLocation(RD->getLocation());
5145 Record.AddSourceLocation(RD->getBeginLoc());
5146 Record.AddSourceRange(RD->getBraceRange());
5147
5148 // Instantiation may change attributes; write them all out afresh.
5149 Record.push_back(D->hasAttrs());
5150 if (D->hasAttrs())
5151 Record.AddAttributes(D->getAttrs());
5152
5153 // FIXME: Ensure we don't get here for explicit instantiations.
5154 break;
5155 }
5156
5157 case UPD_CXX_RESOLVED_DTOR_DELETE:
5158 Record.AddDeclRef(Update.getDecl());
5159 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5160 break;
5161
5162 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5163 auto prototype =
5164 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5165 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5166 break;
5167 }
5168
5169 case UPD_CXX_DEDUCED_RETURN_TYPE:
5170 Record.push_back(GetOrCreateTypeID(Update.getType()));
5171 break;
5172
5173 case UPD_DECL_MARKED_USED:
5174 break;
5175
5176 case UPD_MANGLING_NUMBER:
5177 case UPD_STATIC_LOCAL_NUMBER:
5178 Record.push_back(Update.getNumber());
5179 break;
5180
5181 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5182 Record.AddSourceRange(
5183 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5184 break;
5185
5186 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5187 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5188 Record.push_back(A->getAllocatorType());
5189 Record.AddStmt(A->getAllocator());
5190 Record.AddStmt(A->getAlignment());
5191 Record.AddSourceRange(A->getRange());
5192 break;
5193 }
5194
5195 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5196 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5197 Record.AddSourceRange(
5198 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5199 break;
5200
5201 case UPD_DECL_EXPORTED:
5202 Record.push_back(getSubmoduleID(Update.getModule()));
5203 break;
5204
5205 case UPD_ADDED_ATTR_TO_RECORD:
5206 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5207 break;
5208 }
5209 }
5210
5211 if (HasUpdatedBody) {
5212 const auto *Def = cast<FunctionDecl>(D);
5213 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5214 Record.push_back(Def->isInlined());
5215 Record.AddSourceLocation(Def->getInnerLocStart());
5216 Record.AddFunctionDefinition(Def);
5217 }
5218
5219 OffsetsRecord.push_back(GetDeclRef(D));
5220 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5221 }
5222}
5223
5224void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
5225 RecordDataImpl &Record) {
5226 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5227 Record.push_back(Raw);
5228}
5229
5230void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record,
5231 SourceLocationSequence *Seq) {
5232 Record.push_back(SourceLocationEncoding::encode(Loc, Seq));
5233}
5234
5235void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record,
5236 SourceLocationSequence *Seq) {
5237 AddSourceLocation(Range.getBegin(), Record, Seq);
5238 AddSourceLocation(Range.getEnd(), Record, Seq);
5239}
5240
5241void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5242 AddAPInt(Value.bitcastToAPInt());
5243}
5244
5245void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5246 Record.push_back(getIdentifierRef(II));
5247}
5248
5249IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5250 if (!II)
5251 return 0;
5252
5253 IdentID &ID = IdentifierIDs[II];
5254 if (ID == 0)
5255 ID = NextIdentID++;
5256 return ID;
5257}
5258
5259MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5260 // Don't emit builtin macros like __LINE__ to the AST file unless they
5261 // have been redefined by the header (in which case they are not
5262 // isBuiltinMacro).
5263 if (!MI || MI->isBuiltinMacro())
5264 return 0;
5265
5266 MacroID &ID = MacroIDs[MI];
5267 if (ID == 0) {
5268 ID = NextMacroID++;
5269 MacroInfoToEmitData Info = { Name, MI, ID };
5270 MacroInfosToEmit.push_back(Info);
5271 }
5272 return ID;
5273}
5274
5275MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5276 if (!MI || MI->isBuiltinMacro())
5277 return 0;
5278
5279 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!")(static_cast <bool> (MacroIDs.find(MI) != MacroIDs.end(
) && "Macro not emitted!") ? void (0) : __assert_fail
("MacroIDs.find(MI) != MacroIDs.end() && \"Macro not emitted!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5279, __extension__
__PRETTY_FUNCTION__))
;
5280 return MacroIDs[MI];
5281}
5282
5283uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5284 return IdentMacroDirectivesOffsetMap.lookup(Name);
5285}
5286
5287void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5288 Record->push_back(Writer->getSelectorRef(SelRef));
5289}
5290
5291SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5292 if (Sel.getAsOpaquePtr() == nullptr) {
5293 return 0;
5294 }
5295
5296 SelectorID SID = SelectorIDs[Sel];
5297 if (SID == 0 && Chain) {
5298 // This might trigger a ReadSelector callback, which will set the ID for
5299 // this selector.
5300 Chain->LoadSelector(Sel);
5301 SID = SelectorIDs[Sel];
5302 }
5303 if (SID == 0) {
5304 SID = NextSelectorID++;
5305 SelectorIDs[Sel] = SID;
5306 }
5307 return SID;
5308}
5309
5310void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5311 AddDeclRef(Temp->getDestructor());
5312}
5313
5314void ASTRecordWriter::AddTemplateArgumentLocInfo(
5315 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5316 switch (Kind) {
5317 case TemplateArgument::Expression:
5318 AddStmt(Arg.getAsExpr());
5319 break;
5320 case TemplateArgument::Type:
5321 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5322 break;
5323 case TemplateArgument::Template:
5324 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5325 AddSourceLocation(Arg.getTemplateNameLoc());
5326 break;
5327 case TemplateArgument::TemplateExpansion:
5328 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5329 AddSourceLocation(Arg.getTemplateNameLoc());
5330 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5331 break;
5332 case TemplateArgument::Null:
5333 case TemplateArgument::Integral:
5334 case TemplateArgument::Declaration:
5335 case TemplateArgument::NullPtr:
5336 case TemplateArgument::Pack:
5337 // FIXME: Is this right?
5338 break;
5339 }
5340}
5341
5342void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5343 AddTemplateArgument(Arg.getArgument());
5344
5345 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5346 bool InfoHasSameExpr
5347 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5348 Record->push_back(InfoHasSameExpr);
5349 if (InfoHasSameExpr)
5350 return; // Avoid storing the same expr twice.
5351 }
5352 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5353}
5354
5355void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5356 if (!TInfo) {
5357 AddTypeRef(QualType());
5358 return;
5359 }
5360
5361 AddTypeRef(TInfo->getType());
5362 AddTypeLoc(TInfo->getTypeLoc());
5363}
5364
5365void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) {
5366 LocSeq::State Seq(OuterSeq);
5367 TypeLocWriter TLW(*this, Seq);
5368 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5369 TLW.Visit(TL);
5370}
5371
5372void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5373 Record.push_back(GetOrCreateTypeID(T));
5374}
5375
5376TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5377 assert(Context)(static_cast <bool> (Context) ? void (0) : __assert_fail
("Context", "clang/lib/Serialization/ASTWriter.cpp", 5377, __extension__
__PRETTY_FUNCTION__))
;
5378 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5379 if (T.isNull())
5380 return TypeIdx();
5381 assert(!T.getLocalFastQualifiers())(static_cast <bool> (!T.getLocalFastQualifiers()) ? void
(0) : __assert_fail ("!T.getLocalFastQualifiers()", "clang/lib/Serialization/ASTWriter.cpp"
, 5381, __extension__ __PRETTY_FUNCTION__))
;
5382
5383 TypeIdx &Idx = TypeIdxs[T];
5384 if (Idx.getIndex() == 0) {
5385 if (DoneWritingDeclsAndTypes) {
5386 assert(0 && "New type seen after serializing all the types to emit!")(static_cast <bool> (0 && "New type seen after serializing all the types to emit!"
) ? void (0) : __assert_fail ("0 && \"New type seen after serializing all the types to emit!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5386, __extension__
__PRETTY_FUNCTION__))
;
5387 return TypeIdx();
5388 }
5389
5390 // We haven't seen this type before. Assign it a new ID and put it
5391 // into the queue of types to emit.
5392 Idx = TypeIdx(NextTypeID++);
5393 DeclTypesToEmit.push(T);
5394 }
5395 return Idx;
5396 });
5397}
5398
5399TypeID ASTWriter::getTypeID(QualType T) const {
5400 assert(Context)(static_cast <bool> (Context) ? void (0) : __assert_fail
("Context", "clang/lib/Serialization/ASTWriter.cpp", 5400, __extension__
__PRETTY_FUNCTION__))
;
5401 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5402 if (T.isNull())
5403 return TypeIdx();
5404 assert(!T.getLocalFastQualifiers())(static_cast <bool> (!T.getLocalFastQualifiers()) ? void
(0) : __assert_fail ("!T.getLocalFastQualifiers()", "clang/lib/Serialization/ASTWriter.cpp"
, 5404, __extension__ __PRETTY_FUNCTION__))
;
5405
5406 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5407 assert(I != TypeIdxs.end() && "Type not emitted!")(static_cast <bool> (I != TypeIdxs.end() && "Type not emitted!"
) ? void (0) : __assert_fail ("I != TypeIdxs.end() && \"Type not emitted!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5407, __extension__
__PRETTY_FUNCTION__))
;
5408 return I->second;
5409 });
5410}
5411
5412void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5413 Record.push_back(GetDeclRef(D));
5414}
5415
5416DeclID ASTWriter::GetDeclRef(const Decl *D) {
5417 assert(WritingAST && "Cannot request a declaration ID before AST writing")(static_cast <bool> (WritingAST && "Cannot request a declaration ID before AST writing"
) ? void (0) : __assert_fail ("WritingAST && \"Cannot request a declaration ID before AST writing\""
, "clang/lib/Serialization/ASTWriter.cpp", 5417, __extension__
__PRETTY_FUNCTION__))
;
5418
5419 if (!D) {
5420 return 0;
5421 }
5422
5423 // If D comes from an AST file, its declaration ID is already known and
5424 // fixed.
5425 if (D->isFromASTFile())
5426 return D->getGlobalID();
5427
5428 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer")(static_cast <bool> (!(reinterpret_cast<uintptr_t>
(D) & 0x01) && "Invalid decl pointer") ? void (0)
: __assert_fail ("!(reinterpret_cast<uintptr_t>(D) & 0x01) && \"Invalid decl pointer\""
, "clang/lib/Serialization/ASTWriter.cpp", 5428, __extension__
__PRETTY_FUNCTION__))
;
5429 DeclID &ID = DeclIDs[D];
5430 if (ID == 0) {
5431 if (DoneWritingDeclsAndTypes) {
5432 assert(0 && "New decl seen after serializing all the decls to emit!")(static_cast <bool> (0 && "New decl seen after serializing all the decls to emit!"
) ? void (0) : __assert_fail ("0 && \"New decl seen after serializing all the decls to emit!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5432, __extension__
__PRETTY_FUNCTION__))
;
5433 return 0;
5434 }
5435
5436 // We haven't seen this declaration before. Give it a new ID and
5437 // enqueue it in the list of declarations to emit.
5438 ID = NextDeclID++;
5439 DeclTypesToEmit.push(const_cast<Decl *>(D));
5440 }
5441
5442 return ID;
5443}
5444
5445DeclID ASTWriter::getDeclID(const Decl *D) {
5446 if (!D)
5447 return 0;
5448
5449 // If D comes from an AST file, its declaration ID is already known and
5450 // fixed.
5451 if (D->isFromASTFile())
5452 return D->getGlobalID();
5453
5454 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!")(static_cast <bool> (DeclIDs.find(D) != DeclIDs.end() &&
"Declaration not emitted!") ? void (0) : __assert_fail ("DeclIDs.find(D) != DeclIDs.end() && \"Declaration not emitted!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5454, __extension__
__PRETTY_FUNCTION__))
;
5455 return DeclIDs[D];
5456}
5457
5458void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5459 assert(ID)(static_cast <bool> (ID) ? void (0) : __assert_fail ("ID"
, "clang/lib/Serialization/ASTWriter.cpp", 5459, __extension__
__PRETTY_FUNCTION__))
;
5460 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/Serialization/ASTWriter.cpp", 5460, __extension__
__PRETTY_FUNCTION__))
;
5461
5462 SourceLocation Loc = D->getLocation();
5463 if (Loc.isInvalid())
5464 return;
5465
5466 // We only keep track of the file-level declarations of each file.
5467 if (!D->getLexicalDeclContext()->isFileContext())
5468 return;
5469 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5470 // a function/objc method, should not have TU as lexical context.
5471 // TemplateTemplateParmDecls that are part of an alias template, should not
5472 // have TU as lexical context.
5473 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5474 return;
5475
5476 SourceManager &SM = Context->getSourceManager();
5477 SourceLocation FileLoc = SM.getFileLoc(Loc);
5478 assert(SM.isLocalSourceLocation(FileLoc))(static_cast <bool> (SM.isLocalSourceLocation(FileLoc))
? void (0) : __assert_fail ("SM.isLocalSourceLocation(FileLoc)"
, "clang/lib/Serialization/ASTWriter.cpp", 5478, __extension__
__PRETTY_FUNCTION__))
;
5479 FileID FID;
5480 unsigned Offset;
5481 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5482 if (FID.isInvalid())
5483 return;
5484 assert(SM.getSLocEntry(FID).isFile())(static_cast <bool> (SM.getSLocEntry(FID).isFile()) ? void
(0) : __assert_fail ("SM.getSLocEntry(FID).isFile()", "clang/lib/Serialization/ASTWriter.cpp"
, 5484, __extension__ __PRETTY_FUNCTION__))
;
5485
5486 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5487 if (!Info)
5488 Info = std::make_unique<DeclIDInFileInfo>();
5489
5490 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5491 LocDeclIDsTy &Decls = Info->DeclIDs;
5492 Decls.push_back(LocDecl);
5493}
5494
5495unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5496 assert(needsAnonymousDeclarationNumber(D) &&(static_cast <bool> (needsAnonymousDeclarationNumber(D)
&& "expected an anonymous declaration") ? void (0) :
__assert_fail ("needsAnonymousDeclarationNumber(D) && \"expected an anonymous declaration\""
, "clang/lib/Serialization/ASTWriter.cpp", 5497, __extension__
__PRETTY_FUNCTION__))
5497 "expected an anonymous declaration")(static_cast <bool> (needsAnonymousDeclarationNumber(D)
&& "expected an anonymous declaration") ? void (0) :
__assert_fail ("needsAnonymousDeclarationNumber(D) && \"expected an anonymous declaration\""
, "clang/lib/Serialization/ASTWriter.cpp", 5497, __extension__
__PRETTY_FUNCTION__))
;
5498
5499 // Number the anonymous declarations within this context, if we've not
5500 // already done so.
5501 auto It = AnonymousDeclarationNumbers.find(D);
5502 if (It == AnonymousDeclarationNumbers.end()) {
5503 auto *DC = D->getLexicalDeclContext();
5504 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5505 AnonymousDeclarationNumbers[ND] = Number;
5506 });
5507
5508 It = AnonymousDeclarationNumbers.find(D);
5509 assert(It != AnonymousDeclarationNumbers.end() &&(static_cast <bool> (It != AnonymousDeclarationNumbers.
end() && "declaration not found within its lexical context"
) ? void (0) : __assert_fail ("It != AnonymousDeclarationNumbers.end() && \"declaration not found within its lexical context\""
, "clang/lib/Serialization/ASTWriter.cpp", 5510, __extension__
__PRETTY_FUNCTION__))
5510 "declaration not found within its lexical context")(static_cast <bool> (It != AnonymousDeclarationNumbers.
end() && "declaration not found within its lexical context"
) ? void (0) : __assert_fail ("It != AnonymousDeclarationNumbers.end() && \"declaration not found within its lexical context\""
, "clang/lib/Serialization/ASTWriter.cpp", 5510, __extension__
__PRETTY_FUNCTION__))
;
5511 }
5512
5513 return It->second;
5514}
5515
5516void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5517 DeclarationName Name) {
5518 switch (Name.getNameKind()) {
5519 case DeclarationName::CXXConstructorName:
5520 case DeclarationName::CXXDestructorName:
5521 case DeclarationName::CXXConversionFunctionName:
5522 AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
5523 break;
5524
5525 case DeclarationName::CXXOperatorName:
5526 AddSourceRange(DNLoc.getCXXOperatorNameRange());
5527 break;
5528
5529 case DeclarationName::CXXLiteralOperatorName:
5530 AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
5531 break;
5532
5533 case DeclarationName::Identifier:
5534 case DeclarationName::ObjCZeroArgSelector:
5535 case DeclarationName::ObjCOneArgSelector:
5536 case DeclarationName::ObjCMultiArgSelector:
5537 case DeclarationName::CXXUsingDirective:
5538 case DeclarationName::CXXDeductionGuideName:
5539 break;
5540 }
5541}
5542
5543void ASTRecordWriter::AddDeclarationNameInfo(
5544 const DeclarationNameInfo &NameInfo) {
5545 AddDeclarationName(NameInfo.getName());
5546 AddSourceLocation(NameInfo.getLoc());
5547 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5548}
5549
5550void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5551 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5552 Record->push_back(Info.NumTemplParamLists);
5553 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5554 AddTemplateParameterList(Info.TemplParamLists[i]);
5555}
5556
5557void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5558 // Nested name specifiers usually aren't too long. I think that 8 would
5559 // typically accommodate the vast majority.
5560 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5561
5562 // Push each of the nested-name-specifiers's onto a stack for
5563 // serialization in reverse order.
5564 while (NNS) {
5565 NestedNames.push_back(NNS);
5566 NNS = NNS.getPrefix();
5567 }
5568
5569 Record->push_back(NestedNames.size());
5570 while(!NestedNames.empty()) {
5571 NNS = NestedNames.pop_back_val();
5572 NestedNameSpecifier::SpecifierKind Kind
5573 = NNS.getNestedNameSpecifier()->getKind();
5574 Record->push_back(Kind);
5575 switch (Kind) {
5576 case NestedNameSpecifier::Identifier:
5577 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5578 AddSourceRange(NNS.getLocalSourceRange());
5579 break;
5580
5581 case NestedNameSpecifier::Namespace:
5582 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5583 AddSourceRange(NNS.getLocalSourceRange());
5584 break;
5585
5586 case NestedNameSpecifier::NamespaceAlias:
5587 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5588 AddSourceRange(NNS.getLocalSourceRange());
5589 break;
5590
5591 case NestedNameSpecifier::TypeSpec:
5592 case NestedNameSpecifier::TypeSpecWithTemplate:
5593 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5594 AddTypeRef(NNS.getTypeLoc().getType());
5595 AddTypeLoc(NNS.getTypeLoc());
5596 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5597 break;
5598
5599 case NestedNameSpecifier::Global:
5600 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5601 break;
5602
5603 case NestedNameSpecifier::Super:
5604 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5605 AddSourceRange(NNS.getLocalSourceRange());
5606 break;
5607 }
5608 }
5609}
5610
5611void ASTRecordWriter::AddTemplateParameterList(
5612 const TemplateParameterList *TemplateParams) {
5613 assert(TemplateParams && "No TemplateParams!")(static_cast <bool> (TemplateParams && "No TemplateParams!"
) ? void (0) : __assert_fail ("TemplateParams && \"No TemplateParams!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5613, __extension__
__PRETTY_FUNCTION__))
;
5614 AddSourceLocation(TemplateParams->getTemplateLoc());
5615 AddSourceLocation(TemplateParams->getLAngleLoc());
5616 AddSourceLocation(TemplateParams->getRAngleLoc());
5617
5618 Record->push_back(TemplateParams->size());
5619 for (const auto &P : *TemplateParams)
5620 AddDeclRef(P);
5621 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5622 Record->push_back(true);
5623 AddStmt(const_cast<Expr*>(RequiresClause));
5624 } else {
5625 Record->push_back(false);
5626 }
5627}
5628
5629/// Emit a template argument list.
5630void ASTRecordWriter::AddTemplateArgumentList(
5631 const TemplateArgumentList *TemplateArgs) {
5632 assert(TemplateArgs && "No TemplateArgs!")(static_cast <bool> (TemplateArgs && "No TemplateArgs!"
) ? void (0) : __assert_fail ("TemplateArgs && \"No TemplateArgs!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5632, __extension__
__PRETTY_FUNCTION__))
;
5633 Record->push_back(TemplateArgs->size());
5634 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5635 AddTemplateArgument(TemplateArgs->get(i));
5636}
5637
5638void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5639 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5640 assert(ASTTemplArgList && "No ASTTemplArgList!")(static_cast <bool> (ASTTemplArgList && "No ASTTemplArgList!"
) ? void (0) : __assert_fail ("ASTTemplArgList && \"No ASTTemplArgList!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5640, __extension__
__PRETTY_FUNCTION__))
;
5641 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5642 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5643 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5644 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5645 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5646 AddTemplateArgumentLoc(TemplArgs[i]);
5647}
5648
5649void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5650 Record->push_back(Set.size());
5651 for (ASTUnresolvedSet::const_iterator
5652 I = Set.begin(), E = Set.end(); I != E; ++I) {
5653 AddDeclRef(I.getDecl());
5654 Record->push_back(I.getAccess());
5655 }
5656}
5657
5658// FIXME: Move this out of the main ASTRecordWriter interface.
5659void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5660 Record->push_back(Base.isVirtual());
5661 Record->push_back(Base.isBaseOfClass());
5662 Record->push_back(Base.getAccessSpecifierAsWritten());
5663 Record->push_back(Base.getInheritConstructors());
5664 AddTypeSourceInfo(Base.getTypeSourceInfo());
5665 AddSourceRange(Base.getSourceRange());
5666 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5667 : SourceLocation());
5668}
5669
5670static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5671 ArrayRef<CXXBaseSpecifier> Bases) {
5672 ASTWriter::RecordData Record;
5673 ASTRecordWriter Writer(W, Record);
5674 Writer.push_back(Bases.size());
5675
5676 for (auto &Base : Bases)
5677 Writer.AddCXXBaseSpecifier(Base);
5678
5679 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5680}
5681
5682// FIXME: Move this out of the main ASTRecordWriter interface.
5683void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5684 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5685}
5686
5687static uint64_t
5688EmitCXXCtorInitializers(ASTWriter &W,
5689 ArrayRef<CXXCtorInitializer *> CtorInits) {
5690 ASTWriter::RecordData Record;
5691 ASTRecordWriter Writer(W, Record);
5692 Writer.push_back(CtorInits.size());
5693
5694 for (auto *Init : CtorInits) {
5695 if (Init->isBaseInitializer()) {
5696 Writer.push_back(CTOR_INITIALIZER_BASE);
5697 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5698 Writer.push_back(Init->isBaseVirtual());
5699 } else if (Init->isDelegatingInitializer()) {
5700 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5701 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5702 } else if (Init->isMemberInitializer()){
5703 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5704 Writer.AddDeclRef(Init->getMember());
5705 } else {
5706 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5707 Writer.AddDeclRef(Init->getIndirectMember());
5708 }
5709
5710 Writer.AddSourceLocation(Init->getMemberLocation());
5711 Writer.AddStmt(Init->getInit());
5712 Writer.AddSourceLocation(Init->getLParenLoc());
5713 Writer.AddSourceLocation(Init->getRParenLoc());
5714 Writer.push_back(Init->isWritten());
5715 if (Init->isWritten())
5716 Writer.push_back(Init->getSourceOrder());
5717 }
5718
5719 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5720}
5721
5722// FIXME: Move this out of the main ASTRecordWriter interface.
5723void ASTRecordWriter::AddCXXCtorInitializers(
5724 ArrayRef<CXXCtorInitializer *> CtorInits) {
5725 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5726}
5727
5728void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5729 auto &Data = D->data();
5730 Record->push_back(Data.IsLambda);
5731
5732 #define FIELD(Name, Width, Merge) \
5733 Record->push_back(Data.Name);
5734 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
5735
5736 // getODRHash will compute the ODRHash if it has not been previously computed.
5737 Record->push_back(D->getODRHash());
5738 bool ModulesDebugInfo =
5739 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
5740 Record->push_back(ModulesDebugInfo);
5741 if (ModulesDebugInfo)
5742 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5743
5744 // IsLambda bit is already saved.
5745
5746 Record->push_back(Data.NumBases);
5747 if (Data.NumBases > 0)
5748 AddCXXBaseSpecifiers(Data.bases());
5749
5750 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5751 Record->push_back(Data.NumVBases);
5752 if (Data.NumVBases > 0)
5753 AddCXXBaseSpecifiers(Data.vbases());
5754
5755 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5756 Record->push_back(Data.ComputedVisibleConversions);
5757 if (Data.ComputedVisibleConversions)
5758 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5759 // Data.Definition is the owning decl, no need to write it.
5760 AddDeclRef(D->getFirstFriend());
5761
5762 // Add lambda-specific data.
5763 if (Data.IsLambda) {
5764 auto &Lambda = D->getLambdaData();
5765 Record->push_back(Lambda.DependencyKind);
5766 Record->push_back(Lambda.IsGenericLambda);
5767 Record->push_back(Lambda.CaptureDefault);
5768 Record->push_back(Lambda.NumCaptures);
5769 Record->push_back(Lambda.NumExplicitCaptures);
5770 Record->push_back(Lambda.HasKnownInternalLinkage);
5771 Record->push_back(Lambda.ManglingNumber);
5772 Record->push_back(D->getDeviceLambdaManglingNumber());
5773 AddDeclRef(D->getLambdaContextDecl());
5774 AddTypeSourceInfo(Lambda.MethodTyInfo);
5775 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5776 const LambdaCapture &Capture = Lambda.Captures[I];
5777 AddSourceLocation(Capture.getLocation());
5778 Record->push_back(Capture.isImplicit());
5779 Record->push_back(Capture.getCaptureKind());
5780 switch (Capture.getCaptureKind()) {
5781 case LCK_StarThis:
5782 case LCK_This:
5783 case LCK_VLAType:
5784 break;
5785 case LCK_ByCopy:
5786 case LCK_ByRef:
5787 ValueDecl *Var =
5788 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5789 AddDeclRef(Var);
5790 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5791 : SourceLocation());
5792 break;
5793 }
5794 }
5795 }
5796}
5797
5798void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
5799 const Expr *Init = VD->getInit();
5800 if (!Init) {
5801 push_back(0);
5802 return;
5803 }
5804
5805 unsigned Val = 1;
5806 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
5807 Val |= (ES->HasConstantInitialization ? 2 : 0);
5808 Val |= (ES->HasConstantDestruction ? 4 : 0);
5809 // FIXME: Also emit the constant initializer value.
5810 }
5811 push_back(Val);
5812 writeStmtRef(Init);
5813}
5814
5815void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5816 assert(Reader && "Cannot remove chain")(static_cast <bool> (Reader && "Cannot remove chain"
) ? void (0) : __assert_fail ("Reader && \"Cannot remove chain\""
, "clang/lib/Serialization/ASTWriter.cpp", 5816, __extension__
__PRETTY_FUNCTION__))
;
5817 assert((!Chain || Chain == Reader) && "Cannot replace chain")(static_cast <bool> ((!Chain || Chain == Reader) &&
"Cannot replace chain") ? void (0) : __assert_fail ("(!Chain || Chain == Reader) && \"Cannot replace chain\""
, "clang/lib/Serialization/ASTWriter.cpp", 5817, __extension__
__PRETTY_FUNCTION__))
;
5818 assert(FirstDeclID == NextDeclID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5819 FirstTypeID == NextTypeID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5820 FirstIdentID == NextIdentID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5821 FirstMacroID == NextMacroID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5822 FirstSubmoduleID == NextSubmoduleID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5823 FirstSelectorID == NextSelectorID &&(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
5824 "Setting chain after writing has started.")(static_cast <bool> (FirstDeclID == NextDeclID &&
FirstTypeID == NextTypeID && FirstIdentID == NextIdentID
&& FirstMacroID == NextMacroID && FirstSubmoduleID
== NextSubmoduleID && FirstSelectorID == NextSelectorID
&& "Setting chain after writing has started.") ? void
(0) : __assert_fail ("FirstDeclID == NextDeclID && FirstTypeID == NextTypeID && FirstIdentID == NextIdentID && FirstMacroID == NextMacroID && FirstSubmoduleID == NextSubmoduleID && FirstSelectorID == NextSelectorID && \"Setting chain after writing has started.\""
, "clang/lib/Serialization/ASTWriter.cpp", 5824, __extension__
__PRETTY_FUNCTION__))
;
5825
5826 Chain = Reader;
5827
5828 // Note, this will get called multiple times, once one the reader starts up
5829 // and again each time it's done reading a PCH or module.
5830 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5831 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5832 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5833 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5834 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5835 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5836 NextDeclID = FirstDeclID;
5837 NextTypeID = FirstTypeID;
5838 NextIdentID = FirstIdentID;
5839 NextMacroID = FirstMacroID;
5840 NextSelectorID = FirstSelectorID;
5841 NextSubmoduleID = FirstSubmoduleID;
5842}
5843
5844void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5845 // Always keep the highest ID. See \p TypeRead() for more information.
5846 IdentID &StoredID = IdentifierIDs[II];
5847 if (ID > StoredID)
5848 StoredID = ID;
5849}
5850
5851void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5852 // Always keep the highest ID. See \p TypeRead() for more information.
5853 MacroID &StoredID = MacroIDs[MI];
5854 if (ID > StoredID)
5855 StoredID = ID;
5856}
5857
5858void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5859 // Always take the highest-numbered type index. This copes with an interesting
5860 // case for chained AST writing where we schedule writing the type and then,
5861 // later, deserialize the type from another AST. In this case, we want to
5862 // keep the higher-numbered entry so that we can properly write it out to
5863 // the AST file.
5864 TypeIdx &StoredIdx = TypeIdxs[T];
5865 if (Idx.getIndex() >= StoredIdx.getIndex())
5866 StoredIdx = Idx;
5867}
5868
5869void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5870 // Always keep the highest ID. See \p TypeRead() for more information.
5871 SelectorID &StoredID = SelectorIDs[S];
5872 if (ID > StoredID)
5873 StoredID = ID;
5874}
5875
5876void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5877 MacroDefinitionRecord *MD) {
5878 assert(MacroDefinitions.find(MD) == MacroDefinitions.end())(static_cast <bool> (MacroDefinitions.find(MD) == MacroDefinitions
.end()) ? void (0) : __assert_fail ("MacroDefinitions.find(MD) == MacroDefinitions.end()"
, "clang/lib/Serialization/ASTWriter.cpp", 5878, __extension__
__PRETTY_FUNCTION__))
;
5879 MacroDefinitions[MD] = ID;
5880}
5881
5882void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5883 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end())(static_cast <bool> (SubmoduleIDs.find(Mod) == SubmoduleIDs
.end()) ? void (0) : __assert_fail ("SubmoduleIDs.find(Mod) == SubmoduleIDs.end()"
, "clang/lib/Serialization/ASTWriter.cpp", 5883, __extension__
__PRETTY_FUNCTION__))
;
5884 SubmoduleIDs[Mod] = ID;
5885}
5886
5887void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5888 if (Chain && Chain->isProcessingUpdateRecords()) return;
5889 assert(D->isCompleteDefinition())(static_cast <bool> (D->isCompleteDefinition()) ? void
(0) : __assert_fail ("D->isCompleteDefinition()", "clang/lib/Serialization/ASTWriter.cpp"
, 5889, __extension__ __PRETTY_FUNCTION__))
;
5890 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5890, __extension__
__PRETTY_FUNCTION__))
;
5891 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5892 // We are interested when a PCH decl is modified.
5893 if (RD->isFromASTFile()) {
5894 // A forward reference was mutated into a definition. Rewrite it.
5895 // FIXME: This happens during template instantiation, should we
5896 // have created a new definition decl instead ?
5897 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&(static_cast <bool> (isTemplateInstantiation(RD->getTemplateSpecializationKind
()) && "completed a tag from another module but not by instantiation?"
) ? void (0) : __assert_fail ("isTemplateInstantiation(RD->getTemplateSpecializationKind()) && \"completed a tag from another module but not by instantiation?\""
, "clang/lib/Serialization/ASTWriter.cpp", 5898, __extension__
__PRETTY_FUNCTION__))
5898 "completed a tag from another module but not by instantiation?")(static_cast <bool> (isTemplateInstantiation(RD->getTemplateSpecializationKind
()) && "completed a tag from another module but not by instantiation?"
) ? void (0) : __assert_fail ("isTemplateInstantiation(RD->getTemplateSpecializationKind()) && \"completed a tag from another module but not by instantiation?\""
, "clang/lib/Serialization/ASTWriter.cpp", 5898, __extension__
__PRETTY_FUNCTION__))
;
5899 DeclUpdates[RD].push_back(
5900 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5901 }
5902 }
5903}
5904
5905static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5906 if (D->isFromASTFile())
5907 return true;
5908
5909 // The predefined __va_list_tag struct is imported if we imported any decls.
5910 // FIXME: This is a gross hack.
5911 return D == D->getASTContext().getVaListTagDecl();
5912}
5913
5914void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5915 if (Chain && Chain->isProcessingUpdateRecords()) return;
5916 assert(DC->isLookupContext() &&(static_cast <bool> (DC->isLookupContext() &&
"Should not add lookup results to non-lookup contexts!") ? void
(0) : __assert_fail ("DC->isLookupContext() && \"Should not add lookup results to non-lookup contexts!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5917, __extension__
__PRETTY_FUNCTION__))
5917 "Should not add lookup results to non-lookup contexts!")(static_cast <bool> (DC->isLookupContext() &&
"Should not add lookup results to non-lookup contexts!") ? void
(0) : __assert_fail ("DC->isLookupContext() && \"Should not add lookup results to non-lookup contexts!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5917, __extension__
__PRETTY_FUNCTION__))
;
5918
5919 // TU is handled elsewhere.
5920 if (isa<TranslationUnitDecl>(DC))
5921 return;
5922
5923 // Namespaces are handled elsewhere, except for template instantiations of
5924 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5925 // local instantiations are added to an imported context. Only happens when
5926 // adding ADL lookup candidates, for example templated friends.
5927 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5928 !isa<FunctionTemplateDecl>(D))
5929 return;
5930
5931 // We're only interested in cases where a local declaration is added to an
5932 // imported context.
5933 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5934 return;
5935
5936 assert(DC == DC->getPrimaryContext() && "added to non-primary context")(static_cast <bool> (DC == DC->getPrimaryContext() &&
"added to non-primary context") ? void (0) : __assert_fail (
"DC == DC->getPrimaryContext() && \"added to non-primary context\""
, "clang/lib/Serialization/ASTWriter.cpp", 5936, __extension__
__PRETTY_FUNCTION__))
;
5937 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!")(static_cast <bool> (!getDefinitiveDeclContext(DC) &&
"DeclContext not definitive!") ? void (0) : __assert_fail ("!getDefinitiveDeclContext(DC) && \"DeclContext not definitive!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5937, __extension__
__PRETTY_FUNCTION__))
;
5938 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5938, __extension__
__PRETTY_FUNCTION__))
;
5939 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5940 // We're adding a visible declaration to a predefined decl context. Ensure
5941 // that we write out all of its lookup results so we don't get a nasty
5942 // surprise when we try to emit its lookup table.
5943 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
5944 }
5945 DeclsToEmitEvenIfUnreferenced.push_back(D);
5946}
5947
5948void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5949 if (Chain && Chain->isProcessingUpdateRecords()) return;
5950 assert(D->isImplicit())(static_cast <bool> (D->isImplicit()) ? void (0) : __assert_fail
("D->isImplicit()", "clang/lib/Serialization/ASTWriter.cpp"
, 5950, __extension__ __PRETTY_FUNCTION__))
;
5951
5952 // We're only interested in cases where a local declaration is added to an
5953 // imported context.
5954 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5955 return;
5956
5957 if (!isa<CXXMethodDecl>(D))
5958 return;
5959
5960 // A decl coming from PCH was modified.
5961 assert(RD->isCompleteDefinition())(static_cast <bool> (RD->isCompleteDefinition()) ? void
(0) : __assert_fail ("RD->isCompleteDefinition()", "clang/lib/Serialization/ASTWriter.cpp"
, 5961, __extension__ __PRETTY_FUNCTION__))
;
5962 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5962, __extension__
__PRETTY_FUNCTION__))
;
5963 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5964}
5965
5966void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5967 if (Chain && Chain->isProcessingUpdateRecords()) return;
5968 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!")(static_cast <bool> (!DoneWritingDeclsAndTypes &&
"Already done writing updates!") ? void (0) : __assert_fail (
"!DoneWritingDeclsAndTypes && \"Already done writing updates!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5968, __extension__
__PRETTY_FUNCTION__))
;
5969 if (!Chain) return;
5970 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5971 // If we don't already know the exception specification for this redecl
5972 // chain, add an update record for it.
5973 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5974 ->getType()
5975 ->castAs<FunctionProtoType>()
5976 ->getExceptionSpecType()))
5977 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5978 });
5979}
5980
5981void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5982 if (Chain && Chain->isProcessingUpdateRecords()) return;
5983 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5983, __extension__
__PRETTY_FUNCTION__))
;
5984 if (!Chain) return;
5985 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5986 DeclUpdates[D].push_back(
5987 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5988 });
5989}
5990
5991void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5992 const FunctionDecl *Delete,
5993 Expr *ThisArg) {
5994 if (Chain && Chain->isProcessingUpdateRecords()) return;
5995 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 5995, __extension__
__PRETTY_FUNCTION__))
;
5996 assert(Delete && "Not given an operator delete")(static_cast <bool> (Delete && "Not given an operator delete"
) ? void (0) : __assert_fail ("Delete && \"Not given an operator delete\""
, "clang/lib/Serialization/ASTWriter.cpp", 5996, __extension__
__PRETTY_FUNCTION__))
;
5997 if (!Chain) return;
5998 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5999 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6000 });
6001}
6002
6003void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6004 if (Chain && Chain->isProcessingUpdateRecords()) return;
6005 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6005, __extension__
__PRETTY_FUNCTION__))
;
6006 if (!D->isFromASTFile())
6007 return; // Declaration not imported from PCH.
6008
6009 // Implicit function decl from a PCH was defined.
6010 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6011}
6012
6013void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6014 if (Chain && Chain->isProcessingUpdateRecords()) return;
6015 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6015, __extension__
__PRETTY_FUNCTION__))
;
6016 if (!D->isFromASTFile())
6017 return;
6018
6019 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6020}
6021
6022void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6023 if (Chain && Chain->isProcessingUpdateRecords()) return;
6024 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6024, __extension__
__PRETTY_FUNCTION__))
;
6025 if (!D->isFromASTFile())
6026 return;
6027
6028 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6029}
6030
6031void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6032 if (Chain && Chain->isProcessingUpdateRecords()) return;
6033 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6033, __extension__
__PRETTY_FUNCTION__))
;
6034 if (!D->isFromASTFile())
6035 return;
6036
6037 // Since the actual instantiation is delayed, this really means that we need
6038 // to update the instantiation location.
6039 SourceLocation POI;
6040 if (auto *VD = dyn_cast<VarDecl>(D))
6041 POI = VD->getPointOfInstantiation();
6042 else
6043 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6044 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6045}
6046
6047void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6048 if (Chain && Chain->isProcessingUpdateRecords()) return;
6049 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6049, __extension__
__PRETTY_FUNCTION__))
;
6050 if (!D->isFromASTFile())
6051 return;
6052
6053 DeclUpdates[D].push_back(
6054 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6055}
6056
6057void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6058 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6058, __extension__
__PRETTY_FUNCTION__))
;
6059 if (!D->isFromASTFile())
6060 return;
6061
6062 DeclUpdates[D].push_back(
6063 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6064}
6065
6066void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6067 const ObjCInterfaceDecl *IFD) {
6068 if (Chain && Chain->isProcessingUpdateRecords()) return;
6069 assert(!WritingAST && "Already writing the AST!")(static_cast <bool> (!WritingAST && "Already writing the AST!"
) ? void (0) : __assert_fail ("!WritingAST && \"Already writing the AST!\""
, "clang/lib/Serialization/ASTWriter.cpp", 6069, __extension__
__PRETTY_FUNCTION__))
;
6070 if (!IFD->isFromASTFile())
6071 return; // Declaration not imported from PCH.
6072
6073 assert(IFD->getDefinition() && "Category on a class without a definition?")(static_cast <bool> (IFD->getDefinition() &&
"Category on a class without a definition?") ? void (0) : __assert_fail
("IFD->getDefinition() && \"Category on a class without a definition?\""
, "clang/lib/Serialization/ASTWriter.cpp", 6073, __extension__
__PRETTY_FUNCTION__))
;
6074 ObjCClassesWithCategories.insert(
6075 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6076}
6077
6078void ASTWriter::DeclarationMarkedUsed(const Decl *D) {