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