Bug Summary

File:build/source/clang/lib/Serialization/ASTWriter.cpp
Warning:line 1949, column 7
Potential memory leak

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