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