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