Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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