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