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