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