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