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