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 /// Determine the declaration that should be put into the name lookup table to
3483 /// represent the given declaration in this module. This is usually D itself,
3484 /// but if D was imported and merged into a local declaration, we want the most
3485 /// recent local declaration instead. The chosen declaration will be the most
3486 /// recent declaration in any module that imports this one.
3487 static NamedDecl *getDeclForLocalLookup(NamedDecl *D) {
3488   for (Decl *Redecl = D; Redecl; Redecl = Redecl->getPreviousDecl())
3489     if (!Redecl->isFromASTFile())
3490       return cast<NamedDecl>(Redecl);
3491   return D;
3492 }
3493 
3494 namespace {
3495 // Trait used for the on-disk hash table used in the method pool.
3496 class ASTDeclContextNameLookupTrait {
3497   ASTWriter &Writer;
3498 
3499 public:
3500   typedef DeclarationName key_type;
3501   typedef key_type key_type_ref;
3502 
3503   typedef DeclContext::lookup_result data_type;
3504   typedef const data_type& data_type_ref;
3505 
3506   typedef unsigned hash_value_type;
3507   typedef unsigned offset_type;
3508 
3509   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3510 
3511   hash_value_type ComputeHash(DeclarationName Name) {
3512     llvm::FoldingSetNodeID ID;
3513     ID.AddInteger(Name.getNameKind());
3514 
3515     switch (Name.getNameKind()) {
3516     case DeclarationName::Identifier:
3517       ID.AddString(Name.getAsIdentifierInfo()->getName());
3518       break;
3519     case DeclarationName::ObjCZeroArgSelector:
3520     case DeclarationName::ObjCOneArgSelector:
3521     case DeclarationName::ObjCMultiArgSelector:
3522       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3523       break;
3524     case DeclarationName::CXXConstructorName:
3525     case DeclarationName::CXXDestructorName:
3526     case DeclarationName::CXXConversionFunctionName:
3527       break;
3528     case DeclarationName::CXXOperatorName:
3529       ID.AddInteger(Name.getCXXOverloadedOperator());
3530       break;
3531     case DeclarationName::CXXLiteralOperatorName:
3532       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3533     case DeclarationName::CXXUsingDirective:
3534       break;
3535     }
3536 
3537     return ID.ComputeHash();
3538   }
3539 
3540   std::pair<unsigned,unsigned>
3541     EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3542                       data_type_ref Lookup) {
3543     using namespace llvm::support;
3544     endian::Writer<little> LE(Out);
3545     unsigned KeyLen = 1;
3546     switch (Name.getNameKind()) {
3547     case DeclarationName::Identifier:
3548     case DeclarationName::ObjCZeroArgSelector:
3549     case DeclarationName::ObjCOneArgSelector:
3550     case DeclarationName::ObjCMultiArgSelector:
3551     case DeclarationName::CXXLiteralOperatorName:
3552       KeyLen += 4;
3553       break;
3554     case DeclarationName::CXXOperatorName:
3555       KeyLen += 1;
3556       break;
3557     case DeclarationName::CXXConstructorName:
3558     case DeclarationName::CXXDestructorName:
3559     case DeclarationName::CXXConversionFunctionName:
3560     case DeclarationName::CXXUsingDirective:
3561       break;
3562     }
3563     LE.write<uint16_t>(KeyLen);
3564 
3565     // 2 bytes for num of decls and 4 for each DeclID.
3566     unsigned DataLen = 2 + 4 * Lookup.size();
3567     LE.write<uint16_t>(DataLen);
3568 
3569     return std::make_pair(KeyLen, DataLen);
3570   }
3571 
3572   void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3573     using namespace llvm::support;
3574     endian::Writer<little> LE(Out);
3575     LE.write<uint8_t>(Name.getNameKind());
3576     switch (Name.getNameKind()) {
3577     case DeclarationName::Identifier:
3578       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3579       return;
3580     case DeclarationName::ObjCZeroArgSelector:
3581     case DeclarationName::ObjCOneArgSelector:
3582     case DeclarationName::ObjCMultiArgSelector:
3583       LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
3584       return;
3585     case DeclarationName::CXXOperatorName:
3586       assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3587              "Invalid operator?");
3588       LE.write<uint8_t>(Name.getCXXOverloadedOperator());
3589       return;
3590     case DeclarationName::CXXLiteralOperatorName:
3591       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3592       return;
3593     case DeclarationName::CXXConstructorName:
3594     case DeclarationName::CXXDestructorName:
3595     case DeclarationName::CXXConversionFunctionName:
3596     case DeclarationName::CXXUsingDirective:
3597       return;
3598     }
3599 
3600     llvm_unreachable("Invalid name kind?");
3601   }
3602 
3603   void EmitData(raw_ostream& Out, key_type_ref,
3604                 data_type Lookup, unsigned DataLen) {
3605     using namespace llvm::support;
3606     endian::Writer<little> LE(Out);
3607     uint64_t Start = Out.tell(); (void)Start;
3608     LE.write<uint16_t>(Lookup.size());
3609     for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3610          I != E; ++I)
3611       LE.write<uint32_t>(Writer.GetDeclRef(getDeclForLocalLookup(*I)));
3612 
3613     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3614   }
3615 };
3616 } // end anonymous namespace
3617 
3618 template<typename Visitor>
3619 static void visitLocalLookupResults(const DeclContext *ConstDC,
3620                                     bool NeedToReconcileExternalVisibleStorage,
3621                                     Visitor AddLookupResult) {
3622   // FIXME: We need to build the lookups table, which is logically const.
3623   DeclContext *DC = const_cast<DeclContext*>(ConstDC);
3624   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3625 
3626   SmallVector<DeclarationName, 16> ExternalNames;
3627   for (auto &Lookup : *DC->buildLookup()) {
3628     if (Lookup.second.hasExternalDecls() ||
3629         NeedToReconcileExternalVisibleStorage) {
3630       // We don't know for sure what declarations are found by this name,
3631       // because the external source might have a different set from the set
3632       // that are in the lookup map, and we can't update it now without
3633       // risking invalidating our lookup iterator. So add it to a queue to
3634       // deal with later.
3635       ExternalNames.push_back(Lookup.first);
3636       continue;
3637     }
3638 
3639     AddLookupResult(Lookup.first, Lookup.second.getLookupResult());
3640   }
3641 
3642   // Add the names we needed to defer. Note, this shouldn't add any new decls
3643   // to the list we need to serialize: any new declarations we find here should
3644   // be imported from an external source.
3645   // FIXME: What if the external source isn't an ASTReader?
3646   for (const auto &Name : ExternalNames)
3647     AddLookupResult(Name, DC->lookup(Name));
3648 }
3649 
3650 void ASTWriter::AddUpdatedDeclContext(const DeclContext *DC) {
3651   if (UpdatedDeclContexts.insert(DC) && WritingAST) {
3652     // Ensure we emit all the visible declarations.
3653     visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3654                             [&](DeclarationName Name,
3655                                 DeclContext::lookup_const_result Result) {
3656       for (auto *Decl : Result)
3657         GetDeclRef(getDeclForLocalLookup(Decl));
3658     });
3659   }
3660 }
3661 
3662 uint32_t
3663 ASTWriter::GenerateNameLookupTable(const DeclContext *DC,
3664                                    llvm::SmallVectorImpl<char> &LookupTable) {
3665   assert(!DC->LookupPtr.getInt() && "must call buildLookups first");
3666 
3667   llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
3668       Generator;
3669   ASTDeclContextNameLookupTrait Trait(*this);
3670 
3671   // Create the on-disk hash table representation.
3672   DeclarationName ConstructorName;
3673   DeclarationName ConversionName;
3674   SmallVector<NamedDecl *, 8> ConstructorDecls;
3675   SmallVector<NamedDecl *, 4> ConversionDecls;
3676 
3677   visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3678                           [&](DeclarationName Name,
3679                               DeclContext::lookup_result Result) {
3680     if (Result.empty())
3681       return;
3682 
3683     // Different DeclarationName values of certain kinds are mapped to
3684     // identical serialized keys, because we don't want to use type
3685     // identifiers in the keys (since type ids are local to the module).
3686     switch (Name.getNameKind()) {
3687     case DeclarationName::CXXConstructorName:
3688       // There may be different CXXConstructorName DeclarationName values
3689       // in a DeclContext because a UsingDecl that inherits constructors
3690       // has the DeclarationName of the inherited constructors.
3691       if (!ConstructorName)
3692         ConstructorName = Name;
3693       ConstructorDecls.append(Result.begin(), Result.end());
3694       return;
3695 
3696     case DeclarationName::CXXConversionFunctionName:
3697       if (!ConversionName)
3698         ConversionName = Name;
3699       ConversionDecls.append(Result.begin(), Result.end());
3700       return;
3701 
3702     default:
3703       break;
3704     }
3705 
3706     Generator.insert(Name, Result, Trait);
3707   });
3708 
3709   // Add the constructors.
3710   if (!ConstructorDecls.empty()) {
3711     Generator.insert(ConstructorName,
3712                      DeclContext::lookup_result(ConstructorDecls.begin(),
3713                                                 ConstructorDecls.end()),
3714                      Trait);
3715   }
3716 
3717   // Add the conversion functions.
3718   if (!ConversionDecls.empty()) {
3719     Generator.insert(ConversionName,
3720                      DeclContext::lookup_result(ConversionDecls.begin(),
3721                                                 ConversionDecls.end()),
3722                      Trait);
3723   }
3724 
3725   // Create the on-disk hash table in a buffer.
3726   llvm::raw_svector_ostream Out(LookupTable);
3727   // Make sure that no bucket is at offset 0
3728   using namespace llvm::support;
3729   endian::Writer<little>(Out).write<uint32_t>(0);
3730   return Generator.Emit(Out, Trait);
3731 }
3732 
3733 /// \brief Write the block containing all of the declaration IDs
3734 /// visible from the given DeclContext.
3735 ///
3736 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3737 /// bitstream, or 0 if no block was written.
3738 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3739                                                  DeclContext *DC) {
3740   if (DC->getPrimaryContext() != DC)
3741     return 0;
3742 
3743   // Since there is no name lookup into functions or methods, don't bother to
3744   // build a visible-declarations table for these entities.
3745   if (DC->isFunctionOrMethod())
3746     return 0;
3747 
3748   // If not in C++, we perform name lookup for the translation unit via the
3749   // IdentifierInfo chains, don't bother to build a visible-declarations table.
3750   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3751     return 0;
3752 
3753   // Serialize the contents of the mapping used for lookup. Note that,
3754   // although we have two very different code paths, the serialized
3755   // representation is the same for both cases: a declaration name,
3756   // followed by a size, followed by references to the visible
3757   // declarations that have that name.
3758   uint64_t Offset = Stream.GetCurrentBitNo();
3759   StoredDeclsMap *Map = DC->buildLookup();
3760   if (!Map || Map->empty())
3761     return 0;
3762 
3763   // Create the on-disk hash table in a buffer.
3764   SmallString<4096> LookupTable;
3765   uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3766 
3767   // Write the lookup table
3768   RecordData Record;
3769   Record.push_back(DECL_CONTEXT_VISIBLE);
3770   Record.push_back(BucketOffset);
3771   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3772                             LookupTable.str());
3773   ++NumVisibleDeclContexts;
3774   return Offset;
3775 }
3776 
3777 /// \brief Write an UPDATE_VISIBLE block for the given context.
3778 ///
3779 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3780 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3781 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3782 /// enumeration members (in C++11).
3783 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3784   StoredDeclsMap *Map = DC->getLookupPtr();
3785   if (!Map || Map->empty())
3786     return;
3787 
3788   // Create the on-disk hash table in a buffer.
3789   SmallString<4096> LookupTable;
3790   uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3791 
3792   // Write the lookup table
3793   RecordData Record;
3794   Record.push_back(UPDATE_VISIBLE);
3795   Record.push_back(getDeclID(cast<Decl>(DC)));
3796   Record.push_back(BucketOffset);
3797   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3798 }
3799 
3800 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3801 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3802   RecordData Record;
3803   Record.push_back(Opts.fp_contract);
3804   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3805 }
3806 
3807 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3808 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3809   if (!SemaRef.Context.getLangOpts().OpenCL)
3810     return;
3811 
3812   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3813   RecordData Record;
3814 #define OPENCLEXT(nm)  Record.push_back(Opts.nm);
3815 #include "clang/Basic/OpenCLExtensions.def"
3816   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3817 }
3818 
3819 void ASTWriter::WriteRedeclarations() {
3820   RecordData LocalRedeclChains;
3821   SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3822 
3823   for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3824     Decl *First = Redeclarations[I];
3825     assert(First->isFirstDecl() && "Not the first declaration?");
3826 
3827     Decl *MostRecent = First->getMostRecentDecl();
3828 
3829     // If we only have a single declaration, there is no point in storing
3830     // a redeclaration chain.
3831     if (First == MostRecent)
3832       continue;
3833 
3834     unsigned Offset = LocalRedeclChains.size();
3835     unsigned Size = 0;
3836     LocalRedeclChains.push_back(0); // Placeholder for the size.
3837 
3838     // Collect the set of local redeclarations of this declaration.
3839     for (Decl *Prev = MostRecent; Prev != First;
3840          Prev = Prev->getPreviousDecl()) {
3841       if (!Prev->isFromASTFile()) {
3842         AddDeclRef(Prev, LocalRedeclChains);
3843         ++Size;
3844       }
3845     }
3846 
3847     if (!First->isFromASTFile() && Chain) {
3848       Decl *FirstFromAST = MostRecent;
3849       for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3850         if (Prev->isFromASTFile())
3851           FirstFromAST = Prev;
3852       }
3853 
3854       // FIXME: Do we need to do this for the first declaration from each
3855       // redeclaration chain that was merged into this one?
3856       Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3857     }
3858 
3859     LocalRedeclChains[Offset] = Size;
3860 
3861     // Reverse the set of local redeclarations, so that we store them in
3862     // order (since we found them in reverse order).
3863     std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3864 
3865     // Add the mapping from the first ID from the AST to the set of local
3866     // declarations.
3867     LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3868     LocalRedeclsMap.push_back(Info);
3869 
3870     assert(N == Redeclarations.size() &&
3871            "Deserialized a declaration we shouldn't have");
3872   }
3873 
3874   if (LocalRedeclChains.empty())
3875     return;
3876 
3877   // Sort the local redeclarations map by the first declaration ID,
3878   // since the reader will be performing binary searches on this information.
3879   llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3880 
3881   // Emit the local redeclarations map.
3882   using namespace llvm;
3883   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3884   Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3885   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3886   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3887   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3888 
3889   RecordData Record;
3890   Record.push_back(LOCAL_REDECLARATIONS_MAP);
3891   Record.push_back(LocalRedeclsMap.size());
3892   Stream.EmitRecordWithBlob(AbbrevID, Record,
3893     reinterpret_cast<char*>(LocalRedeclsMap.data()),
3894     LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3895 
3896   // Emit the redeclaration chains.
3897   Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3898 }
3899 
3900 void ASTWriter::WriteObjCCategories() {
3901   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3902   RecordData Categories;
3903 
3904   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3905     unsigned Size = 0;
3906     unsigned StartIndex = Categories.size();
3907 
3908     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3909 
3910     // Allocate space for the size.
3911     Categories.push_back(0);
3912 
3913     // Add the categories.
3914     for (ObjCInterfaceDecl::known_categories_iterator
3915            Cat = Class->known_categories_begin(),
3916            CatEnd = Class->known_categories_end();
3917          Cat != CatEnd; ++Cat, ++Size) {
3918       assert(getDeclID(*Cat) != 0 && "Bogus category");
3919       AddDeclRef(*Cat, Categories);
3920     }
3921 
3922     // Update the size.
3923     Categories[StartIndex] = Size;
3924 
3925     // Record this interface -> category map.
3926     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3927     CategoriesMap.push_back(CatInfo);
3928   }
3929 
3930   // Sort the categories map by the definition ID, since the reader will be
3931   // performing binary searches on this information.
3932   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3933 
3934   // Emit the categories map.
3935   using namespace llvm;
3936   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3937   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3938   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3939   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3940   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3941 
3942   RecordData Record;
3943   Record.push_back(OBJC_CATEGORIES_MAP);
3944   Record.push_back(CategoriesMap.size());
3945   Stream.EmitRecordWithBlob(AbbrevID, Record,
3946                             reinterpret_cast<char*>(CategoriesMap.data()),
3947                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3948 
3949   // Emit the category lists.
3950   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3951 }
3952 
3953 void ASTWriter::WriteMergedDecls() {
3954   if (!Chain || Chain->MergedDecls.empty())
3955     return;
3956 
3957   RecordData Record;
3958   for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3959                                         IEnd = Chain->MergedDecls.end();
3960        I != IEnd; ++I) {
3961     DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3962                                               : GetDeclRef(I->first);
3963     assert(CanonID && "Merged declaration not known?");
3964 
3965     Record.push_back(CanonID);
3966     Record.push_back(I->second.size());
3967     Record.append(I->second.begin(), I->second.end());
3968   }
3969   Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3970 }
3971 
3972 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3973   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3974 
3975   if (LPTMap.empty())
3976     return;
3977 
3978   RecordData Record;
3979   for (Sema::LateParsedTemplateMapT::iterator It = LPTMap.begin(),
3980                                               ItEnd = LPTMap.end();
3981        It != ItEnd; ++It) {
3982     LateParsedTemplate *LPT = It->second;
3983     AddDeclRef(It->first, Record);
3984     AddDeclRef(LPT->D, Record);
3985     Record.push_back(LPT->Toks.size());
3986 
3987     for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
3988                                 TokEnd = LPT->Toks.end();
3989          TokIt != TokEnd; ++TokIt) {
3990       AddToken(*TokIt, Record);
3991     }
3992   }
3993   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3994 }
3995 
3996 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
3997 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3998   RecordData Record;
3999   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4000   AddSourceLocation(PragmaLoc, Record);
4001   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4002 }
4003 
4004 //===----------------------------------------------------------------------===//
4005 // General Serialization Routines
4006 //===----------------------------------------------------------------------===//
4007 
4008 /// \brief Write a record containing the given attributes.
4009 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
4010                                 RecordDataImpl &Record) {
4011   Record.push_back(Attrs.size());
4012   for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
4013                                         e = Attrs.end(); i != e; ++i){
4014     const Attr *A = *i;
4015     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4016     AddSourceRange(A->getRange(), Record);
4017 
4018 #include "clang/Serialization/AttrPCHWrite.inc"
4019 
4020   }
4021 }
4022 
4023 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4024   AddSourceLocation(Tok.getLocation(), Record);
4025   Record.push_back(Tok.getLength());
4026 
4027   // FIXME: When reading literal tokens, reconstruct the literal pointer
4028   // if it is needed.
4029   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4030   // FIXME: Should translate token kind to a stable encoding.
4031   Record.push_back(Tok.getKind());
4032   // FIXME: Should translate token flags to a stable encoding.
4033   Record.push_back(Tok.getFlags());
4034 }
4035 
4036 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4037   Record.push_back(Str.size());
4038   Record.insert(Record.end(), Str.begin(), Str.end());
4039 }
4040 
4041 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4042                                 RecordDataImpl &Record) {
4043   Record.push_back(Version.getMajor());
4044   if (Optional<unsigned> Minor = Version.getMinor())
4045     Record.push_back(*Minor + 1);
4046   else
4047     Record.push_back(0);
4048   if (Optional<unsigned> Subminor = Version.getSubminor())
4049     Record.push_back(*Subminor + 1);
4050   else
4051     Record.push_back(0);
4052 }
4053 
4054 /// \brief Note that the identifier II occurs at the given offset
4055 /// within the identifier table.
4056 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4057   IdentID ID = IdentifierIDs[II];
4058   // Only store offsets new to this AST file. Other identifier names are looked
4059   // up earlier in the chain and thus don't need an offset.
4060   if (ID >= FirstIdentID)
4061     IdentifierOffsets[ID - FirstIdentID] = Offset;
4062 }
4063 
4064 /// \brief Note that the selector Sel occurs at the given offset
4065 /// within the method pool/selector table.
4066 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4067   unsigned ID = SelectorIDs[Sel];
4068   assert(ID && "Unknown selector");
4069   // Don't record offsets for selectors that are also available in a different
4070   // file.
4071   if (ID < FirstSelectorID)
4072     return;
4073   SelectorOffsets[ID - FirstSelectorID] = Offset;
4074 }
4075 
4076 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
4077     : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
4078       WritingModule(nullptr), WritingAST(false),
4079       DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false),
4080       FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
4081       FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
4082       FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
4083       FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
4084       FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
4085       NextSubmoduleID(FirstSubmoduleID),
4086       FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4087       CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4088       NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
4089       NextCXXBaseSpecifiersID(1), TypeExtQualAbbrev(0),
4090       TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
4091       DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
4092       UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
4093       DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
4094       DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4095       CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
4096       ExprImplicitCastAbbrev(0) {}
4097 
4098 ASTWriter::~ASTWriter() {
4099   llvm::DeleteContainerSeconds(FileDeclIDs);
4100 }
4101 
4102 void ASTWriter::WriteAST(Sema &SemaRef,
4103                          const std::string &OutputFile,
4104                          Module *WritingModule, StringRef isysroot,
4105                          bool hasErrors) {
4106   WritingAST = true;
4107 
4108   ASTHasCompilerErrors = hasErrors;
4109 
4110   // Emit the file header.
4111   Stream.Emit((unsigned)'C', 8);
4112   Stream.Emit((unsigned)'P', 8);
4113   Stream.Emit((unsigned)'C', 8);
4114   Stream.Emit((unsigned)'H', 8);
4115 
4116   WriteBlockInfoBlock();
4117 
4118   Context = &SemaRef.Context;
4119   PP = &SemaRef.PP;
4120   this->WritingModule = WritingModule;
4121   WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4122   Context = nullptr;
4123   PP = nullptr;
4124   this->WritingModule = nullptr;
4125 
4126   WritingAST = false;
4127 }
4128 
4129 template<typename Vector>
4130 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4131                                ASTWriter::RecordData &Record) {
4132   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4133        I != E; ++I) {
4134     Writer.AddDeclRef(*I, Record);
4135   }
4136 }
4137 
4138 void ASTWriter::WriteASTCore(Sema &SemaRef,
4139                              StringRef isysroot,
4140                              const std::string &OutputFile,
4141                              Module *WritingModule) {
4142   using namespace llvm;
4143 
4144   bool isModule = WritingModule != nullptr;
4145 
4146   // Make sure that the AST reader knows to finalize itself.
4147   if (Chain)
4148     Chain->finalizeForWriting();
4149 
4150   ASTContext &Context = SemaRef.Context;
4151   Preprocessor &PP = SemaRef.PP;
4152 
4153   // Set up predefined declaration IDs.
4154   DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
4155   if (Context.ObjCIdDecl)
4156     DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
4157   if (Context.ObjCSelDecl)
4158     DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
4159   if (Context.ObjCClassDecl)
4160     DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
4161   if (Context.ObjCProtocolClassDecl)
4162     DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
4163   if (Context.Int128Decl)
4164     DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
4165   if (Context.UInt128Decl)
4166     DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
4167   if (Context.ObjCInstanceTypeDecl)
4168     DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
4169   if (Context.BuiltinVaListDecl)
4170     DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
4171 
4172   if (!Chain) {
4173     // Make sure that we emit IdentifierInfos (and any attached
4174     // declarations) for builtins. We don't need to do this when we're
4175     // emitting chained PCH files, because all of the builtins will be
4176     // in the original PCH file.
4177     // FIXME: Modules won't like this at all.
4178     IdentifierTable &Table = PP.getIdentifierTable();
4179     SmallVector<const char *, 32> BuiltinNames;
4180     if (!Context.getLangOpts().NoBuiltin) {
4181       Context.BuiltinInfo.GetBuiltinNames(BuiltinNames);
4182     }
4183     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
4184       getIdentifierRef(&Table.get(BuiltinNames[I]));
4185   }
4186 
4187   // If there are any out-of-date identifiers, bring them up to date.
4188   if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
4189     // Find out-of-date identifiers.
4190     SmallVector<IdentifierInfo *, 4> OutOfDate;
4191     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4192                                 IDEnd = PP.getIdentifierTable().end();
4193          ID != IDEnd; ++ID) {
4194       if (ID->second->isOutOfDate())
4195         OutOfDate.push_back(ID->second);
4196     }
4197 
4198     // Update the out-of-date identifiers.
4199     for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
4200       ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
4201     }
4202   }
4203 
4204   // If we saw any DeclContext updates before we started writing the AST file,
4205   // make sure all visible decls in those DeclContexts are written out.
4206   if (!UpdatedDeclContexts.empty()) {
4207     auto OldUpdatedDeclContexts = std::move(UpdatedDeclContexts);
4208     UpdatedDeclContexts.clear();
4209     for (auto *DC : OldUpdatedDeclContexts)
4210       AddUpdatedDeclContext(DC);
4211   }
4212 
4213   // Build a record containing all of the tentative definitions in this file, in
4214   // TentativeDefinitions order.  Generally, this record will be empty for
4215   // headers.
4216   RecordData TentativeDefinitions;
4217   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4218 
4219   // Build a record containing all of the file scoped decls in this file.
4220   RecordData UnusedFileScopedDecls;
4221   if (!isModule)
4222     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4223                        UnusedFileScopedDecls);
4224 
4225   // Build a record containing all of the delegating constructors we still need
4226   // to resolve.
4227   RecordData DelegatingCtorDecls;
4228   if (!isModule)
4229     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4230 
4231   // Write the set of weak, undeclared identifiers. We always write the
4232   // entire table, since later PCH files in a PCH chain are only interested in
4233   // the results at the end of the chain.
4234   RecordData WeakUndeclaredIdentifiers;
4235   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
4236     for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
4237          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
4238          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
4239       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
4240       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
4241       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
4242       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
4243     }
4244   }
4245 
4246   // Build a record containing all of the locally-scoped extern "C"
4247   // declarations in this header file. Generally, this record will be
4248   // empty.
4249   RecordData LocallyScopedExternCDecls;
4250   // FIXME: This is filling in the AST file in densemap order which is
4251   // nondeterminstic!
4252   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
4253          TD = SemaRef.LocallyScopedExternCDecls.begin(),
4254          TDEnd = SemaRef.LocallyScopedExternCDecls.end();
4255        TD != TDEnd; ++TD) {
4256     if (!TD->second->isFromASTFile())
4257       AddDeclRef(TD->second, LocallyScopedExternCDecls);
4258   }
4259 
4260   // Build a record containing all of the ext_vector declarations.
4261   RecordData ExtVectorDecls;
4262   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4263 
4264   // Build a record containing all of the VTable uses information.
4265   RecordData VTableUses;
4266   if (!SemaRef.VTableUses.empty()) {
4267     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4268       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4269       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4270       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4271     }
4272   }
4273 
4274   // Build a record containing all of dynamic classes declarations.
4275   RecordData DynamicClasses;
4276   AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
4277 
4278   // Build a record containing all of pending implicit instantiations.
4279   RecordData PendingInstantiations;
4280   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
4281          I = SemaRef.PendingInstantiations.begin(),
4282          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
4283     AddDeclRef(I->first, PendingInstantiations);
4284     AddSourceLocation(I->second, PendingInstantiations);
4285   }
4286   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4287          "There are local ones at end of translation unit!");
4288 
4289   // Build a record containing some declaration references.
4290   RecordData SemaDeclRefs;
4291   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4292     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4293     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4294   }
4295 
4296   RecordData CUDASpecialDeclRefs;
4297   if (Context.getcudaConfigureCallDecl()) {
4298     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4299   }
4300 
4301   // Build a record containing all of the known namespaces.
4302   RecordData KnownNamespaces;
4303   for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4304             I = SemaRef.KnownNamespaces.begin(),
4305          IEnd = SemaRef.KnownNamespaces.end();
4306        I != IEnd; ++I) {
4307     if (!I->second)
4308       AddDeclRef(I->first, KnownNamespaces);
4309   }
4310 
4311   // Build a record of all used, undefined objects that require definitions.
4312   RecordData UndefinedButUsed;
4313 
4314   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4315   SemaRef.getUndefinedButUsed(Undefined);
4316   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4317          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
4318     AddDeclRef(I->first, UndefinedButUsed);
4319     AddSourceLocation(I->second, UndefinedButUsed);
4320   }
4321 
4322   // Write the control block
4323   WriteControlBlock(PP, Context, isysroot, OutputFile);
4324 
4325   // Write the remaining AST contents.
4326   RecordData Record;
4327   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4328 
4329   // This is so that older clang versions, before the introduction
4330   // of the control block, can read and reject the newer PCH format.
4331   Record.clear();
4332   Record.push_back(VERSION_MAJOR);
4333   Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4334 
4335   // Create a lexical update block containing all of the declarations in the
4336   // translation unit that do not come from other AST files.
4337   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4338   SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
4339   for (const auto *I : TU->noload_decls()) {
4340     if (!I->isFromASTFile())
4341       NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
4342   }
4343 
4344   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4345   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4346   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4347   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4348   Record.clear();
4349   Record.push_back(TU_UPDATE_LEXICAL);
4350   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4351                             data(NewGlobalDecls));
4352 
4353   // And a visible updates block for the translation unit.
4354   Abv = new llvm::BitCodeAbbrev();
4355   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4356   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4357   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4358   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4359   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4360   WriteDeclContextVisibleUpdate(TU);
4361 
4362   // If the translation unit has an anonymous namespace, and we don't already
4363   // have an update block for it, write it as an update block.
4364   // FIXME: Why do we not do this if there's already an update block?
4365   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4366     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4367     if (Record.empty())
4368       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4369   }
4370 
4371   // Add update records for all mangling numbers and static local numbers.
4372   // These aren't really update records, but this is a convenient way of
4373   // tagging this rare extra data onto the declarations.
4374   for (const auto &Number : Context.MangleNumbers)
4375     if (!Number.first->isFromASTFile())
4376       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4377                                                      Number.second));
4378   for (const auto &Number : Context.StaticLocalNumbers)
4379     if (!Number.first->isFromASTFile())
4380       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4381                                                      Number.second));
4382 
4383   // Make sure visible decls, added to DeclContexts previously loaded from
4384   // an AST file, are registered for serialization.
4385   for (SmallVectorImpl<const Decl *>::iterator
4386          I = UpdatingVisibleDecls.begin(),
4387          E = UpdatingVisibleDecls.end(); I != E; ++I) {
4388     GetDeclRef(*I);
4389   }
4390 
4391   // Make sure all decls associated with an identifier are registered for
4392   // serialization.
4393   for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4394                               IDEnd = PP.getIdentifierTable().end();
4395        ID != IDEnd; ++ID) {
4396     const IdentifierInfo *II = ID->second;
4397     if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) {
4398       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4399                                      DEnd = SemaRef.IdResolver.end();
4400            D != DEnd; ++D) {
4401         GetDeclRef(*D);
4402       }
4403     }
4404   }
4405 
4406   // Form the record of special types.
4407   RecordData SpecialTypes;
4408   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4409   AddTypeRef(Context.getFILEType(), SpecialTypes);
4410   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4411   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4412   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4413   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4414   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4415   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4416 
4417   if (Chain) {
4418     // Write the mapping information describing our module dependencies and how
4419     // each of those modules were mapped into our own offset/ID space, so that
4420     // the reader can build the appropriate mapping to its own offset/ID space.
4421     // The map consists solely of a blob with the following format:
4422     // *(module-name-len:i16 module-name:len*i8
4423     //   source-location-offset:i32
4424     //   identifier-id:i32
4425     //   preprocessed-entity-id:i32
4426     //   macro-definition-id:i32
4427     //   submodule-id:i32
4428     //   selector-id:i32
4429     //   declaration-id:i32
4430     //   c++-base-specifiers-id:i32
4431     //   type-id:i32)
4432     //
4433     llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4434     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4435     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4436     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4437     SmallString<2048> Buffer;
4438     {
4439       llvm::raw_svector_ostream Out(Buffer);
4440       for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
4441                                            MEnd = Chain->ModuleMgr.end();
4442            M != MEnd; ++M) {
4443         using namespace llvm::support;
4444         endian::Writer<little> LE(Out);
4445         StringRef FileName = (*M)->FileName;
4446         LE.write<uint16_t>(FileName.size());
4447         Out.write(FileName.data(), FileName.size());
4448         LE.write<uint32_t>((*M)->SLocEntryBaseOffset);
4449         LE.write<uint32_t>((*M)->BaseIdentifierID);
4450         LE.write<uint32_t>((*M)->BaseMacroID);
4451         LE.write<uint32_t>((*M)->BasePreprocessedEntityID);
4452         LE.write<uint32_t>((*M)->BaseSubmoduleID);
4453         LE.write<uint32_t>((*M)->BaseSelectorID);
4454         LE.write<uint32_t>((*M)->BaseDeclID);
4455         LE.write<uint32_t>((*M)->BaseTypeIndex);
4456       }
4457     }
4458     Record.clear();
4459     Record.push_back(MODULE_OFFSET_MAP);
4460     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4461                               Buffer.data(), Buffer.size());
4462   }
4463 
4464   RecordData DeclUpdatesOffsetsRecord;
4465 
4466   // Keep writing types, declarations, and declaration update records
4467   // until we've emitted all of them.
4468   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4469   WriteTypeAbbrevs();
4470   WriteDeclAbbrevs();
4471   for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4472                                   E = DeclsToRewrite.end();
4473        I != E; ++I)
4474     DeclTypesToEmit.push(const_cast<Decl*>(*I));
4475   do {
4476     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4477     while (!DeclTypesToEmit.empty()) {
4478       DeclOrType DOT = DeclTypesToEmit.front();
4479       DeclTypesToEmit.pop();
4480       if (DOT.isType())
4481         WriteType(DOT.getType());
4482       else
4483         WriteDecl(Context, DOT.getDecl());
4484     }
4485   } while (!DeclUpdates.empty());
4486   Stream.ExitBlock();
4487 
4488   DoneWritingDeclsAndTypes = true;
4489 
4490   // These things can only be done once we've written out decls and types.
4491   WriteTypeDeclOffsets();
4492   if (!DeclUpdatesOffsetsRecord.empty())
4493     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4494   WriteCXXBaseSpecifiersOffsets();
4495   WriteFileDeclIDsMap();
4496   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
4497 
4498   WriteComments();
4499   WritePreprocessor(PP, isModule);
4500   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
4501   WriteSelectors(SemaRef);
4502   WriteReferencedSelectorsPool(SemaRef);
4503   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4504   WriteFPPragmaOptions(SemaRef.getFPOptions());
4505   WriteOpenCLExtensions(SemaRef);
4506   WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4507 
4508   // If we're emitting a module, write out the submodule information.
4509   if (WritingModule)
4510     WriteSubmodules(WritingModule);
4511 
4512   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4513 
4514   // Write the record containing external, unnamed definitions.
4515   if (!EagerlyDeserializedDecls.empty())
4516     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4517 
4518   // Write the record containing tentative definitions.
4519   if (!TentativeDefinitions.empty())
4520     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4521 
4522   // Write the record containing unused file scoped decls.
4523   if (!UnusedFileScopedDecls.empty())
4524     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4525 
4526   // Write the record containing weak undeclared identifiers.
4527   if (!WeakUndeclaredIdentifiers.empty())
4528     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4529                       WeakUndeclaredIdentifiers);
4530 
4531   // Write the record containing locally-scoped extern "C" definitions.
4532   if (!LocallyScopedExternCDecls.empty())
4533     Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4534                       LocallyScopedExternCDecls);
4535 
4536   // Write the record containing ext_vector type names.
4537   if (!ExtVectorDecls.empty())
4538     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4539 
4540   // Write the record containing VTable uses information.
4541   if (!VTableUses.empty())
4542     Stream.EmitRecord(VTABLE_USES, VTableUses);
4543 
4544   // Write the record containing dynamic classes declarations.
4545   if (!DynamicClasses.empty())
4546     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
4547 
4548   // Write the record containing pending implicit instantiations.
4549   if (!PendingInstantiations.empty())
4550     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4551 
4552   // Write the record containing declaration references of Sema.
4553   if (!SemaDeclRefs.empty())
4554     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4555 
4556   // Write the record containing CUDA-specific declaration references.
4557   if (!CUDASpecialDeclRefs.empty())
4558     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4559 
4560   // Write the delegating constructors.
4561   if (!DelegatingCtorDecls.empty())
4562     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4563 
4564   // Write the known namespaces.
4565   if (!KnownNamespaces.empty())
4566     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4567 
4568   // Write the undefined internal functions and variables, and inline functions.
4569   if (!UndefinedButUsed.empty())
4570     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4571 
4572   // Write the visible updates to DeclContexts.
4573   for (auto *DC : UpdatedDeclContexts)
4574     WriteDeclContextVisibleUpdate(DC);
4575 
4576   if (!WritingModule) {
4577     // Write the submodules that were imported, if any.
4578     struct ModuleInfo {
4579       uint64_t ID;
4580       Module *M;
4581       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4582     };
4583     llvm::SmallVector<ModuleInfo, 64> Imports;
4584     for (const auto *I : Context.local_imports()) {
4585       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4586       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4587                          I->getImportedModule()));
4588     }
4589 
4590     if (!Imports.empty()) {
4591       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4592         return A.ID < B.ID;
4593       };
4594 
4595       // Sort and deduplicate module IDs.
4596       std::sort(Imports.begin(), Imports.end(), Cmp);
4597       Imports.erase(std::unique(Imports.begin(), Imports.end(), Cmp),
4598                     Imports.end());
4599 
4600       RecordData ImportedModules;
4601       for (const auto &Import : Imports) {
4602         ImportedModules.push_back(Import.ID);
4603         // FIXME: If the module has macros imported then later has declarations
4604         // imported, this location won't be the right one as a location for the
4605         // declaration imports.
4606         AddSourceLocation(Import.M->MacroVisibilityLoc, ImportedModules);
4607       }
4608 
4609       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4610     }
4611   }
4612 
4613   WriteDeclReplacementsBlock();
4614   WriteRedeclarations();
4615   WriteMergedDecls();
4616   WriteObjCCategories();
4617   WriteLateParsedTemplates(SemaRef);
4618   if(!WritingModule)
4619     WriteOptimizePragmaOptions(SemaRef);
4620 
4621   // Some simple statistics
4622   Record.clear();
4623   Record.push_back(NumStatements);
4624   Record.push_back(NumMacros);
4625   Record.push_back(NumLexicalDeclContexts);
4626   Record.push_back(NumVisibleDeclContexts);
4627   Stream.EmitRecord(STATISTICS, Record);
4628   Stream.ExitBlock();
4629 }
4630 
4631 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4632   if (DeclUpdates.empty())
4633     return;
4634 
4635   DeclUpdateMap LocalUpdates;
4636   LocalUpdates.swap(DeclUpdates);
4637 
4638   for (auto &DeclUpdate : LocalUpdates) {
4639     const Decl *D = DeclUpdate.first;
4640     if (isRewritten(D))
4641       continue; // The decl will be written completely,no need to store updates.
4642 
4643     bool HasUpdatedBody = false;
4644     RecordData Record;
4645     for (auto &Update : DeclUpdate.second) {
4646       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4647 
4648       Record.push_back(Kind);
4649       switch (Kind) {
4650       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4651       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4652       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4653         assert(Update.getDecl() && "no decl to add?");
4654         Record.push_back(GetDeclRef(Update.getDecl()));
4655         break;
4656 
4657       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4658         // An updated body is emitted last, so that the reader doesn't need
4659         // to skip over the lazy body to reach statements for other records.
4660         Record.pop_back();
4661         HasUpdatedBody = true;
4662         break;
4663 
4664       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4665         AddSourceLocation(Update.getLoc(), Record);
4666         break;
4667 
4668       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4669         auto *RD = cast<CXXRecordDecl>(D);
4670         AddUpdatedDeclContext(RD->getPrimaryContext());
4671         AddCXXDefinitionData(RD, Record);
4672         Record.push_back(WriteDeclContextLexicalBlock(
4673             *Context, const_cast<CXXRecordDecl *>(RD)));
4674 
4675         // This state is sometimes updated by template instantiation, when we
4676         // switch from the specialization referring to the template declaration
4677         // to it referring to the template definition.
4678         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4679           Record.push_back(MSInfo->getTemplateSpecializationKind());
4680           AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4681         } else {
4682           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4683           Record.push_back(Spec->getTemplateSpecializationKind());
4684           AddSourceLocation(Spec->getPointOfInstantiation(), Record);
4685 
4686           // The instantiation might have been resolved to a partial
4687           // specialization. If so, record which one.
4688           auto From = Spec->getInstantiatedFrom();
4689           if (auto PartialSpec =
4690                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4691             Record.push_back(true);
4692             AddDeclRef(PartialSpec, Record);
4693             AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4694                                     Record);
4695           } else {
4696             Record.push_back(false);
4697           }
4698         }
4699         Record.push_back(RD->getTagKind());
4700         AddSourceLocation(RD->getLocation(), Record);
4701         AddSourceLocation(RD->getLocStart(), Record);
4702         AddSourceLocation(RD->getRBraceLoc(), Record);
4703 
4704         // Instantiation may change attributes; write them all out afresh.
4705         Record.push_back(D->hasAttrs());
4706         if (Record.back())
4707           WriteAttributes(ArrayRef<const Attr*>(D->getAttrs().begin(),
4708                                                 D->getAttrs().size()), Record);
4709 
4710         // FIXME: Ensure we don't get here for explicit instantiations.
4711         break;
4712       }
4713 
4714       case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4715         addExceptionSpec(
4716             *this,
4717             cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4718             Record);
4719         break;
4720 
4721       case UPD_CXX_DEDUCED_RETURN_TYPE:
4722         Record.push_back(GetOrCreateTypeID(Update.getType()));
4723         break;
4724 
4725       case UPD_DECL_MARKED_USED:
4726         break;
4727 
4728       case UPD_MANGLING_NUMBER:
4729       case UPD_STATIC_LOCAL_NUMBER:
4730         Record.push_back(Update.getNumber());
4731         break;
4732       }
4733     }
4734 
4735     if (HasUpdatedBody) {
4736       const FunctionDecl *Def = cast<FunctionDecl>(D);
4737       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4738       Record.push_back(Def->isInlined());
4739       AddSourceLocation(Def->getInnerLocStart(), Record);
4740       AddFunctionDefinition(Def, Record);
4741       if (auto *DD = dyn_cast<CXXDestructorDecl>(Def))
4742         Record.push_back(GetDeclRef(DD->getOperatorDelete()));
4743     }
4744 
4745     OffsetsRecord.push_back(GetDeclRef(D));
4746     OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4747 
4748     Stream.EmitRecord(DECL_UPDATES, Record);
4749 
4750     // Flush any statements that were written as part of this update record.
4751     FlushStmts();
4752 
4753     // Flush C++ base specifiers, if there are any.
4754     FlushCXXBaseSpecifiers();
4755   }
4756 }
4757 
4758 void ASTWriter::WriteDeclReplacementsBlock() {
4759   if (ReplacedDecls.empty())
4760     return;
4761 
4762   RecordData Record;
4763   for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4764          I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4765     Record.push_back(I->ID);
4766     Record.push_back(I->Offset);
4767     Record.push_back(I->Loc);
4768   }
4769   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4770 }
4771 
4772 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4773   Record.push_back(Loc.getRawEncoding());
4774 }
4775 
4776 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4777   AddSourceLocation(Range.getBegin(), Record);
4778   AddSourceLocation(Range.getEnd(), Record);
4779 }
4780 
4781 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4782   Record.push_back(Value.getBitWidth());
4783   const uint64_t *Words = Value.getRawData();
4784   Record.append(Words, Words + Value.getNumWords());
4785 }
4786 
4787 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4788   Record.push_back(Value.isUnsigned());
4789   AddAPInt(Value, Record);
4790 }
4791 
4792 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4793   AddAPInt(Value.bitcastToAPInt(), Record);
4794 }
4795 
4796 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4797   Record.push_back(getIdentifierRef(II));
4798 }
4799 
4800 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4801   if (!II)
4802     return 0;
4803 
4804   IdentID &ID = IdentifierIDs[II];
4805   if (ID == 0)
4806     ID = NextIdentID++;
4807   return ID;
4808 }
4809 
4810 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4811   // Don't emit builtin macros like __LINE__ to the AST file unless they
4812   // have been redefined by the header (in which case they are not
4813   // isBuiltinMacro).
4814   if (!MI || MI->isBuiltinMacro())
4815     return 0;
4816 
4817   MacroID &ID = MacroIDs[MI];
4818   if (ID == 0) {
4819     ID = NextMacroID++;
4820     MacroInfoToEmitData Info = { Name, MI, ID };
4821     MacroInfosToEmit.push_back(Info);
4822   }
4823   return ID;
4824 }
4825 
4826 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4827   if (!MI || MI->isBuiltinMacro())
4828     return 0;
4829 
4830   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4831   return MacroIDs[MI];
4832 }
4833 
4834 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4835   assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4836   return IdentMacroDirectivesOffsetMap[Name];
4837 }
4838 
4839 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4840   Record.push_back(getSelectorRef(SelRef));
4841 }
4842 
4843 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4844   if (Sel.getAsOpaquePtr() == nullptr) {
4845     return 0;
4846   }
4847 
4848   SelectorID SID = SelectorIDs[Sel];
4849   if (SID == 0 && Chain) {
4850     // This might trigger a ReadSelector callback, which will set the ID for
4851     // this selector.
4852     Chain->LoadSelector(Sel);
4853     SID = SelectorIDs[Sel];
4854   }
4855   if (SID == 0) {
4856     SID = NextSelectorID++;
4857     SelectorIDs[Sel] = SID;
4858   }
4859   return SID;
4860 }
4861 
4862 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4863   AddDeclRef(Temp->getDestructor(), Record);
4864 }
4865 
4866 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4867                                       CXXBaseSpecifier const *BasesEnd,
4868                                         RecordDataImpl &Record) {
4869   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4870   CXXBaseSpecifiersToWrite.push_back(
4871                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4872                                                         Bases, BasesEnd));
4873   Record.push_back(NextCXXBaseSpecifiersID++);
4874 }
4875 
4876 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4877                                            const TemplateArgumentLocInfo &Arg,
4878                                            RecordDataImpl &Record) {
4879   switch (Kind) {
4880   case TemplateArgument::Expression:
4881     AddStmt(Arg.getAsExpr());
4882     break;
4883   case TemplateArgument::Type:
4884     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4885     break;
4886   case TemplateArgument::Template:
4887     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4888     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4889     break;
4890   case TemplateArgument::TemplateExpansion:
4891     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4892     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4893     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4894     break;
4895   case TemplateArgument::Null:
4896   case TemplateArgument::Integral:
4897   case TemplateArgument::Declaration:
4898   case TemplateArgument::NullPtr:
4899   case TemplateArgument::Pack:
4900     // FIXME: Is this right?
4901     break;
4902   }
4903 }
4904 
4905 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4906                                        RecordDataImpl &Record) {
4907   AddTemplateArgument(Arg.getArgument(), Record);
4908 
4909   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4910     bool InfoHasSameExpr
4911       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4912     Record.push_back(InfoHasSameExpr);
4913     if (InfoHasSameExpr)
4914       return; // Avoid storing the same expr twice.
4915   }
4916   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4917                              Record);
4918 }
4919 
4920 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4921                                   RecordDataImpl &Record) {
4922   if (!TInfo) {
4923     AddTypeRef(QualType(), Record);
4924     return;
4925   }
4926 
4927   AddTypeLoc(TInfo->getTypeLoc(), Record);
4928 }
4929 
4930 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4931   AddTypeRef(TL.getType(), Record);
4932 
4933   TypeLocWriter TLW(*this, Record);
4934   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4935     TLW.Visit(TL);
4936 }
4937 
4938 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4939   Record.push_back(GetOrCreateTypeID(T));
4940 }
4941 
4942 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4943   assert(Context);
4944   return MakeTypeID(*Context, T,
4945               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4946 }
4947 
4948 TypeID ASTWriter::getTypeID(QualType T) const {
4949   assert(Context);
4950   return MakeTypeID(*Context, T,
4951               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4952 }
4953 
4954 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4955   if (T.isNull())
4956     return TypeIdx();
4957   assert(!T.getLocalFastQualifiers());
4958 
4959   TypeIdx &Idx = TypeIdxs[T];
4960   if (Idx.getIndex() == 0) {
4961     if (DoneWritingDeclsAndTypes) {
4962       assert(0 && "New type seen after serializing all the types to emit!");
4963       return TypeIdx();
4964     }
4965 
4966     // We haven't seen this type before. Assign it a new ID and put it
4967     // into the queue of types to emit.
4968     Idx = TypeIdx(NextTypeID++);
4969     DeclTypesToEmit.push(T);
4970   }
4971   return Idx;
4972 }
4973 
4974 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4975   if (T.isNull())
4976     return TypeIdx();
4977   assert(!T.getLocalFastQualifiers());
4978 
4979   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4980   assert(I != TypeIdxs.end() && "Type not emitted!");
4981   return I->second;
4982 }
4983 
4984 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4985   Record.push_back(GetDeclRef(D));
4986 }
4987 
4988 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4989   assert(WritingAST && "Cannot request a declaration ID before AST writing");
4990 
4991   if (!D) {
4992     return 0;
4993   }
4994 
4995   // If D comes from an AST file, its declaration ID is already known and
4996   // fixed.
4997   if (D->isFromASTFile())
4998     return D->getGlobalID();
4999 
5000   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5001   DeclID &ID = DeclIDs[D];
5002   if (ID == 0) {
5003     if (DoneWritingDeclsAndTypes) {
5004       assert(0 && "New decl seen after serializing all the decls to emit!");
5005       return 0;
5006     }
5007 
5008     // We haven't seen this declaration before. Give it a new ID and
5009     // enqueue it in the list of declarations to emit.
5010     ID = NextDeclID++;
5011     DeclTypesToEmit.push(const_cast<Decl *>(D));
5012   }
5013 
5014   return ID;
5015 }
5016 
5017 DeclID ASTWriter::getDeclID(const Decl *D) {
5018   if (!D)
5019     return 0;
5020 
5021   // If D comes from an AST file, its declaration ID is already known and
5022   // fixed.
5023   if (D->isFromASTFile())
5024     return D->getGlobalID();
5025 
5026   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5027   return DeclIDs[D];
5028 }
5029 
5030 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5031   assert(ID);
5032   assert(D);
5033 
5034   SourceLocation Loc = D->getLocation();
5035   if (Loc.isInvalid())
5036     return;
5037 
5038   // We only keep track of the file-level declarations of each file.
5039   if (!D->getLexicalDeclContext()->isFileContext())
5040     return;
5041   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5042   // a function/objc method, should not have TU as lexical context.
5043   if (isa<ParmVarDecl>(D))
5044     return;
5045 
5046   SourceManager &SM = Context->getSourceManager();
5047   SourceLocation FileLoc = SM.getFileLoc(Loc);
5048   assert(SM.isLocalSourceLocation(FileLoc));
5049   FileID FID;
5050   unsigned Offset;
5051   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5052   if (FID.isInvalid())
5053     return;
5054   assert(SM.getSLocEntry(FID).isFile());
5055 
5056   DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5057   if (!Info)
5058     Info = new DeclIDInFileInfo();
5059 
5060   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5061   LocDeclIDsTy &Decls = Info->DeclIDs;
5062 
5063   if (Decls.empty() || Decls.back().first <= Offset) {
5064     Decls.push_back(LocDecl);
5065     return;
5066   }
5067 
5068   LocDeclIDsTy::iterator I =
5069       std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5070 
5071   Decls.insert(I, LocDecl);
5072 }
5073 
5074 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
5075   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
5076   Record.push_back(Name.getNameKind());
5077   switch (Name.getNameKind()) {
5078   case DeclarationName::Identifier:
5079     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5080     break;
5081 
5082   case DeclarationName::ObjCZeroArgSelector:
5083   case DeclarationName::ObjCOneArgSelector:
5084   case DeclarationName::ObjCMultiArgSelector:
5085     AddSelectorRef(Name.getObjCSelector(), Record);
5086     break;
5087 
5088   case DeclarationName::CXXConstructorName:
5089   case DeclarationName::CXXDestructorName:
5090   case DeclarationName::CXXConversionFunctionName:
5091     AddTypeRef(Name.getCXXNameType(), Record);
5092     break;
5093 
5094   case DeclarationName::CXXOperatorName:
5095     Record.push_back(Name.getCXXOverloadedOperator());
5096     break;
5097 
5098   case DeclarationName::CXXLiteralOperatorName:
5099     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5100     break;
5101 
5102   case DeclarationName::CXXUsingDirective:
5103     // No extra data to emit
5104     break;
5105   }
5106 }
5107 
5108 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5109                                      DeclarationName Name, RecordDataImpl &Record) {
5110   switch (Name.getNameKind()) {
5111   case DeclarationName::CXXConstructorName:
5112   case DeclarationName::CXXDestructorName:
5113   case DeclarationName::CXXConversionFunctionName:
5114     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5115     break;
5116 
5117   case DeclarationName::CXXOperatorName:
5118     AddSourceLocation(
5119        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5120        Record);
5121     AddSourceLocation(
5122         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5123         Record);
5124     break;
5125 
5126   case DeclarationName::CXXLiteralOperatorName:
5127     AddSourceLocation(
5128      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5129      Record);
5130     break;
5131 
5132   case DeclarationName::Identifier:
5133   case DeclarationName::ObjCZeroArgSelector:
5134   case DeclarationName::ObjCOneArgSelector:
5135   case DeclarationName::ObjCMultiArgSelector:
5136   case DeclarationName::CXXUsingDirective:
5137     break;
5138   }
5139 }
5140 
5141 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5142                                        RecordDataImpl &Record) {
5143   AddDeclarationName(NameInfo.getName(), Record);
5144   AddSourceLocation(NameInfo.getLoc(), Record);
5145   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5146 }
5147 
5148 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
5149                                  RecordDataImpl &Record) {
5150   AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
5151   Record.push_back(Info.NumTemplParamLists);
5152   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5153     AddTemplateParameterList(Info.TemplParamLists[i], Record);
5154 }
5155 
5156 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
5157                                        RecordDataImpl &Record) {
5158   // Nested name specifiers usually aren't too long. I think that 8 would
5159   // typically accommodate the vast majority.
5160   SmallVector<NestedNameSpecifier *, 8> NestedNames;
5161 
5162   // Push each of the NNS's onto a stack for serialization in reverse order.
5163   while (NNS) {
5164     NestedNames.push_back(NNS);
5165     NNS = NNS->getPrefix();
5166   }
5167 
5168   Record.push_back(NestedNames.size());
5169   while(!NestedNames.empty()) {
5170     NNS = NestedNames.pop_back_val();
5171     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5172     Record.push_back(Kind);
5173     switch (Kind) {
5174     case NestedNameSpecifier::Identifier:
5175       AddIdentifierRef(NNS->getAsIdentifier(), Record);
5176       break;
5177 
5178     case NestedNameSpecifier::Namespace:
5179       AddDeclRef(NNS->getAsNamespace(), Record);
5180       break;
5181 
5182     case NestedNameSpecifier::NamespaceAlias:
5183       AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5184       break;
5185 
5186     case NestedNameSpecifier::TypeSpec:
5187     case NestedNameSpecifier::TypeSpecWithTemplate:
5188       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5189       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5190       break;
5191 
5192     case NestedNameSpecifier::Global:
5193       // Don't need to write an associated value.
5194       break;
5195     }
5196   }
5197 }
5198 
5199 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5200                                           RecordDataImpl &Record) {
5201   // Nested name specifiers usually aren't too long. I think that 8 would
5202   // typically accommodate the vast majority.
5203   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5204 
5205   // Push each of the nested-name-specifiers's onto a stack for
5206   // serialization in reverse order.
5207   while (NNS) {
5208     NestedNames.push_back(NNS);
5209     NNS = NNS.getPrefix();
5210   }
5211 
5212   Record.push_back(NestedNames.size());
5213   while(!NestedNames.empty()) {
5214     NNS = NestedNames.pop_back_val();
5215     NestedNameSpecifier::SpecifierKind Kind
5216       = NNS.getNestedNameSpecifier()->getKind();
5217     Record.push_back(Kind);
5218     switch (Kind) {
5219     case NestedNameSpecifier::Identifier:
5220       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5221       AddSourceRange(NNS.getLocalSourceRange(), Record);
5222       break;
5223 
5224     case NestedNameSpecifier::Namespace:
5225       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5226       AddSourceRange(NNS.getLocalSourceRange(), Record);
5227       break;
5228 
5229     case NestedNameSpecifier::NamespaceAlias:
5230       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5231       AddSourceRange(NNS.getLocalSourceRange(), Record);
5232       break;
5233 
5234     case NestedNameSpecifier::TypeSpec:
5235     case NestedNameSpecifier::TypeSpecWithTemplate:
5236       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5237       AddTypeLoc(NNS.getTypeLoc(), Record);
5238       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5239       break;
5240 
5241     case NestedNameSpecifier::Global:
5242       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5243       break;
5244     }
5245   }
5246 }
5247 
5248 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
5249   TemplateName::NameKind Kind = Name.getKind();
5250   Record.push_back(Kind);
5251   switch (Kind) {
5252   case TemplateName::Template:
5253     AddDeclRef(Name.getAsTemplateDecl(), Record);
5254     break;
5255 
5256   case TemplateName::OverloadedTemplate: {
5257     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5258     Record.push_back(OvT->size());
5259     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
5260            I != E; ++I)
5261       AddDeclRef(*I, Record);
5262     break;
5263   }
5264 
5265   case TemplateName::QualifiedTemplate: {
5266     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5267     AddNestedNameSpecifier(QualT->getQualifier(), Record);
5268     Record.push_back(QualT->hasTemplateKeyword());
5269     AddDeclRef(QualT->getTemplateDecl(), Record);
5270     break;
5271   }
5272 
5273   case TemplateName::DependentTemplate: {
5274     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5275     AddNestedNameSpecifier(DepT->getQualifier(), Record);
5276     Record.push_back(DepT->isIdentifier());
5277     if (DepT->isIdentifier())
5278       AddIdentifierRef(DepT->getIdentifier(), Record);
5279     else
5280       Record.push_back(DepT->getOperator());
5281     break;
5282   }
5283 
5284   case TemplateName::SubstTemplateTemplateParm: {
5285     SubstTemplateTemplateParmStorage *subst
5286       = Name.getAsSubstTemplateTemplateParm();
5287     AddDeclRef(subst->getParameter(), Record);
5288     AddTemplateName(subst->getReplacement(), Record);
5289     break;
5290   }
5291 
5292   case TemplateName::SubstTemplateTemplateParmPack: {
5293     SubstTemplateTemplateParmPackStorage *SubstPack
5294       = Name.getAsSubstTemplateTemplateParmPack();
5295     AddDeclRef(SubstPack->getParameterPack(), Record);
5296     AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5297     break;
5298   }
5299   }
5300 }
5301 
5302 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
5303                                     RecordDataImpl &Record) {
5304   Record.push_back(Arg.getKind());
5305   switch (Arg.getKind()) {
5306   case TemplateArgument::Null:
5307     break;
5308   case TemplateArgument::Type:
5309     AddTypeRef(Arg.getAsType(), Record);
5310     break;
5311   case TemplateArgument::Declaration:
5312     AddDeclRef(Arg.getAsDecl(), Record);
5313     Record.push_back(Arg.isDeclForReferenceParam());
5314     break;
5315   case TemplateArgument::NullPtr:
5316     AddTypeRef(Arg.getNullPtrType(), Record);
5317     break;
5318   case TemplateArgument::Integral:
5319     AddAPSInt(Arg.getAsIntegral(), Record);
5320     AddTypeRef(Arg.getIntegralType(), Record);
5321     break;
5322   case TemplateArgument::Template:
5323     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5324     break;
5325   case TemplateArgument::TemplateExpansion:
5326     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5327     if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5328       Record.push_back(*NumExpansions + 1);
5329     else
5330       Record.push_back(0);
5331     break;
5332   case TemplateArgument::Expression:
5333     AddStmt(Arg.getAsExpr());
5334     break;
5335   case TemplateArgument::Pack:
5336     Record.push_back(Arg.pack_size());
5337     for (const auto &P : Arg.pack_elements())
5338       AddTemplateArgument(P, Record);
5339     break;
5340   }
5341 }
5342 
5343 void
5344 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
5345                                     RecordDataImpl &Record) {
5346   assert(TemplateParams && "No TemplateParams!");
5347   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5348   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5349   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5350   Record.push_back(TemplateParams->size());
5351   for (TemplateParameterList::const_iterator
5352          P = TemplateParams->begin(), PEnd = TemplateParams->end();
5353          P != PEnd; ++P)
5354     AddDeclRef(*P, Record);
5355 }
5356 
5357 /// \brief Emit a template argument list.
5358 void
5359 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
5360                                    RecordDataImpl &Record) {
5361   assert(TemplateArgs && "No TemplateArgs!");
5362   Record.push_back(TemplateArgs->size());
5363   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5364     AddTemplateArgument(TemplateArgs->get(i), Record);
5365 }
5366 
5367 void
5368 ASTWriter::AddASTTemplateArgumentListInfo
5369 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5370   assert(ASTTemplArgList && "No ASTTemplArgList!");
5371   AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5372   AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5373   Record.push_back(ASTTemplArgList->NumTemplateArgs);
5374   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5375   for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5376     AddTemplateArgumentLoc(TemplArgs[i], Record);
5377 }
5378 
5379 void
5380 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
5381   Record.push_back(Set.size());
5382   for (ASTUnresolvedSet::const_iterator
5383          I = Set.begin(), E = Set.end(); I != E; ++I) {
5384     AddDeclRef(I.getDecl(), Record);
5385     Record.push_back(I.getAccess());
5386   }
5387 }
5388 
5389 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
5390                                     RecordDataImpl &Record) {
5391   Record.push_back(Base.isVirtual());
5392   Record.push_back(Base.isBaseOfClass());
5393   Record.push_back(Base.getAccessSpecifierAsWritten());
5394   Record.push_back(Base.getInheritConstructors());
5395   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
5396   AddSourceRange(Base.getSourceRange(), Record);
5397   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5398                                           : SourceLocation(),
5399                     Record);
5400 }
5401 
5402 void ASTWriter::FlushCXXBaseSpecifiers() {
5403   RecordData Record;
5404   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
5405     Record.clear();
5406 
5407     // Record the offset of this base-specifier set.
5408     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5409     if (Index == CXXBaseSpecifiersOffsets.size())
5410       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5411     else {
5412       if (Index > CXXBaseSpecifiersOffsets.size())
5413         CXXBaseSpecifiersOffsets.resize(Index + 1);
5414       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5415     }
5416 
5417     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5418                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5419     Record.push_back(BEnd - B);
5420     for (; B != BEnd; ++B)
5421       AddCXXBaseSpecifier(*B, Record);
5422     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5423 
5424     // Flush any expressions that were written as part of the base specifiers.
5425     FlushStmts();
5426   }
5427 
5428   CXXBaseSpecifiersToWrite.clear();
5429 }
5430 
5431 void ASTWriter::AddCXXCtorInitializers(
5432                              const CXXCtorInitializer * const *CtorInitializers,
5433                              unsigned NumCtorInitializers,
5434                              RecordDataImpl &Record) {
5435   Record.push_back(NumCtorInitializers);
5436   for (unsigned i=0; i != NumCtorInitializers; ++i) {
5437     const CXXCtorInitializer *Init = CtorInitializers[i];
5438 
5439     if (Init->isBaseInitializer()) {
5440       Record.push_back(CTOR_INITIALIZER_BASE);
5441       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5442       Record.push_back(Init->isBaseVirtual());
5443     } else if (Init->isDelegatingInitializer()) {
5444       Record.push_back(CTOR_INITIALIZER_DELEGATING);
5445       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5446     } else if (Init->isMemberInitializer()){
5447       Record.push_back(CTOR_INITIALIZER_MEMBER);
5448       AddDeclRef(Init->getMember(), Record);
5449     } else {
5450       Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5451       AddDeclRef(Init->getIndirectMember(), Record);
5452     }
5453 
5454     AddSourceLocation(Init->getMemberLocation(), Record);
5455     AddStmt(Init->getInit());
5456     AddSourceLocation(Init->getLParenLoc(), Record);
5457     AddSourceLocation(Init->getRParenLoc(), Record);
5458     Record.push_back(Init->isWritten());
5459     if (Init->isWritten()) {
5460       Record.push_back(Init->getSourceOrder());
5461     } else {
5462       Record.push_back(Init->getNumArrayIndices());
5463       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5464         AddDeclRef(Init->getArrayIndex(i), Record);
5465     }
5466   }
5467 }
5468 
5469 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
5470   auto &Data = D->data();
5471   Record.push_back(Data.IsLambda);
5472   Record.push_back(Data.UserDeclaredConstructor);
5473   Record.push_back(Data.UserDeclaredSpecialMembers);
5474   Record.push_back(Data.Aggregate);
5475   Record.push_back(Data.PlainOldData);
5476   Record.push_back(Data.Empty);
5477   Record.push_back(Data.Polymorphic);
5478   Record.push_back(Data.Abstract);
5479   Record.push_back(Data.IsStandardLayout);
5480   Record.push_back(Data.HasNoNonEmptyBases);
5481   Record.push_back(Data.HasPrivateFields);
5482   Record.push_back(Data.HasProtectedFields);
5483   Record.push_back(Data.HasPublicFields);
5484   Record.push_back(Data.HasMutableFields);
5485   Record.push_back(Data.HasVariantMembers);
5486   Record.push_back(Data.HasOnlyCMembers);
5487   Record.push_back(Data.HasInClassInitializer);
5488   Record.push_back(Data.HasUninitializedReferenceMember);
5489   Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5490   Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5491   Record.push_back(Data.NeedOverloadResolutionForDestructor);
5492   Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5493   Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5494   Record.push_back(Data.DefaultedDestructorIsDeleted);
5495   Record.push_back(Data.HasTrivialSpecialMembers);
5496   Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
5497   Record.push_back(Data.HasIrrelevantDestructor);
5498   Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5499   Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5500   Record.push_back(Data.HasConstexprDefaultConstructor);
5501   Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5502   Record.push_back(Data.ComputedVisibleConversions);
5503   Record.push_back(Data.UserProvidedDefaultConstructor);
5504   Record.push_back(Data.DeclaredSpecialMembers);
5505   Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5506   Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5507   Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5508   Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5509   // IsLambda bit is already saved.
5510 
5511   Record.push_back(Data.NumBases);
5512   if (Data.NumBases > 0)
5513     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5514                             Record);
5515 
5516   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5517   Record.push_back(Data.NumVBases);
5518   if (Data.NumVBases > 0)
5519     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5520                             Record);
5521 
5522   AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5523   AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5524   // Data.Definition is the owning decl, no need to write it.
5525   AddDeclRef(D->getFirstFriend(), Record);
5526 
5527   // Add lambda-specific data.
5528   if (Data.IsLambda) {
5529     auto &Lambda = D->getLambdaData();
5530     Record.push_back(Lambda.Dependent);
5531     Record.push_back(Lambda.IsGenericLambda);
5532     Record.push_back(Lambda.CaptureDefault);
5533     Record.push_back(Lambda.NumCaptures);
5534     Record.push_back(Lambda.NumExplicitCaptures);
5535     Record.push_back(Lambda.ManglingNumber);
5536     AddDeclRef(Lambda.ContextDecl, Record);
5537     AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5538     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5539       const LambdaCapture &Capture = Lambda.Captures[I];
5540       AddSourceLocation(Capture.getLocation(), Record);
5541       Record.push_back(Capture.isImplicit());
5542       Record.push_back(Capture.getCaptureKind());
5543       switch (Capture.getCaptureKind()) {
5544       case LCK_This:
5545         break;
5546       case LCK_ByCopy:
5547       case LCK_ByRef:
5548         VarDecl *Var =
5549             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5550         AddDeclRef(Var, Record);
5551         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5552                                                     : SourceLocation(),
5553                           Record);
5554         break;
5555       }
5556     }
5557   }
5558 }
5559 
5560 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5561   assert(Reader && "Cannot remove chain");
5562   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5563   assert(FirstDeclID == NextDeclID &&
5564          FirstTypeID == NextTypeID &&
5565          FirstIdentID == NextIdentID &&
5566          FirstMacroID == NextMacroID &&
5567          FirstSubmoduleID == NextSubmoduleID &&
5568          FirstSelectorID == NextSelectorID &&
5569          "Setting chain after writing has started.");
5570 
5571   Chain = Reader;
5572 
5573   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5574   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5575   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5576   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5577   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5578   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5579   NextDeclID = FirstDeclID;
5580   NextTypeID = FirstTypeID;
5581   NextIdentID = FirstIdentID;
5582   NextMacroID = FirstMacroID;
5583   NextSelectorID = FirstSelectorID;
5584   NextSubmoduleID = FirstSubmoduleID;
5585 }
5586 
5587 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5588   // Always keep the highest ID. See \p TypeRead() for more information.
5589   IdentID &StoredID = IdentifierIDs[II];
5590   if (ID > StoredID)
5591     StoredID = ID;
5592 }
5593 
5594 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5595   // Always keep the highest ID. See \p TypeRead() for more information.
5596   MacroID &StoredID = MacroIDs[MI];
5597   if (ID > StoredID)
5598     StoredID = ID;
5599 }
5600 
5601 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5602   // Always take the highest-numbered type index. This copes with an interesting
5603   // case for chained AST writing where we schedule writing the type and then,
5604   // later, deserialize the type from another AST. In this case, we want to
5605   // keep the higher-numbered entry so that we can properly write it out to
5606   // the AST file.
5607   TypeIdx &StoredIdx = TypeIdxs[T];
5608   if (Idx.getIndex() >= StoredIdx.getIndex())
5609     StoredIdx = Idx;
5610 }
5611 
5612 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5613   // Always keep the highest ID. See \p TypeRead() for more information.
5614   SelectorID &StoredID = SelectorIDs[S];
5615   if (ID > StoredID)
5616     StoredID = ID;
5617 }
5618 
5619 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5620                                     MacroDefinition *MD) {
5621   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5622   MacroDefinitions[MD] = ID;
5623 }
5624 
5625 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5626   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5627   SubmoduleIDs[Mod] = ID;
5628 }
5629 
5630 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5631   assert(D->isCompleteDefinition());
5632   assert(!WritingAST && "Already writing the AST!");
5633   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5634     // We are interested when a PCH decl is modified.
5635     if (RD->isFromASTFile()) {
5636       // A forward reference was mutated into a definition. Rewrite it.
5637       // FIXME: This happens during template instantiation, should we
5638       // have created a new definition decl instead ?
5639       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5640              "completed a tag from another module but not by instantiation?");
5641       DeclUpdates[RD].push_back(
5642           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5643     }
5644   }
5645 }
5646 
5647 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5648   assert(!WritingAST && "Already writing the AST!");
5649 
5650   // TU and namespaces are handled elsewhere.
5651   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5652     return;
5653 
5654   if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5655     return; // Not a source decl added to a DeclContext from PCH.
5656 
5657   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5658   AddUpdatedDeclContext(DC);
5659   UpdatingVisibleDecls.push_back(D);
5660 }
5661 
5662 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5663   assert(!WritingAST && "Already writing the AST!");
5664   assert(D->isImplicit());
5665   if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5666     return; // Not a source member added to a class from PCH.
5667   if (!isa<CXXMethodDecl>(D))
5668     return; // We are interested in lazily declared implicit methods.
5669 
5670   // A decl coming from PCH was modified.
5671   assert(RD->isCompleteDefinition());
5672   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5673 }
5674 
5675 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5676                                      const ClassTemplateSpecializationDecl *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(
5688     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *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::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5700                                                const FunctionDecl *D) {
5701   // The specializations set is kept in the canonical template.
5702   assert(!WritingAST && "Already writing the AST!");
5703   TD = TD->getCanonicalDecl();
5704   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5705     return; // Not a source specialization added to a template from PCH.
5706 
5707   DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5708                                        D));
5709 }
5710 
5711 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5712   assert(!WritingAST && "Already writing the AST!");
5713   FD = FD->getCanonicalDecl();
5714   if (!FD->isFromASTFile())
5715     return; // Not a function declared in PCH and defined outside.
5716 
5717   DeclUpdates[FD].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5718 }
5719 
5720 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5721   assert(!WritingAST && "Already writing the AST!");
5722   FD = FD->getCanonicalDecl();
5723   if (!FD->isFromASTFile())
5724     return; // Not a function declared in PCH and defined outside.
5725 
5726   DeclUpdates[FD].push_back(DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5727 }
5728 
5729 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5730   assert(!WritingAST && "Already writing the AST!");
5731   if (!D->isFromASTFile())
5732     return; // Declaration not imported from PCH.
5733 
5734   // Implicit function decl from a PCH was defined.
5735   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5736 }
5737 
5738 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5739   assert(!WritingAST && "Already writing the AST!");
5740   if (!D->isFromASTFile())
5741     return;
5742 
5743   DeclUpdates[D].push_back(
5744       DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5745 }
5746 
5747 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5748   assert(!WritingAST && "Already writing the AST!");
5749   if (!D->isFromASTFile())
5750     return;
5751 
5752   // Since the actual instantiation is delayed, this really means that we need
5753   // to update the instantiation location.
5754   DeclUpdates[D].push_back(
5755       DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5756        D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5757 }
5758 
5759 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5760                                              const ObjCInterfaceDecl *IFD) {
5761   assert(!WritingAST && "Already writing the AST!");
5762   if (!IFD->isFromASTFile())
5763     return; // Declaration not imported from PCH.
5764 
5765   assert(IFD->getDefinition() && "Category on a class without a definition?");
5766   ObjCClassesWithCategories.insert(
5767     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5768 }
5769 
5770 
5771 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5772                                           const ObjCPropertyDecl *OrigProp,
5773                                           const ObjCCategoryDecl *ClassExt) {
5774   const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5775   if (!D)
5776     return;
5777 
5778   assert(!WritingAST && "Already writing the AST!");
5779   if (!D->isFromASTFile())
5780     return; // Declaration not imported from PCH.
5781 
5782   RewriteDecl(D);
5783 }
5784 
5785 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5786   assert(!WritingAST && "Already writing the AST!");
5787   if (!D->isFromASTFile())
5788     return;
5789 
5790   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5791 }
5792