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