Bug Summary

File:build/source/llvm/include/llvm/Bitstream/BitstreamWriter.h
Warning:line 493, column 9
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTWriter.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -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 _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/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 1672917203 -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-01-05-142129-16235-1 -x c++ /build/source/clang/lib/Serialization/ASTWriter.cpp

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

/build/source/llvm/include/llvm/Bitstream/BitstreamWriter.h

1//===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines the BitstreamWriter class. This class can be used to
10// write an arbitrary bitstream, regardless of its contents.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
15#define LLVM_BITSTREAM_BITSTREAMWRITER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Bitstream/BitCodes.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Support/raw_ostream.h"
24#include <algorithm>
25#include <optional>
26#include <vector>
27
28namespace llvm {
29
30class BitstreamWriter {
31 /// Out - The buffer that keeps unflushed bytes.
32 SmallVectorImpl<char> &Out;
33
34 /// FS - The file stream that Out flushes to. If FS is nullptr, it does not
35 /// support read or seek, Out cannot be flushed until all data are written.
36 raw_fd_stream *FS;
37
38 /// FlushThreshold - If FS is valid, this is the threshold (unit B) to flush
39 /// FS.
40 const uint64_t FlushThreshold;
41
42 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
43 unsigned CurBit;
44
45 /// CurValue - The current value. Only bits < CurBit are valid.
46 uint32_t CurValue;
47
48 /// CurCodeSize - This is the declared size of code values used for the
49 /// current block, in bits.
50 unsigned CurCodeSize;
51
52 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
53 /// selected BLOCK ID.
54 unsigned BlockInfoCurBID;
55
56 /// CurAbbrevs - Abbrevs installed at in this block.
57 std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
58
59 struct Block {
60 unsigned PrevCodeSize;
61 size_t StartSizeWord;
62 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
63 Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
64 };
65
66 /// BlockScope - This tracks the current blocks that we have entered.
67 std::vector<Block> BlockScope;
68
69 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
70 /// These describe abbreviations that all blocks of the specified ID inherit.
71 struct BlockInfo {
72 unsigned BlockID;
73 std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
74 };
75 std::vector<BlockInfo> BlockInfoRecords;
76
77 void WriteWord(unsigned Value) {
78 Value = support::endian::byte_swap<uint32_t, support::little>(Value);
79 Out.append(reinterpret_cast<const char *>(&Value),
80 reinterpret_cast<const char *>(&Value + 1));
81 }
82
83 uint64_t GetNumOfFlushedBytes() const { return FS ? FS->tell() : 0; }
84
85 size_t GetBufferOffset() const { return Out.size() + GetNumOfFlushedBytes(); }
86
87 size_t GetWordIndex() const {
88 size_t Offset = GetBufferOffset();
89 assert((Offset & 3) == 0 && "Not 32-bit aligned")(static_cast <bool> ((Offset & 3) == 0 && "Not 32-bit aligned"
) ? void (0) : __assert_fail ("(Offset & 3) == 0 && \"Not 32-bit aligned\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 89, __extension__
__PRETTY_FUNCTION__))
;
90 return Offset / 4;
91 }
92
93 /// If the related file stream supports reading, seeking and writing, flush
94 /// the buffer if its size is above a threshold.
95 void FlushToFile() {
96 if (!FS)
97 return;
98 if (Out.size() < FlushThreshold)
99 return;
100 FS->write((char *)&Out.front(), Out.size());
101 Out.clear();
102 }
103
104public:
105 /// Create a BitstreamWriter that writes to Buffer \p O.
106 ///
107 /// \p FS is the file stream that \p O flushes to incrementally. If \p FS is
108 /// null, \p O does not flush incrementially, but writes to disk at the end.
109 ///
110 /// \p FlushThreshold is the threshold (unit M) to flush \p O if \p FS is
111 /// valid. Flushing only occurs at (sub)block boundaries.
112 BitstreamWriter(SmallVectorImpl<char> &O, raw_fd_stream *FS = nullptr,
113 uint32_t FlushThreshold = 512)
114 : Out(O), FS(FS), FlushThreshold(FlushThreshold << 20), CurBit(0),
115 CurValue(0), CurCodeSize(2) {}
116
117 ~BitstreamWriter() {
118 assert(CurBit == 0 && "Unflushed data remaining")(static_cast <bool> (CurBit == 0 && "Unflushed data remaining"
) ? void (0) : __assert_fail ("CurBit == 0 && \"Unflushed data remaining\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 118, __extension__
__PRETTY_FUNCTION__))
;
119 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance")(static_cast <bool> (BlockScope.empty() && CurAbbrevs
.empty() && "Block imbalance") ? void (0) : __assert_fail
("BlockScope.empty() && CurAbbrevs.empty() && \"Block imbalance\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 119, __extension__
__PRETTY_FUNCTION__))
;
120 }
121
122 /// Retrieve the current position in the stream, in bits.
123 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
124
125 /// Retrieve the number of bits currently used to encode an abbrev ID.
126 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
127
128 //===--------------------------------------------------------------------===//
129 // Basic Primitives for emitting bits to the stream.
130 //===--------------------------------------------------------------------===//
131
132 /// Backpatch a 32-bit word in the output at the given bit offset
133 /// with the specified value.
134 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
135 using namespace llvm::support;
136 uint64_t ByteNo = BitNo / 8;
137 uint64_t StartBit = BitNo & 7;
138 uint64_t NumOfFlushedBytes = GetNumOfFlushedBytes();
139
140 if (ByteNo >= NumOfFlushedBytes) {
141 assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>((static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes]
, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes], StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 143, __extension__
__PRETTY_FUNCTION__))
142 &Out[ByteNo - NumOfFlushedBytes], StartBit)) &&(static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes]
, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes], StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 143, __extension__
__PRETTY_FUNCTION__))
143 "Expected to be patching over 0-value placeholders")(static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes]
, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( &Out[ByteNo - NumOfFlushedBytes], StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 143, __extension__
__PRETTY_FUNCTION__))
;
144 endian::writeAtBitAlignment<uint32_t, little, unaligned>(
145 &Out[ByteNo - NumOfFlushedBytes], NewWord, StartBit);
146 return;
147 }
148
149 // If the byte offset to backpatch is flushed, use seek to backfill data.
150 // First, save the file position to restore later.
151 uint64_t CurPos = FS->tell();
152
153 // Copy data to update into Bytes from the file FS and the buffer Out.
154 char Bytes[9]; // Use one more byte to silence a warning from Visual C++.
155 size_t BytesNum = StartBit ? 8 : 4;
156 size_t BytesFromDisk = std::min(static_cast<uint64_t>(BytesNum), NumOfFlushedBytes - ByteNo);
157 size_t BytesFromBuffer = BytesNum - BytesFromDisk;
158
159 // When unaligned, copy existing data into Bytes from the file FS and the
160 // buffer Out so that it can be updated before writing. For debug builds
161 // read bytes unconditionally in order to check that the existing value is 0
162 // as expected.
163#ifdef NDEBUG
164 if (StartBit)
165#endif
166 {
167 FS->seek(ByteNo);
168 ssize_t BytesRead = FS->read(Bytes, BytesFromDisk);
169 (void)BytesRead; // silence warning
170 assert(BytesRead >= 0 && static_cast<size_t>(BytesRead) == BytesFromDisk)(static_cast <bool> (BytesRead >= 0 && static_cast
<size_t>(BytesRead) == BytesFromDisk) ? void (0) : __assert_fail
("BytesRead >= 0 && static_cast<size_t>(BytesRead) == BytesFromDisk"
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 170, __extension__
__PRETTY_FUNCTION__))
;
171 for (size_t i = 0; i < BytesFromBuffer; ++i)
172 Bytes[BytesFromDisk + i] = Out[i];
173 assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>((static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( Bytes, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( Bytes, StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 175, __extension__
__PRETTY_FUNCTION__))
174 Bytes, StartBit)) &&(static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( Bytes, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( Bytes, StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 175, __extension__
__PRETTY_FUNCTION__))
175 "Expected to be patching over 0-value placeholders")(static_cast <bool> ((!endian::readAtBitAlignment<uint32_t
, little, unaligned>( Bytes, StartBit)) && "Expected to be patching over 0-value placeholders"
) ? void (0) : __assert_fail ("(!endian::readAtBitAlignment<uint32_t, little, unaligned>( Bytes, StartBit)) && \"Expected to be patching over 0-value placeholders\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 175, __extension__
__PRETTY_FUNCTION__))
;
176 }
177
178 // Update Bytes in terms of bit offset and value.
179 endian::writeAtBitAlignment<uint32_t, little, unaligned>(Bytes, NewWord,
180 StartBit);
181
182 // Copy updated data back to the file FS and the buffer Out.
183 FS->seek(ByteNo);
184 FS->write(Bytes, BytesFromDisk);
185 for (size_t i = 0; i < BytesFromBuffer; ++i)
186 Out[i] = Bytes[BytesFromDisk + i];
187
188 // Restore the file position.
189 FS->seek(CurPos);
190 }
191
192 void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
193 BackpatchWord(BitNo, (uint32_t)Val);
194 BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
195 }
196
197 void Emit(uint32_t Val, unsigned NumBits) {
198 assert(NumBits && NumBits <= 32 && "Invalid value size!")(static_cast <bool> (NumBits && NumBits <= 32
&& "Invalid value size!") ? void (0) : __assert_fail
("NumBits && NumBits <= 32 && \"Invalid value size!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 198, __extension__
__PRETTY_FUNCTION__))
;
199 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!")(static_cast <bool> ((Val & ~(~0U >> (32-NumBits
))) == 0 && "High bits set!") ? void (0) : __assert_fail
("(Val & ~(~0U >> (32-NumBits))) == 0 && \"High bits set!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 199, __extension__
__PRETTY_FUNCTION__))
;
200 CurValue |= Val << CurBit;
201 if (CurBit + NumBits < 32) {
202 CurBit += NumBits;
203 return;
204 }
205
206 // Add the current word.
207 WriteWord(CurValue);
208
209 if (CurBit)
210 CurValue = Val >> (32-CurBit);
211 else
212 CurValue = 0;
213 CurBit = (CurBit+NumBits) & 31;
214 }
215
216 void FlushToWord() {
217 if (CurBit) {
218 WriteWord(CurValue);
219 CurBit = 0;
220 CurValue = 0;
221 }
222 }
223
224 void EmitVBR(uint32_t Val, unsigned NumBits) {
225 assert(NumBits <= 32 && "Too many bits to emit!")(static_cast <bool> (NumBits <= 32 && "Too many bits to emit!"
) ? void (0) : __assert_fail ("NumBits <= 32 && \"Too many bits to emit!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 225, __extension__
__PRETTY_FUNCTION__))
;
226 uint32_t Threshold = 1U << (NumBits-1);
227
228 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
229 while (Val >= Threshold) {
230 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
231 Val >>= NumBits-1;
232 }
233
234 Emit(Val, NumBits);
235 }
236
237 void EmitVBR64(uint64_t Val, unsigned NumBits) {
238 assert(NumBits <= 32 && "Too many bits to emit!")(static_cast <bool> (NumBits <= 32 && "Too many bits to emit!"
) ? void (0) : __assert_fail ("NumBits <= 32 && \"Too many bits to emit!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 238, __extension__
__PRETTY_FUNCTION__))
;
239 if ((uint32_t)Val == Val)
240 return EmitVBR((uint32_t)Val, NumBits);
241
242 uint32_t Threshold = 1U << (NumBits-1);
243
244 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
245 while (Val >= Threshold) {
246 Emit(((uint32_t)Val & ((1 << (NumBits - 1)) - 1)) | (1 << (NumBits - 1)),
247 NumBits);
248 Val >>= NumBits-1;
249 }
250
251 Emit((uint32_t)Val, NumBits);
252 }
253
254 /// EmitCode - Emit the specified code.
255 void EmitCode(unsigned Val) {
256 Emit(Val, CurCodeSize);
257 }
258
259 //===--------------------------------------------------------------------===//
260 // Block Manipulation
261 //===--------------------------------------------------------------------===//
262
263 /// getBlockInfo - If there is block info for the specified ID, return it,
264 /// otherwise return null.
265 BlockInfo *getBlockInfo(unsigned BlockID) {
266 // Common case, the most recent entry matches BlockID.
267 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
268 return &BlockInfoRecords.back();
269
270 for (BlockInfo &BI : BlockInfoRecords)
271 if (BI.BlockID == BlockID)
272 return &BI;
273 return nullptr;
274 }
275
276 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
277 // Block header:
278 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
279 EmitCode(bitc::ENTER_SUBBLOCK);
280 EmitVBR(BlockID, bitc::BlockIDWidth);
281 EmitVBR(CodeLen, bitc::CodeLenWidth);
282 FlushToWord();
283
284 size_t BlockSizeWordIndex = GetWordIndex();
285 unsigned OldCodeSize = CurCodeSize;
286
287 // Emit a placeholder, which will be replaced when the block is popped.
288 Emit(0, bitc::BlockSizeWidth);
289
290 CurCodeSize = CodeLen;
291
292 // Push the outer block's abbrev set onto the stack, start out with an
293 // empty abbrev set.
294 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
295 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
296
297 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
298 // to the abbrev list.
299 if (BlockInfo *Info = getBlockInfo(BlockID))
300 append_range(CurAbbrevs, Info->Abbrevs);
301 }
302
303 void ExitBlock() {
304 assert(!BlockScope.empty() && "Block scope imbalance!")(static_cast <bool> (!BlockScope.empty() && "Block scope imbalance!"
) ? void (0) : __assert_fail ("!BlockScope.empty() && \"Block scope imbalance!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 304, __extension__
__PRETTY_FUNCTION__))
;
305 const Block &B = BlockScope.back();
306
307 // Block tail:
308 // [END_BLOCK, <align4bytes>]
309 EmitCode(bitc::END_BLOCK);
310 FlushToWord();
311
312 // Compute the size of the block, in words, not counting the size field.
313 size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
314 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
315
316 // Update the block size field in the header of this sub-block.
317 BackpatchWord(BitNo, SizeInWords);
318
319 // Restore the inner block's code size and abbrev table.
320 CurCodeSize = B.PrevCodeSize;
321 CurAbbrevs = std::move(B.PrevAbbrevs);
322 BlockScope.pop_back();
323 FlushToFile();
324 }
325
326 //===--------------------------------------------------------------------===//
327 // Record Emission
328 //===--------------------------------------------------------------------===//
329
330private:
331 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
332 /// record. This is a no-op, since the abbrev specifies the literal to use.
333 template<typename uintty>
334 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
335 assert(Op.isLiteral() && "Not a literal")(static_cast <bool> (Op.isLiteral() && "Not a literal"
) ? void (0) : __assert_fail ("Op.isLiteral() && \"Not a literal\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 335, __extension__
__PRETTY_FUNCTION__))
;
336 // If the abbrev specifies the literal value to use, don't emit
337 // anything.
338 assert(V == Op.getLiteralValue() &&(static_cast <bool> (V == Op.getLiteralValue() &&
"Invalid abbrev for record!") ? void (0) : __assert_fail ("V == Op.getLiteralValue() && \"Invalid abbrev for record!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 339, __extension__
__PRETTY_FUNCTION__))
339 "Invalid abbrev for record!")(static_cast <bool> (V == Op.getLiteralValue() &&
"Invalid abbrev for record!") ? void (0) : __assert_fail ("V == Op.getLiteralValue() && \"Invalid abbrev for record!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 339, __extension__
__PRETTY_FUNCTION__))
;
340 }
341
342 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
343 /// encoding.
344 template<typename uintty>
345 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
346 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!")(static_cast <bool> (!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!"
) ? void (0) : __assert_fail ("!Op.isLiteral() && \"Literals should use EmitAbbreviatedLiteral!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 346, __extension__
__PRETTY_FUNCTION__))
;
347
348 // Encode the value as we are commanded.
349 switch (Op.getEncoding()) {
350 default: llvm_unreachable("Unknown encoding!")::llvm::llvm_unreachable_internal("Unknown encoding!", "llvm/include/llvm/Bitstream/BitstreamWriter.h"
, 350)
;
351 case BitCodeAbbrevOp::Fixed:
352 if (Op.getEncodingData())
353 Emit((unsigned)V, (unsigned)Op.getEncodingData());
354 break;
355 case BitCodeAbbrevOp::VBR:
356 if (Op.getEncodingData())
357 EmitVBR64(V, (unsigned)Op.getEncodingData());
358 break;
359 case BitCodeAbbrevOp::Char6:
360 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
361 break;
362 }
363 }
364
365 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
366 /// emission code. If BlobData is non-null, then it specifies an array of
367 /// data that should be emitted as part of the Blob or Array operand that is
368 /// known to exist at the end of the record. If Code is specified, then
369 /// it is the record code to emit before the Vals, which must not contain
370 /// the code.
371 template <typename uintty>
372 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
373 StringRef Blob, std::optional<unsigned> Code) {
374 const char *BlobData = Blob.data();
375 unsigned BlobLen = (unsigned) Blob.size();
376 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
377 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!")(static_cast <bool> (AbbrevNo < CurAbbrevs.size() &&
"Invalid abbrev #!") ? void (0) : __assert_fail ("AbbrevNo < CurAbbrevs.size() && \"Invalid abbrev #!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 377, __extension__
__PRETTY_FUNCTION__))
;
378 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
379
380 EmitCode(Abbrev);
381
382 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
383 if (Code) {
384 assert(e && "Expected non-empty abbreviation")(static_cast <bool> (e && "Expected non-empty abbreviation"
) ? void (0) : __assert_fail ("e && \"Expected non-empty abbreviation\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 384, __extension__
__PRETTY_FUNCTION__))
;
385 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
386
387 if (Op.isLiteral())
388 EmitAbbreviatedLiteral(Op, *Code);
389 else {
390 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&(static_cast <bool> (Op.getEncoding() != BitCodeAbbrevOp
::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob &&
"Expected literal or scalar") ? void (0) : __assert_fail ("Op.getEncoding() != BitCodeAbbrevOp::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob && \"Expected literal or scalar\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 392, __extension__
__PRETTY_FUNCTION__))
391 Op.getEncoding() != BitCodeAbbrevOp::Blob &&(static_cast <bool> (Op.getEncoding() != BitCodeAbbrevOp
::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob &&
"Expected literal or scalar") ? void (0) : __assert_fail ("Op.getEncoding() != BitCodeAbbrevOp::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob && \"Expected literal or scalar\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 392, __extension__
__PRETTY_FUNCTION__))
392 "Expected literal or scalar")(static_cast <bool> (Op.getEncoding() != BitCodeAbbrevOp
::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob &&
"Expected literal or scalar") ? void (0) : __assert_fail ("Op.getEncoding() != BitCodeAbbrevOp::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob && \"Expected literal or scalar\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 392, __extension__
__PRETTY_FUNCTION__))
;
393 EmitAbbreviatedField(Op, *Code);
394 }
395 }
396
397 unsigned RecordIdx = 0;
398 for (; i != e; ++i) {
399 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
400 if (Op.isLiteral()) {
401 assert(RecordIdx < Vals.size() && "Invalid abbrev/record")(static_cast <bool> (RecordIdx < Vals.size() &&
"Invalid abbrev/record") ? void (0) : __assert_fail ("RecordIdx < Vals.size() && \"Invalid abbrev/record\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 401, __extension__
__PRETTY_FUNCTION__))
;
402 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
403 ++RecordIdx;
404 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
405 // Array case.
406 assert(i + 2 == e && "array op not second to last?")(static_cast <bool> (i + 2 == e && "array op not second to last?"
) ? void (0) : __assert_fail ("i + 2 == e && \"array op not second to last?\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 406, __extension__
__PRETTY_FUNCTION__))
;
407 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
408
409 // If this record has blob data, emit it, otherwise we must have record
410 // entries to encode this way.
411 if (BlobData) {
412 assert(RecordIdx == Vals.size() &&(static_cast <bool> (RecordIdx == Vals.size() &&
"Blob data and record entries specified for array!") ? void (
0) : __assert_fail ("RecordIdx == Vals.size() && \"Blob data and record entries specified for array!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 413, __extension__
__PRETTY_FUNCTION__))
413 "Blob data and record entries specified for array!")(static_cast <bool> (RecordIdx == Vals.size() &&
"Blob data and record entries specified for array!") ? void (
0) : __assert_fail ("RecordIdx == Vals.size() && \"Blob data and record entries specified for array!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 413, __extension__
__PRETTY_FUNCTION__))
;
414 // Emit a vbr6 to indicate the number of elements present.
415 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
416
417 // Emit each field.
418 for (unsigned i = 0; i != BlobLen; ++i)
419 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
420
421 // Know that blob data is consumed for assertion below.
422 BlobData = nullptr;
423 } else {
424 // Emit a vbr6 to indicate the number of elements present.
425 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
426
427 // Emit each field.
428 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
429 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
430 }
431 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
432 // If this record has blob data, emit it, otherwise we must have record
433 // entries to encode this way.
434
435 if (BlobData) {
436 assert(RecordIdx == Vals.size() &&(static_cast <bool> (RecordIdx == Vals.size() &&
"Blob data and record entries specified for blob operand!") ?
void (0) : __assert_fail ("RecordIdx == Vals.size() && \"Blob data and record entries specified for blob operand!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 437, __extension__
__PRETTY_FUNCTION__))
437 "Blob data and record entries specified for blob operand!")(static_cast <bool> (RecordIdx == Vals.size() &&
"Blob data and record entries specified for blob operand!") ?
void (0) : __assert_fail ("RecordIdx == Vals.size() && \"Blob data and record entries specified for blob operand!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 437, __extension__
__PRETTY_FUNCTION__))
;
438
439 assert(Blob.data() == BlobData && "BlobData got moved")(static_cast <bool> (Blob.data() == BlobData &&
"BlobData got moved") ? void (0) : __assert_fail ("Blob.data() == BlobData && \"BlobData got moved\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 439, __extension__
__PRETTY_FUNCTION__))
;
440 assert(Blob.size() == BlobLen && "BlobLen got changed")(static_cast <bool> (Blob.size() == BlobLen && "BlobLen got changed"
) ? void (0) : __assert_fail ("Blob.size() == BlobLen && \"BlobLen got changed\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 440, __extension__
__PRETTY_FUNCTION__))
;
441 emitBlob(Blob);
442 BlobData = nullptr;
443 } else {
444 emitBlob(Vals.slice(RecordIdx));
445 }
446 } else { // Single scalar field.
447 assert(RecordIdx < Vals.size() && "Invalid abbrev/record")(static_cast <bool> (RecordIdx < Vals.size() &&
"Invalid abbrev/record") ? void (0) : __assert_fail ("RecordIdx < Vals.size() && \"Invalid abbrev/record\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 447, __extension__
__PRETTY_FUNCTION__))
;
448 EmitAbbreviatedField(Op, Vals[RecordIdx]);
449 ++RecordIdx;
450 }
451 }
452 assert(RecordIdx == Vals.size() && "Not all record operands emitted!")(static_cast <bool> (RecordIdx == Vals.size() &&
"Not all record operands emitted!") ? void (0) : __assert_fail
("RecordIdx == Vals.size() && \"Not all record operands emitted!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 452, __extension__
__PRETTY_FUNCTION__))
;
453 assert(BlobData == nullptr &&(static_cast <bool> (BlobData == nullptr && "Blob data specified for record that doesn't use it!"
) ? void (0) : __assert_fail ("BlobData == nullptr && \"Blob data specified for record that doesn't use it!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 454, __extension__
__PRETTY_FUNCTION__))
454 "Blob data specified for record that doesn't use it!")(static_cast <bool> (BlobData == nullptr && "Blob data specified for record that doesn't use it!"
) ? void (0) : __assert_fail ("BlobData == nullptr && \"Blob data specified for record that doesn't use it!\""
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 454, __extension__
__PRETTY_FUNCTION__))
;
455 }
456
457public:
458 /// Emit a blob, including flushing before and tail-padding.
459 template <class UIntTy>
460 void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
461 // Emit a vbr6 to indicate the number of elements present.
462 if (ShouldEmitSize)
463 EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
464
465 // Flush to a 32-bit alignment boundary.
466 FlushToWord();
467
468 // Emit literal bytes.
469 assert(llvm::all_of(Bytes, [](UIntTy B) { return isUInt<8>(B); }))(static_cast <bool> (llvm::all_of(Bytes, [](UIntTy B) {
return isUInt<8>(B); })) ? void (0) : __assert_fail ("llvm::all_of(Bytes, [](UIntTy B) { return isUInt<8>(B); })"
, "llvm/include/llvm/Bitstream/BitstreamWriter.h", 469, __extension__
__PRETTY_FUNCTION__))
;
470 Out.append(Bytes.begin(), Bytes.end());
471
472 // Align end to 32-bits.
473 while (GetBufferOffset() & 3)
474 Out.push_back(0);
475 }
476 void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
477 emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
478 ShouldEmitSize);
479 }
480
481 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
482 /// we have one to compress the output.
483 template <typename Container>
484 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
485 if (!Abbrev
1.1
'Abbrev' is 0
1.1
'Abbrev' is 0
) {
2
Taking true branch
486 // If we don't have an abbrev to use, emit this in its fully unabbreviated
487 // form.
488 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
489 EmitCode(bitc::UNABBREV_RECORD);
490 EmitVBR(Code, 6);
491 EmitVBR(Count, 6);
492 for (unsigned i = 0, e = Count; i != e; ++i)
3
Assuming 'i' is not equal to 'e'
4
Loop condition is true. Entering loop body
5
The value 1 is assigned to 'i'
6
Assuming 'i' is not equal to 'e'
7
Loop condition is true. Entering loop body
493 EmitVBR64(Vals[i], 6);
8
1st function call argument is an uninitialized value
494 return;
495 }
496
497 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
498 }
499
500 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
501 /// Unlike EmitRecord, the code for the record should be included in Vals as
502 /// the first entry.
503 template <typename Container>
504 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
505 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(),
506 std::nullopt);
507 }
508
509 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
510 /// abbrev that includes a blob at the end. The blob data to emit is
511 /// specified by the pointer and length specified at the end. In contrast to
512 /// EmitRecord, this routine expects that the first entry in Vals is the code
513 /// of the record.
514 template <typename Container>
515 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
516 StringRef Blob) {
517 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, std::nullopt);
518 }
519 template <typename Container>
520 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
521 const char *BlobData, unsigned BlobLen) {
522 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
523 StringRef(BlobData, BlobLen), std::nullopt);
524 }
525
526 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
527 /// that end with an array.
528 template <typename Container>
529 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
530 StringRef Array) {
531 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, std::nullopt);
532 }
533 template <typename Container>
534 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
535 const char *ArrayData, unsigned ArrayLen) {
536 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
537 StringRef(ArrayData, ArrayLen),
538 std::nullopt);
539 }
540
541 //===--------------------------------------------------------------------===//
542 // Abbrev Emission
543 //===--------------------------------------------------------------------===//
544
545private:
546 // Emit the abbreviation as a DEFINE_ABBREV record.
547 void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
548 EmitCode(bitc::DEFINE_ABBREV);
549 EmitVBR(Abbv.getNumOperandInfos(), 5);
550 for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
551 i != e; ++i) {
552 const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
553 Emit(Op.isLiteral(), 1);
554 if (Op.isLiteral()) {
555 EmitVBR64(Op.getLiteralValue(), 8);
556 } else {
557 Emit(Op.getEncoding(), 3);
558 if (Op.hasEncodingData())
559 EmitVBR64(Op.getEncodingData(), 5);
560 }
561 }
562 }
563public:
564
565 /// Emits the abbreviation \p Abbv to the stream.
566 unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
567 EncodeAbbrev(*Abbv);
568 CurAbbrevs.push_back(std::move(Abbv));
569 return static_cast<unsigned>(CurAbbrevs.size())-1 +
570 bitc::FIRST_APPLICATION_ABBREV;
571 }
572
573 //===--------------------------------------------------------------------===//
574 // BlockInfo Block Emission
575 //===--------------------------------------------------------------------===//
576
577 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
578 void EnterBlockInfoBlock() {
579 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
580 BlockInfoCurBID = ~0U;
581 BlockInfoRecords.clear();
582 }
583private:
584 /// SwitchToBlockID - If we aren't already talking about the specified block
585 /// ID, emit a BLOCKINFO_CODE_SETBID record.
586 void SwitchToBlockID(unsigned BlockID) {
587 if (BlockInfoCurBID == BlockID) return;
588 SmallVector<unsigned, 2> V;
589 V.push_back(BlockID);
590 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
591 BlockInfoCurBID = BlockID;
592 }
593
594 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
595 if (BlockInfo *BI = getBlockInfo(BlockID))
596 return *BI;
597
598 // Otherwise, add a new record.
599 BlockInfoRecords.emplace_back();
600 BlockInfoRecords.back().BlockID = BlockID;
601 return BlockInfoRecords.back();
602 }
603
604public:
605
606 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
607 /// BlockID.
608 unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr<BitCodeAbbrev> Abbv) {
609 SwitchToBlockID(BlockID);
610 EncodeAbbrev(*Abbv);
611
612 // Add the abbrev to the specified block record.
613 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
614 Info.Abbrevs.push_back(std::move(Abbv));
615
616 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
617 }
618};
619
620
621} // End llvm namespace
622
623#endif