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