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