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