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