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