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