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