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