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