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