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