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