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