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