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