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