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