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 
1073   // SourceManager Block.
1074   BLOCK(SOURCE_MANAGER_BLOCK);
1075   RECORD(SM_SLOC_FILE_ENTRY);
1076   RECORD(SM_SLOC_BUFFER_ENTRY);
1077   RECORD(SM_SLOC_BUFFER_BLOB);
1078   RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1079   RECORD(SM_SLOC_EXPANSION_ENTRY);
1080 
1081   // Preprocessor Block.
1082   BLOCK(PREPROCESSOR_BLOCK);
1083   RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1084   RECORD(PP_MACRO_FUNCTION_LIKE);
1085   RECORD(PP_MACRO_OBJECT_LIKE);
1086   RECORD(PP_MODULE_MACRO);
1087   RECORD(PP_TOKEN);
1088 
1089   // Submodule Block.
1090   BLOCK(SUBMODULE_BLOCK);
1091   RECORD(SUBMODULE_METADATA);
1092   RECORD(SUBMODULE_DEFINITION);
1093   RECORD(SUBMODULE_UMBRELLA_HEADER);
1094   RECORD(SUBMODULE_HEADER);
1095   RECORD(SUBMODULE_TOPHEADER);
1096   RECORD(SUBMODULE_UMBRELLA_DIR);
1097   RECORD(SUBMODULE_IMPORTS);
1098   RECORD(SUBMODULE_EXPORTS);
1099   RECORD(SUBMODULE_REQUIRES);
1100   RECORD(SUBMODULE_EXCLUDED_HEADER);
1101   RECORD(SUBMODULE_LINK_LIBRARY);
1102   RECORD(SUBMODULE_CONFIG_MACRO);
1103   RECORD(SUBMODULE_CONFLICT);
1104   RECORD(SUBMODULE_PRIVATE_HEADER);
1105   RECORD(SUBMODULE_TEXTUAL_HEADER);
1106   RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1107   RECORD(SUBMODULE_INITIALIZERS);
1108 
1109   // Comments Block.
1110   BLOCK(COMMENTS_BLOCK);
1111   RECORD(COMMENTS_RAW_COMMENT);
1112 
1113   // Decls and Types block.
1114   BLOCK(DECLTYPES_BLOCK);
1115   RECORD(TYPE_EXT_QUAL);
1116   RECORD(TYPE_COMPLEX);
1117   RECORD(TYPE_POINTER);
1118   RECORD(TYPE_BLOCK_POINTER);
1119   RECORD(TYPE_LVALUE_REFERENCE);
1120   RECORD(TYPE_RVALUE_REFERENCE);
1121   RECORD(TYPE_MEMBER_POINTER);
1122   RECORD(TYPE_CONSTANT_ARRAY);
1123   RECORD(TYPE_INCOMPLETE_ARRAY);
1124   RECORD(TYPE_VARIABLE_ARRAY);
1125   RECORD(TYPE_VECTOR);
1126   RECORD(TYPE_EXT_VECTOR);
1127   RECORD(TYPE_FUNCTION_NO_PROTO);
1128   RECORD(TYPE_FUNCTION_PROTO);
1129   RECORD(TYPE_TYPEDEF);
1130   RECORD(TYPE_TYPEOF_EXPR);
1131   RECORD(TYPE_TYPEOF);
1132   RECORD(TYPE_RECORD);
1133   RECORD(TYPE_ENUM);
1134   RECORD(TYPE_OBJC_INTERFACE);
1135   RECORD(TYPE_OBJC_OBJECT_POINTER);
1136   RECORD(TYPE_DECLTYPE);
1137   RECORD(TYPE_ELABORATED);
1138   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1139   RECORD(TYPE_UNRESOLVED_USING);
1140   RECORD(TYPE_INJECTED_CLASS_NAME);
1141   RECORD(TYPE_OBJC_OBJECT);
1142   RECORD(TYPE_TEMPLATE_TYPE_PARM);
1143   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1144   RECORD(TYPE_DEPENDENT_NAME);
1145   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1146   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1147   RECORD(TYPE_PAREN);
1148   RECORD(TYPE_PACK_EXPANSION);
1149   RECORD(TYPE_ATTRIBUTED);
1150   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1151   RECORD(TYPE_AUTO);
1152   RECORD(TYPE_UNARY_TRANSFORM);
1153   RECORD(TYPE_ATOMIC);
1154   RECORD(TYPE_DECAYED);
1155   RECORD(TYPE_ADJUSTED);
1156   RECORD(TYPE_OBJC_TYPE_PARAM);
1157   RECORD(LOCAL_REDECLARATIONS);
1158   RECORD(DECL_TYPEDEF);
1159   RECORD(DECL_TYPEALIAS);
1160   RECORD(DECL_ENUM);
1161   RECORD(DECL_RECORD);
1162   RECORD(DECL_ENUM_CONSTANT);
1163   RECORD(DECL_FUNCTION);
1164   RECORD(DECL_OBJC_METHOD);
1165   RECORD(DECL_OBJC_INTERFACE);
1166   RECORD(DECL_OBJC_PROTOCOL);
1167   RECORD(DECL_OBJC_IVAR);
1168   RECORD(DECL_OBJC_AT_DEFS_FIELD);
1169   RECORD(DECL_OBJC_CATEGORY);
1170   RECORD(DECL_OBJC_CATEGORY_IMPL);
1171   RECORD(DECL_OBJC_IMPLEMENTATION);
1172   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1173   RECORD(DECL_OBJC_PROPERTY);
1174   RECORD(DECL_OBJC_PROPERTY_IMPL);
1175   RECORD(DECL_FIELD);
1176   RECORD(DECL_MS_PROPERTY);
1177   RECORD(DECL_VAR);
1178   RECORD(DECL_IMPLICIT_PARAM);
1179   RECORD(DECL_PARM_VAR);
1180   RECORD(DECL_FILE_SCOPE_ASM);
1181   RECORD(DECL_BLOCK);
1182   RECORD(DECL_CONTEXT_LEXICAL);
1183   RECORD(DECL_CONTEXT_VISIBLE);
1184   RECORD(DECL_NAMESPACE);
1185   RECORD(DECL_NAMESPACE_ALIAS);
1186   RECORD(DECL_USING);
1187   RECORD(DECL_USING_SHADOW);
1188   RECORD(DECL_USING_DIRECTIVE);
1189   RECORD(DECL_UNRESOLVED_USING_VALUE);
1190   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1191   RECORD(DECL_LINKAGE_SPEC);
1192   RECORD(DECL_CXX_RECORD);
1193   RECORD(DECL_CXX_METHOD);
1194   RECORD(DECL_CXX_CONSTRUCTOR);
1195   RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
1196   RECORD(DECL_CXX_DESTRUCTOR);
1197   RECORD(DECL_CXX_CONVERSION);
1198   RECORD(DECL_ACCESS_SPEC);
1199   RECORD(DECL_FRIEND);
1200   RECORD(DECL_FRIEND_TEMPLATE);
1201   RECORD(DECL_CLASS_TEMPLATE);
1202   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1203   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1204   RECORD(DECL_VAR_TEMPLATE);
1205   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1206   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1207   RECORD(DECL_FUNCTION_TEMPLATE);
1208   RECORD(DECL_TEMPLATE_TYPE_PARM);
1209   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1210   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1211   RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1212   RECORD(DECL_STATIC_ASSERT);
1213   RECORD(DECL_CXX_BASE_SPECIFIERS);
1214   RECORD(DECL_CXX_CTOR_INITIALIZERS);
1215   RECORD(DECL_INDIRECTFIELD);
1216   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1217   RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1218   RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1219   RECORD(DECL_IMPORT);
1220   RECORD(DECL_OMP_THREADPRIVATE);
1221   RECORD(DECL_EMPTY);
1222   RECORD(DECL_OBJC_TYPE_PARAM);
1223   RECORD(DECL_OMP_CAPTUREDEXPR);
1224   RECORD(DECL_PRAGMA_COMMENT);
1225   RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1226   RECORD(DECL_OMP_DECLARE_REDUCTION);
1227 
1228   // Statements and Exprs can occur in the Decls and Types block.
1229   AddStmtsExprs(Stream, Record);
1230 
1231   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1232   RECORD(PPD_MACRO_EXPANSION);
1233   RECORD(PPD_MACRO_DEFINITION);
1234   RECORD(PPD_INCLUSION_DIRECTIVE);
1235 
1236   // Decls and Types block.
1237   BLOCK(EXTENSION_BLOCK);
1238   RECORD(EXTENSION_METADATA);
1239 
1240 #undef RECORD
1241 #undef BLOCK
1242   Stream.ExitBlock();
1243 }
1244 
1245 /// \brief Prepares a path for being written to an AST file by converting it
1246 /// to an absolute path and removing nested './'s.
1247 ///
1248 /// \return \c true if the path was changed.
1249 static bool cleanPathForOutput(FileManager &FileMgr,
1250                                SmallVectorImpl<char> &Path) {
1251   bool Changed = FileMgr.makeAbsolutePath(Path);
1252   return Changed | llvm::sys::path::remove_dots(Path);
1253 }
1254 
1255 /// \brief Adjusts the given filename to only write out the portion of the
1256 /// filename that is not part of the system root directory.
1257 ///
1258 /// \param Filename the file name to adjust.
1259 ///
1260 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1261 /// the returned filename will be adjusted by this root directory.
1262 ///
1263 /// \returns either the original filename (if it needs no adjustment) or the
1264 /// adjusted filename (which points into the @p Filename parameter).
1265 static const char *
1266 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1267   assert(Filename && "No file name to adjust?");
1268 
1269   if (BaseDir.empty())
1270     return Filename;
1271 
1272   // Verify that the filename and the system root have the same prefix.
1273   unsigned Pos = 0;
1274   for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1275     if (Filename[Pos] != BaseDir[Pos])
1276       return Filename; // Prefixes don't match.
1277 
1278   // We hit the end of the filename before we hit the end of the system root.
1279   if (!Filename[Pos])
1280     return Filename;
1281 
1282   // If there's not a path separator at the end of the base directory nor
1283   // immediately after it, then this isn't within the base directory.
1284   if (!llvm::sys::path::is_separator(Filename[Pos])) {
1285     if (!llvm::sys::path::is_separator(BaseDir.back()))
1286       return Filename;
1287   } else {
1288     // If the file name has a '/' at the current position, skip over the '/'.
1289     // We distinguish relative paths from absolute paths by the
1290     // absence of '/' at the beginning of relative paths.
1291     //
1292     // FIXME: This is wrong. We distinguish them by asking if the path is
1293     // absolute, which isn't the same thing. And there might be multiple '/'s
1294     // in a row. Use a better mechanism to indicate whether we have emitted an
1295     // absolute or relative path.
1296     ++Pos;
1297   }
1298 
1299   return Filename + Pos;
1300 }
1301 
1302 static ASTFileSignature getSignature() {
1303   while (true) {
1304     if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1305       return S;
1306     // Rely on GetRandomNumber to eventually return non-zero...
1307   }
1308 }
1309 
1310 /// \brief Write the control block.
1311 uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1312                                       ASTContext &Context,
1313                                       StringRef isysroot,
1314                                       const std::string &OutputFile) {
1315   ASTFileSignature Signature = 0;
1316 
1317   using namespace llvm;
1318   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1319   RecordData Record;
1320 
1321   // Metadata
1322   auto *MetadataAbbrev = new BitCodeAbbrev();
1323   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1324   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1325   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1326   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1327   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1328   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1329   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1330   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1331   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1332   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1333   assert((!WritingModule || isysroot.empty()) &&
1334          "writing module as a relocatable PCH?");
1335   {
1336     RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1337                                        CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1338                                        !isysroot.empty(), IncludeTimestamps,
1339                                        ASTHasCompilerErrors};
1340     Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1341                               getClangFullRepositoryVersion());
1342   }
1343   if (WritingModule) {
1344     // For implicit modules we output a signature that we can use to ensure
1345     // duplicate module builds don't collide in the cache as their output order
1346     // is non-deterministic.
1347     // FIXME: Remove this when output is deterministic.
1348     if (Context.getLangOpts().ImplicitModules) {
1349       Signature = getSignature();
1350       RecordData::value_type Record[] = {Signature};
1351       Stream.EmitRecord(SIGNATURE, Record);
1352     }
1353 
1354     // Module name
1355     auto *Abbrev = new BitCodeAbbrev();
1356     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1357     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1358     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1359     RecordData::value_type Record[] = {MODULE_NAME};
1360     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1361   }
1362 
1363   if (WritingModule && WritingModule->Directory) {
1364     SmallString<128> BaseDir(WritingModule->Directory->getName());
1365     cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1366 
1367     // If the home of the module is the current working directory, then we
1368     // want to pick up the cwd of the build process loading the module, not
1369     // our cwd, when we load this module.
1370     if (!PP.getHeaderSearchInfo()
1371              .getHeaderSearchOpts()
1372              .ModuleMapFileHomeIsCwd ||
1373         WritingModule->Directory->getName() != StringRef(".")) {
1374       // Module directory.
1375       auto *Abbrev = new BitCodeAbbrev();
1376       Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1377       Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1378       unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1379 
1380       RecordData::value_type Record[] = {MODULE_DIRECTORY};
1381       Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1382     }
1383 
1384     // Write out all other paths relative to the base directory if possible.
1385     BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1386   } else if (!isysroot.empty()) {
1387     // Write out paths relative to the sysroot if possible.
1388     BaseDirectory = isysroot;
1389   }
1390 
1391   // Module map file
1392   if (WritingModule) {
1393     Record.clear();
1394 
1395     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1396 
1397     // Primary module map file.
1398     AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1399 
1400     // Additional module map files.
1401     if (auto *AdditionalModMaps =
1402             Map.getAdditionalModuleMapFiles(WritingModule)) {
1403       Record.push_back(AdditionalModMaps->size());
1404       for (const FileEntry *F : *AdditionalModMaps)
1405         AddPath(F->getName(), Record);
1406     } else {
1407       Record.push_back(0);
1408     }
1409 
1410     Stream.EmitRecord(MODULE_MAP_FILE, Record);
1411   }
1412 
1413   // Imports
1414   if (Chain) {
1415     serialization::ModuleManager &Mgr = Chain->getModuleManager();
1416     Record.clear();
1417 
1418     for (auto *M : Mgr) {
1419       // Skip modules that weren't directly imported.
1420       if (!M->isDirectlyImported())
1421         continue;
1422 
1423       Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1424       AddSourceLocation(M->ImportLoc, Record);
1425       Record.push_back(M->File->getSize());
1426       Record.push_back(getTimestampForOutput(M->File));
1427       Record.push_back(M->Signature);
1428       AddPath(M->FileName, Record);
1429     }
1430     Stream.EmitRecord(IMPORTS, Record);
1431   }
1432 
1433   // Write the options block.
1434   Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1435 
1436   // Language options.
1437   Record.clear();
1438   const LangOptions &LangOpts = Context.getLangOpts();
1439 #define LANGOPT(Name, Bits, Default, Description) \
1440   Record.push_back(LangOpts.Name);
1441 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1442   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1443 #include "clang/Basic/LangOptions.def"
1444 #define SANITIZER(NAME, ID)                                                    \
1445   Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1446 #include "clang/Basic/Sanitizers.def"
1447 
1448   Record.push_back(LangOpts.ModuleFeatures.size());
1449   for (StringRef Feature : LangOpts.ModuleFeatures)
1450     AddString(Feature, Record);
1451 
1452   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1453   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1454 
1455   AddString(LangOpts.CurrentModule, Record);
1456 
1457   // Comment options.
1458   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1459   for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1460     AddString(I, Record);
1461   }
1462   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1463 
1464   // OpenMP offloading options.
1465   Record.push_back(LangOpts.OMPTargetTriples.size());
1466   for (auto &T : LangOpts.OMPTargetTriples)
1467     AddString(T.getTriple(), Record);
1468 
1469   AddString(LangOpts.OMPHostIRFile, Record);
1470 
1471   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1472 
1473   // Target options.
1474   Record.clear();
1475   const TargetInfo &Target = Context.getTargetInfo();
1476   const TargetOptions &TargetOpts = Target.getTargetOpts();
1477   AddString(TargetOpts.Triple, Record);
1478   AddString(TargetOpts.CPU, Record);
1479   AddString(TargetOpts.ABI, Record);
1480   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1481   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1482     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1483   }
1484   Record.push_back(TargetOpts.Features.size());
1485   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1486     AddString(TargetOpts.Features[I], Record);
1487   }
1488   Stream.EmitRecord(TARGET_OPTIONS, Record);
1489 
1490   // Diagnostic options.
1491   Record.clear();
1492   const DiagnosticOptions &DiagOpts
1493     = Context.getDiagnostics().getDiagnosticOptions();
1494 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1495 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1496   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1497 #include "clang/Basic/DiagnosticOptions.def"
1498   Record.push_back(DiagOpts.Warnings.size());
1499   for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1500     AddString(DiagOpts.Warnings[I], Record);
1501   Record.push_back(DiagOpts.Remarks.size());
1502   for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1503     AddString(DiagOpts.Remarks[I], Record);
1504   // Note: we don't serialize the log or serialization file names, because they
1505   // are generally transient files and will almost always be overridden.
1506   Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1507 
1508   // File system options.
1509   Record.clear();
1510   const FileSystemOptions &FSOpts =
1511       Context.getSourceManager().getFileManager().getFileSystemOpts();
1512   AddString(FSOpts.WorkingDir, Record);
1513   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1514 
1515   // Header search options.
1516   Record.clear();
1517   const HeaderSearchOptions &HSOpts
1518     = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1519   AddString(HSOpts.Sysroot, Record);
1520 
1521   // Include entries.
1522   Record.push_back(HSOpts.UserEntries.size());
1523   for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1524     const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1525     AddString(Entry.Path, Record);
1526     Record.push_back(static_cast<unsigned>(Entry.Group));
1527     Record.push_back(Entry.IsFramework);
1528     Record.push_back(Entry.IgnoreSysRoot);
1529   }
1530 
1531   // System header prefixes.
1532   Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1533   for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1534     AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1535     Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1536   }
1537 
1538   AddString(HSOpts.ResourceDir, Record);
1539   AddString(HSOpts.ModuleCachePath, Record);
1540   AddString(HSOpts.ModuleUserBuildPath, Record);
1541   Record.push_back(HSOpts.DisableModuleHash);
1542   Record.push_back(HSOpts.UseBuiltinIncludes);
1543   Record.push_back(HSOpts.UseStandardSystemIncludes);
1544   Record.push_back(HSOpts.UseStandardCXXIncludes);
1545   Record.push_back(HSOpts.UseLibcxx);
1546   // Write out the specific module cache path that contains the module files.
1547   AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1548   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1549 
1550   // Preprocessor options.
1551   Record.clear();
1552   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1553 
1554   // Macro definitions.
1555   Record.push_back(PPOpts.Macros.size());
1556   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1557     AddString(PPOpts.Macros[I].first, Record);
1558     Record.push_back(PPOpts.Macros[I].second);
1559   }
1560 
1561   // Includes
1562   Record.push_back(PPOpts.Includes.size());
1563   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1564     AddString(PPOpts.Includes[I], Record);
1565 
1566   // Macro includes
1567   Record.push_back(PPOpts.MacroIncludes.size());
1568   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1569     AddString(PPOpts.MacroIncludes[I], Record);
1570 
1571   Record.push_back(PPOpts.UsePredefines);
1572   // Detailed record is important since it is used for the module cache hash.
1573   Record.push_back(PPOpts.DetailedRecord);
1574   AddString(PPOpts.ImplicitPCHInclude, Record);
1575   AddString(PPOpts.ImplicitPTHInclude, Record);
1576   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1577   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1578 
1579   // Leave the options block.
1580   Stream.ExitBlock();
1581 
1582   // Original file name and file ID
1583   SourceManager &SM = Context.getSourceManager();
1584   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1585     auto *FileAbbrev = new BitCodeAbbrev();
1586     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1587     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1588     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1589     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1590 
1591     Record.clear();
1592     Record.push_back(ORIGINAL_FILE);
1593     Record.push_back(SM.getMainFileID().getOpaqueValue());
1594     EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1595   }
1596 
1597   Record.clear();
1598   Record.push_back(SM.getMainFileID().getOpaqueValue());
1599   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1600 
1601   // Original PCH directory
1602   if (!OutputFile.empty() && OutputFile != "-") {
1603     auto *Abbrev = new BitCodeAbbrev();
1604     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1605     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1606     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1607 
1608     SmallString<128> OutputPath(OutputFile);
1609 
1610     SM.getFileManager().makeAbsolutePath(OutputPath);
1611     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1612 
1613     RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1614     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1615   }
1616 
1617   WriteInputFiles(Context.SourceMgr,
1618                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1619                   PP.getLangOpts().Modules);
1620   Stream.ExitBlock();
1621   return Signature;
1622 }
1623 
1624 namespace  {
1625 
1626   /// \brief An input file.
1627   struct InputFileEntry {
1628     const FileEntry *File;
1629     bool IsSystemFile;
1630     bool IsTransient;
1631     bool BufferOverridden;
1632   };
1633 
1634 } // end anonymous namespace
1635 
1636 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1637                                 HeaderSearchOptions &HSOpts,
1638                                 bool Modules) {
1639   using namespace llvm;
1640   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1641 
1642   // Create input-file abbreviation.
1643   auto *IFAbbrev = new BitCodeAbbrev();
1644   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1645   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1646   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1647   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1648   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1649   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1650   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1651   unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1652 
1653   // Get all ContentCache objects for files, sorted by whether the file is a
1654   // system one or not. System files go at the back, users files at the front.
1655   std::deque<InputFileEntry> SortedFiles;
1656   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1657     // Get this source location entry.
1658     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1659     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1660 
1661     // We only care about file entries that were not overridden.
1662     if (!SLoc->isFile())
1663       continue;
1664     const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1665     if (!Cache->OrigEntry)
1666       continue;
1667 
1668     InputFileEntry Entry;
1669     Entry.File = Cache->OrigEntry;
1670     Entry.IsSystemFile = Cache->IsSystemFile;
1671     Entry.IsTransient = Cache->IsTransient;
1672     Entry.BufferOverridden = Cache->BufferOverridden;
1673     if (Cache->IsSystemFile)
1674       SortedFiles.push_back(Entry);
1675     else
1676       SortedFiles.push_front(Entry);
1677   }
1678 
1679   unsigned UserFilesNum = 0;
1680   // Write out all of the input files.
1681   std::vector<uint64_t> InputFileOffsets;
1682   for (const auto &Entry : SortedFiles) {
1683     uint32_t &InputFileID = InputFileIDs[Entry.File];
1684     if (InputFileID != 0)
1685       continue; // already recorded this file.
1686 
1687     // Record this entry's offset.
1688     InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1689 
1690     InputFileID = InputFileOffsets.size();
1691 
1692     if (!Entry.IsSystemFile)
1693       ++UserFilesNum;
1694 
1695     // Emit size/modification time for this file.
1696     // And whether this file was overridden.
1697     RecordData::value_type Record[] = {
1698         INPUT_FILE,
1699         InputFileOffsets.size(),
1700         (uint64_t)Entry.File->getSize(),
1701         (uint64_t)getTimestampForOutput(Entry.File),
1702         Entry.BufferOverridden,
1703         Entry.IsTransient};
1704 
1705     EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1706   }
1707 
1708   Stream.ExitBlock();
1709 
1710   // Create input file offsets abbreviation.
1711   auto *OffsetsAbbrev = new BitCodeAbbrev();
1712   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1713   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1714   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1715                                                                 //   input files
1716   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1717   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1718 
1719   // Write input file offsets.
1720   RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1721                                      InputFileOffsets.size(), UserFilesNum};
1722   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1723 }
1724 
1725 //===----------------------------------------------------------------------===//
1726 // Source Manager Serialization
1727 //===----------------------------------------------------------------------===//
1728 
1729 /// \brief Create an abbreviation for the SLocEntry that refers to a
1730 /// file.
1731 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1732   using namespace llvm;
1733 
1734   auto *Abbrev = new BitCodeAbbrev();
1735   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1736   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1737   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1738   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1739   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1740   // FileEntry fields.
1741   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1742   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1743   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1744   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1745   return Stream.EmitAbbrev(Abbrev);
1746 }
1747 
1748 /// \brief Create an abbreviation for the SLocEntry that refers to a
1749 /// buffer.
1750 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1751   using namespace llvm;
1752 
1753   auto *Abbrev = new BitCodeAbbrev();
1754   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1755   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1756   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1757   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1758   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1759   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1760   return Stream.EmitAbbrev(Abbrev);
1761 }
1762 
1763 /// \brief Create an abbreviation for the SLocEntry that refers to a
1764 /// buffer's blob.
1765 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1766                                            bool Compressed) {
1767   using namespace llvm;
1768 
1769   auto *Abbrev = new BitCodeAbbrev();
1770   Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1771                                          : SM_SLOC_BUFFER_BLOB));
1772   if (Compressed)
1773     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1774   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1775   return Stream.EmitAbbrev(Abbrev);
1776 }
1777 
1778 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1779 /// expansion.
1780 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1781   using namespace llvm;
1782 
1783   auto *Abbrev = new BitCodeAbbrev();
1784   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1785   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1786   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1787   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1788   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1789   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1790   return Stream.EmitAbbrev(Abbrev);
1791 }
1792 
1793 namespace {
1794 
1795   // Trait used for the on-disk hash table of header search information.
1796   class HeaderFileInfoTrait {
1797     ASTWriter &Writer;
1798     const HeaderSearch &HS;
1799 
1800     // Keep track of the framework names we've used during serialization.
1801     SmallVector<char, 128> FrameworkStringData;
1802     llvm::StringMap<unsigned> FrameworkNameOffset;
1803 
1804   public:
1805     HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1806       : Writer(Writer), HS(HS) { }
1807 
1808     struct key_type {
1809       const FileEntry *FE;
1810       const char *Filename;
1811     };
1812     typedef const key_type &key_type_ref;
1813 
1814     typedef HeaderFileInfo data_type;
1815     typedef const data_type &data_type_ref;
1816     typedef unsigned hash_value_type;
1817     typedef unsigned offset_type;
1818 
1819     hash_value_type ComputeHash(key_type_ref key) {
1820       // The hash is based only on size/time of the file, so that the reader can
1821       // match even when symlinking or excess path elements ("foo/../", "../")
1822       // change the form of the name. However, complete path is still the key.
1823       return llvm::hash_combine(key.FE->getSize(),
1824                                 Writer.getTimestampForOutput(key.FE));
1825     }
1826 
1827     std::pair<unsigned,unsigned>
1828     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1829       using namespace llvm::support;
1830       endian::Writer<little> LE(Out);
1831       unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1832       LE.write<uint16_t>(KeyLen);
1833       unsigned DataLen = 1 + 2 + 4 + 4;
1834       for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1835         if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1836           DataLen += 4;
1837       LE.write<uint8_t>(DataLen);
1838       return std::make_pair(KeyLen, DataLen);
1839     }
1840 
1841     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1842       using namespace llvm::support;
1843       endian::Writer<little> LE(Out);
1844       LE.write<uint64_t>(key.FE->getSize());
1845       KeyLen -= 8;
1846       LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
1847       KeyLen -= 8;
1848       Out.write(key.Filename, KeyLen);
1849     }
1850 
1851     void EmitData(raw_ostream &Out, key_type_ref key,
1852                   data_type_ref Data, unsigned DataLen) {
1853       using namespace llvm::support;
1854       endian::Writer<little> LE(Out);
1855       uint64_t Start = Out.tell(); (void)Start;
1856 
1857       unsigned char Flags = (Data.isImport << 4)
1858                           | (Data.isPragmaOnce << 3)
1859                           | (Data.DirInfo << 1)
1860                           | Data.IndexHeaderMapHeader;
1861       LE.write<uint8_t>(Flags);
1862       LE.write<uint16_t>(Data.NumIncludes);
1863 
1864       if (!Data.ControllingMacro)
1865         LE.write<uint32_t>(Data.ControllingMacroID);
1866       else
1867         LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1868 
1869       unsigned Offset = 0;
1870       if (!Data.Framework.empty()) {
1871         // If this header refers into a framework, save the framework name.
1872         llvm::StringMap<unsigned>::iterator Pos
1873           = FrameworkNameOffset.find(Data.Framework);
1874         if (Pos == FrameworkNameOffset.end()) {
1875           Offset = FrameworkStringData.size() + 1;
1876           FrameworkStringData.append(Data.Framework.begin(),
1877                                      Data.Framework.end());
1878           FrameworkStringData.push_back(0);
1879 
1880           FrameworkNameOffset[Data.Framework] = Offset;
1881         } else
1882           Offset = Pos->second;
1883       }
1884       LE.write<uint32_t>(Offset);
1885 
1886       // FIXME: If the header is excluded, we should write out some
1887       // record of that fact.
1888       for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1889         if (uint32_t ModID =
1890                 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1891           uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1892           assert((Value >> 2) == ModID && "overflow in header module info");
1893           LE.write<uint32_t>(Value);
1894         }
1895       }
1896 
1897       assert(Out.tell() - Start == DataLen && "Wrong data length");
1898     }
1899 
1900     const char *strings_begin() const { return FrameworkStringData.begin(); }
1901     const char *strings_end() const { return FrameworkStringData.end(); }
1902   };
1903 
1904 } // end anonymous namespace
1905 
1906 /// \brief Write the header search block for the list of files that
1907 ///
1908 /// \param HS The header search structure to save.
1909 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1910   SmallVector<const FileEntry *, 16> FilesByUID;
1911   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1912 
1913   if (FilesByUID.size() > HS.header_file_size())
1914     FilesByUID.resize(HS.header_file_size());
1915 
1916   HeaderFileInfoTrait GeneratorTrait(*this, HS);
1917   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1918   SmallVector<const char *, 4> SavedStrings;
1919   unsigned NumHeaderSearchEntries = 0;
1920   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1921     const FileEntry *File = FilesByUID[UID];
1922     if (!File)
1923       continue;
1924 
1925     // Get the file info. This will load info from the external source if
1926     // necessary. Skip emitting this file if we have no information on it
1927     // as a header file (in which case HFI will be null) or if it hasn't
1928     // changed since it was loaded. Also skip it if it's for a modular header
1929     // from a different module; in that case, we rely on the module(s)
1930     // containing the header to provide this information.
1931     const HeaderFileInfo *HFI =
1932         HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1933     if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1934       continue;
1935 
1936     // Massage the file path into an appropriate form.
1937     const char *Filename = File->getName();
1938     SmallString<128> FilenameTmp(Filename);
1939     if (PreparePathForOutput(FilenameTmp)) {
1940       // If we performed any translation on the file name at all, we need to
1941       // save this string, since the generator will refer to it later.
1942       Filename = strdup(FilenameTmp.c_str());
1943       SavedStrings.push_back(Filename);
1944     }
1945 
1946     HeaderFileInfoTrait::key_type key = { File, Filename };
1947     Generator.insert(key, *HFI, GeneratorTrait);
1948     ++NumHeaderSearchEntries;
1949   }
1950 
1951   // Create the on-disk hash table in a buffer.
1952   SmallString<4096> TableData;
1953   uint32_t BucketOffset;
1954   {
1955     using namespace llvm::support;
1956     llvm::raw_svector_ostream Out(TableData);
1957     // Make sure that no bucket is at offset 0
1958     endian::Writer<little>(Out).write<uint32_t>(0);
1959     BucketOffset = Generator.Emit(Out, GeneratorTrait);
1960   }
1961 
1962   // Create a blob abbreviation
1963   using namespace llvm;
1964 
1965   auto *Abbrev = new BitCodeAbbrev();
1966   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1967   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1968   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1969   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1970   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1971   unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1972 
1973   // Write the header search table
1974   RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1975                                      NumHeaderSearchEntries, TableData.size()};
1976   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1977   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1978 
1979   // Free all of the strings we had to duplicate.
1980   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1981     free(const_cast<char *>(SavedStrings[I]));
1982 }
1983 
1984 /// \brief Writes the block containing the serialized form of the
1985 /// source manager.
1986 ///
1987 /// TODO: We should probably use an on-disk hash table (stored in a
1988 /// blob), indexed based on the file name, so that we only create
1989 /// entries for files that we actually need. In the common case (no
1990 /// errors), we probably won't have to create file entries for any of
1991 /// the files in the AST.
1992 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1993                                         const Preprocessor &PP) {
1994   RecordData Record;
1995 
1996   // Enter the source manager block.
1997   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
1998 
1999   // Abbreviations for the various kinds of source-location entries.
2000   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2001   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2002   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2003   unsigned SLocBufferBlobCompressedAbbrv =
2004       CreateSLocBufferBlobAbbrev(Stream, true);
2005   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2006 
2007   // Write out the source location entry table. We skip the first
2008   // entry, which is always the same dummy entry.
2009   std::vector<uint32_t> SLocEntryOffsets;
2010   RecordData PreloadSLocs;
2011   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2012   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2013        I != N; ++I) {
2014     // Get this source location entry.
2015     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2016     FileID FID = FileID::get(I);
2017     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2018 
2019     // Record the offset of this source-location entry.
2020     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2021 
2022     // Figure out which record code to use.
2023     unsigned Code;
2024     if (SLoc->isFile()) {
2025       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2026       if (Cache->OrigEntry) {
2027         Code = SM_SLOC_FILE_ENTRY;
2028       } else
2029         Code = SM_SLOC_BUFFER_ENTRY;
2030     } else
2031       Code = SM_SLOC_EXPANSION_ENTRY;
2032     Record.clear();
2033     Record.push_back(Code);
2034 
2035     // Starting offset of this entry within this module, so skip the dummy.
2036     Record.push_back(SLoc->getOffset() - 2);
2037     if (SLoc->isFile()) {
2038       const SrcMgr::FileInfo &File = SLoc->getFile();
2039       AddSourceLocation(File.getIncludeLoc(), Record);
2040       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2041       Record.push_back(File.hasLineDirectives());
2042 
2043       const SrcMgr::ContentCache *Content = File.getContentCache();
2044       bool EmitBlob = false;
2045       if (Content->OrigEntry) {
2046         assert(Content->OrigEntry == Content->ContentsEntry &&
2047                "Writing to AST an overridden file is not supported");
2048 
2049         // The source location entry is a file. Emit input file ID.
2050         assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2051         Record.push_back(InputFileIDs[Content->OrigEntry]);
2052 
2053         Record.push_back(File.NumCreatedFIDs);
2054 
2055         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2056         if (FDI != FileDeclIDs.end()) {
2057           Record.push_back(FDI->second->FirstDeclIndex);
2058           Record.push_back(FDI->second->DeclIDs.size());
2059         } else {
2060           Record.push_back(0);
2061           Record.push_back(0);
2062         }
2063 
2064         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2065 
2066         if (Content->BufferOverridden || Content->IsTransient)
2067           EmitBlob = true;
2068       } else {
2069         // The source location entry is a buffer. The blob associated
2070         // with this entry contains the contents of the buffer.
2071 
2072         // We add one to the size so that we capture the trailing NULL
2073         // that is required by llvm::MemoryBuffer::getMemBuffer (on
2074         // the reader side).
2075         const llvm::MemoryBuffer *Buffer
2076           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2077         const char *Name = Buffer->getBufferIdentifier();
2078         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2079                                   StringRef(Name, strlen(Name) + 1));
2080         EmitBlob = true;
2081 
2082         if (strcmp(Name, "<built-in>") == 0) {
2083           PreloadSLocs.push_back(SLocEntryOffsets.size());
2084         }
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::WriteObjCCategories() {
3947   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3948   RecordData Categories;
3949 
3950   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3951     unsigned Size = 0;
3952     unsigned StartIndex = Categories.size();
3953 
3954     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3955 
3956     // Allocate space for the size.
3957     Categories.push_back(0);
3958 
3959     // Add the categories.
3960     for (ObjCInterfaceDecl::known_categories_iterator
3961            Cat = Class->known_categories_begin(),
3962            CatEnd = Class->known_categories_end();
3963          Cat != CatEnd; ++Cat, ++Size) {
3964       assert(getDeclID(*Cat) != 0 && "Bogus category");
3965       AddDeclRef(*Cat, Categories);
3966     }
3967 
3968     // Update the size.
3969     Categories[StartIndex] = Size;
3970 
3971     // Record this interface -> category map.
3972     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3973     CategoriesMap.push_back(CatInfo);
3974   }
3975 
3976   // Sort the categories map by the definition ID, since the reader will be
3977   // performing binary searches on this information.
3978   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3979 
3980   // Emit the categories map.
3981   using namespace llvm;
3982 
3983   auto *Abbrev = new BitCodeAbbrev();
3984   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3985   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3986   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3987   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3988 
3989   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3990   Stream.EmitRecordWithBlob(AbbrevID, Record,
3991                             reinterpret_cast<char *>(CategoriesMap.data()),
3992                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3993 
3994   // Emit the category lists.
3995   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3996 }
3997 
3998 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3999   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4000 
4001   if (LPTMap.empty())
4002     return;
4003 
4004   RecordData Record;
4005   for (auto LPTMapEntry : LPTMap) {
4006     const FunctionDecl *FD = LPTMapEntry.first;
4007     LateParsedTemplate *LPT = LPTMapEntry.second;
4008     AddDeclRef(FD, Record);
4009     AddDeclRef(LPT->D, Record);
4010     Record.push_back(LPT->Toks.size());
4011 
4012     for (const auto &Tok : LPT->Toks) {
4013       AddToken(Tok, Record);
4014     }
4015   }
4016   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4017 }
4018 
4019 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4020 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4021   RecordData Record;
4022   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4023   AddSourceLocation(PragmaLoc, Record);
4024   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4025 }
4026 
4027 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
4028 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4029   RecordData Record;
4030   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4031   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4032 }
4033 
4034 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
4035 //module.
4036 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4037   RecordData Record;
4038   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4039   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4040   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4041 }
4042 
4043 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4044                                          ModuleFileExtensionWriter &Writer) {
4045   // Enter the extension block.
4046   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4047 
4048   // Emit the metadata record abbreviation.
4049   auto *Abv = new llvm::BitCodeAbbrev();
4050   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4051   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4052   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4053   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4054   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4055   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4056   unsigned Abbrev = Stream.EmitAbbrev(Abv);
4057 
4058   // Emit the metadata record.
4059   RecordData Record;
4060   auto Metadata = Writer.getExtension()->getExtensionMetadata();
4061   Record.push_back(EXTENSION_METADATA);
4062   Record.push_back(Metadata.MajorVersion);
4063   Record.push_back(Metadata.MinorVersion);
4064   Record.push_back(Metadata.BlockName.size());
4065   Record.push_back(Metadata.UserInfo.size());
4066   SmallString<64> Buffer;
4067   Buffer += Metadata.BlockName;
4068   Buffer += Metadata.UserInfo;
4069   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4070 
4071   // Emit the contents of the extension block.
4072   Writer.writeExtensionContents(SemaRef, Stream);
4073 
4074   // Exit the extension block.
4075   Stream.ExitBlock();
4076 }
4077 
4078 //===----------------------------------------------------------------------===//
4079 // General Serialization Routines
4080 //===----------------------------------------------------------------------===//
4081 
4082 /// \brief Emit the list of attributes to the specified record.
4083 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4084   auto &Record = *this;
4085   Record.push_back(Attrs.size());
4086   for (const auto *A : Attrs) {
4087     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4088     Record.AddSourceRange(A->getRange());
4089 
4090 #include "clang/Serialization/AttrPCHWrite.inc"
4091 
4092   }
4093 }
4094 
4095 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4096   AddSourceLocation(Tok.getLocation(), Record);
4097   Record.push_back(Tok.getLength());
4098 
4099   // FIXME: When reading literal tokens, reconstruct the literal pointer
4100   // if it is needed.
4101   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4102   // FIXME: Should translate token kind to a stable encoding.
4103   Record.push_back(Tok.getKind());
4104   // FIXME: Should translate token flags to a stable encoding.
4105   Record.push_back(Tok.getFlags());
4106 }
4107 
4108 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4109   Record.push_back(Str.size());
4110   Record.insert(Record.end(), Str.begin(), Str.end());
4111 }
4112 
4113 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4114   assert(Context && "should have context when outputting path");
4115 
4116   bool Changed =
4117       cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4118 
4119   // Remove a prefix to make the path relative, if relevant.
4120   const char *PathBegin = Path.data();
4121   const char *PathPtr =
4122       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4123   if (PathPtr != PathBegin) {
4124     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4125     Changed = true;
4126   }
4127 
4128   return Changed;
4129 }
4130 
4131 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4132   SmallString<128> FilePath(Path);
4133   PreparePathForOutput(FilePath);
4134   AddString(FilePath, Record);
4135 }
4136 
4137 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4138                                    StringRef Path) {
4139   SmallString<128> FilePath(Path);
4140   PreparePathForOutput(FilePath);
4141   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4142 }
4143 
4144 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4145                                 RecordDataImpl &Record) {
4146   Record.push_back(Version.getMajor());
4147   if (Optional<unsigned> Minor = Version.getMinor())
4148     Record.push_back(*Minor + 1);
4149   else
4150     Record.push_back(0);
4151   if (Optional<unsigned> Subminor = Version.getSubminor())
4152     Record.push_back(*Subminor + 1);
4153   else
4154     Record.push_back(0);
4155 }
4156 
4157 /// \brief Note that the identifier II occurs at the given offset
4158 /// within the identifier table.
4159 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4160   IdentID ID = IdentifierIDs[II];
4161   // Only store offsets new to this AST file. Other identifier names are looked
4162   // up earlier in the chain and thus don't need an offset.
4163   if (ID >= FirstIdentID)
4164     IdentifierOffsets[ID - FirstIdentID] = Offset;
4165 }
4166 
4167 /// \brief Note that the selector Sel occurs at the given offset
4168 /// within the method pool/selector table.
4169 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4170   unsigned ID = SelectorIDs[Sel];
4171   assert(ID && "Unknown selector");
4172   // Don't record offsets for selectors that are also available in a different
4173   // file.
4174   if (ID < FirstSelectorID)
4175     return;
4176   SelectorOffsets[ID - FirstSelectorID] = Offset;
4177 }
4178 
4179 ASTWriter::ASTWriter(
4180   llvm::BitstreamWriter &Stream,
4181   ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4182   bool IncludeTimestamps)
4183     : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
4184       WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4185       WritingAST(false), DoneWritingDeclsAndTypes(false),
4186       ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4187       NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4188       NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4189       NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4190       NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
4191       NextSubmoduleID(FirstSubmoduleID),
4192       FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4193       NumStatements(0), NumMacros(0),
4194       NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
4195       TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
4196       DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
4197       UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
4198       DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
4199       DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4200       CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
4201       ExprImplicitCastAbbrev(0) {
4202   for (const auto &Ext : Extensions) {
4203     if (auto Writer = Ext->createExtensionWriter(*this))
4204       ModuleFileExtensionWriters.push_back(std::move(Writer));
4205   }
4206 }
4207 
4208 ASTWriter::~ASTWriter() {
4209   llvm::DeleteContainerSeconds(FileDeclIDs);
4210 }
4211 
4212 const LangOptions &ASTWriter::getLangOpts() const {
4213   assert(WritingAST && "can't determine lang opts when not writing AST");
4214   return Context->getLangOpts();
4215 }
4216 
4217 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4218   return IncludeTimestamps ? E->getModificationTime() : 0;
4219 }
4220 
4221 uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4222                              Module *WritingModule, StringRef isysroot,
4223                              bool hasErrors) {
4224   WritingAST = true;
4225 
4226   ASTHasCompilerErrors = hasErrors;
4227 
4228   // Emit the file header.
4229   Stream.Emit((unsigned)'C', 8);
4230   Stream.Emit((unsigned)'P', 8);
4231   Stream.Emit((unsigned)'C', 8);
4232   Stream.Emit((unsigned)'H', 8);
4233 
4234   WriteBlockInfoBlock();
4235 
4236   Context = &SemaRef.Context;
4237   PP = &SemaRef.PP;
4238   this->WritingModule = WritingModule;
4239   ASTFileSignature Signature =
4240       WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4241   Context = nullptr;
4242   PP = nullptr;
4243   this->WritingModule = nullptr;
4244   this->BaseDirectory.clear();
4245 
4246   WritingAST = false;
4247   return Signature;
4248 }
4249 
4250 template<typename Vector>
4251 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4252                                ASTWriter::RecordData &Record) {
4253   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4254        I != E; ++I) {
4255     Writer.AddDeclRef(*I, Record);
4256   }
4257 }
4258 
4259 uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4260                                  const std::string &OutputFile,
4261                                  Module *WritingModule) {
4262   using namespace llvm;
4263 
4264   bool isModule = WritingModule != nullptr;
4265 
4266   // Make sure that the AST reader knows to finalize itself.
4267   if (Chain)
4268     Chain->finalizeForWriting();
4269 
4270   ASTContext &Context = SemaRef.Context;
4271   Preprocessor &PP = SemaRef.PP;
4272 
4273   // Set up predefined declaration IDs.
4274   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4275     if (D) {
4276       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4277       DeclIDs[D] = ID;
4278     }
4279   };
4280   RegisterPredefDecl(Context.getTranslationUnitDecl(),
4281                      PREDEF_DECL_TRANSLATION_UNIT_ID);
4282   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4283   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4284   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4285   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4286                      PREDEF_DECL_OBJC_PROTOCOL_ID);
4287   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4288   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4289   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4290                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4291   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4292   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4293   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4294                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4295   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4296   RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4297                      PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4298   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4299                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
4300   RegisterPredefDecl(Context.CFConstantStringTagDecl,
4301                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4302   RegisterPredefDecl(Context.TypePackElementDecl,
4303                      PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4304 
4305   // Build a record containing all of the tentative definitions in this file, in
4306   // TentativeDefinitions order.  Generally, this record will be empty for
4307   // headers.
4308   RecordData TentativeDefinitions;
4309   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4310 
4311   // Build a record containing all of the file scoped decls in this file.
4312   RecordData UnusedFileScopedDecls;
4313   if (!isModule)
4314     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4315                        UnusedFileScopedDecls);
4316 
4317   // Build a record containing all of the delegating constructors we still need
4318   // to resolve.
4319   RecordData DelegatingCtorDecls;
4320   if (!isModule)
4321     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4322 
4323   // Write the set of weak, undeclared identifiers. We always write the
4324   // entire table, since later PCH files in a PCH chain are only interested in
4325   // the results at the end of the chain.
4326   RecordData WeakUndeclaredIdentifiers;
4327   for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4328     IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4329     WeakInfo &WI = WeakUndeclaredIdentifier.second;
4330     AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4331     AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4332     AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4333     WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4334   }
4335 
4336   // Build a record containing all of the ext_vector declarations.
4337   RecordData ExtVectorDecls;
4338   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4339 
4340   // Build a record containing all of the VTable uses information.
4341   RecordData VTableUses;
4342   if (!SemaRef.VTableUses.empty()) {
4343     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4344       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4345       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4346       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4347     }
4348   }
4349 
4350   // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4351   RecordData UnusedLocalTypedefNameCandidates;
4352   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4353     AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4354 
4355   // Build a record containing all of pending implicit instantiations.
4356   RecordData PendingInstantiations;
4357   for (const auto &I : SemaRef.PendingInstantiations) {
4358     AddDeclRef(I.first, PendingInstantiations);
4359     AddSourceLocation(I.second, PendingInstantiations);
4360   }
4361   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4362          "There are local ones at end of translation unit!");
4363 
4364   // Build a record containing some declaration references.
4365   RecordData SemaDeclRefs;
4366   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4367     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4368     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4369   }
4370 
4371   RecordData CUDASpecialDeclRefs;
4372   if (Context.getcudaConfigureCallDecl()) {
4373     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4374   }
4375 
4376   // Build a record containing all of the known namespaces.
4377   RecordData KnownNamespaces;
4378   for (const auto &I : SemaRef.KnownNamespaces) {
4379     if (!I.second)
4380       AddDeclRef(I.first, KnownNamespaces);
4381   }
4382 
4383   // Build a record of all used, undefined objects that require definitions.
4384   RecordData UndefinedButUsed;
4385 
4386   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4387   SemaRef.getUndefinedButUsed(Undefined);
4388   for (const auto &I : Undefined) {
4389     AddDeclRef(I.first, UndefinedButUsed);
4390     AddSourceLocation(I.second, UndefinedButUsed);
4391   }
4392 
4393   // Build a record containing all delete-expressions that we would like to
4394   // analyze later in AST.
4395   RecordData DeleteExprsToAnalyze;
4396 
4397   for (const auto &DeleteExprsInfo :
4398        SemaRef.getMismatchingDeleteExpressions()) {
4399     AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4400     DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4401     for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4402       AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4403       DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4404     }
4405   }
4406 
4407   // Write the control block
4408   uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
4409 
4410   // Write the remaining AST contents.
4411   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4412 
4413   // This is so that older clang versions, before the introduction
4414   // of the control block, can read and reject the newer PCH format.
4415   {
4416     RecordData Record = {VERSION_MAJOR};
4417     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4418   }
4419 
4420   // Create a lexical update block containing all of the declarations in the
4421   // translation unit that do not come from other AST files.
4422   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4423   SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4424   for (const auto *D : TU->noload_decls()) {
4425     if (!D->isFromASTFile()) {
4426       NewGlobalKindDeclPairs.push_back(D->getKind());
4427       NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4428     }
4429   }
4430 
4431   auto *Abv = new llvm::BitCodeAbbrev();
4432   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4433   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4434   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4435   {
4436     RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4437     Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4438                               bytes(NewGlobalKindDeclPairs));
4439   }
4440 
4441   // And a visible updates block for the translation unit.
4442   Abv = new llvm::BitCodeAbbrev();
4443   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4444   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4445   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4446   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4447   WriteDeclContextVisibleUpdate(TU);
4448 
4449   // If we have any extern "C" names, write out a visible update for them.
4450   if (Context.ExternCContext)
4451     WriteDeclContextVisibleUpdate(Context.ExternCContext);
4452 
4453   // If the translation unit has an anonymous namespace, and we don't already
4454   // have an update block for it, write it as an update block.
4455   // FIXME: Why do we not do this if there's already an update block?
4456   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4457     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4458     if (Record.empty())
4459       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4460   }
4461 
4462   // Add update records for all mangling numbers and static local numbers.
4463   // These aren't really update records, but this is a convenient way of
4464   // tagging this rare extra data onto the declarations.
4465   for (const auto &Number : Context.MangleNumbers)
4466     if (!Number.first->isFromASTFile())
4467       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4468                                                      Number.second));
4469   for (const auto &Number : Context.StaticLocalNumbers)
4470     if (!Number.first->isFromASTFile())
4471       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4472                                                      Number.second));
4473 
4474   // Make sure visible decls, added to DeclContexts previously loaded from
4475   // an AST file, are registered for serialization.
4476   for (const auto *I : UpdatingVisibleDecls) {
4477     GetDeclRef(I);
4478   }
4479 
4480   // Make sure all decls associated with an identifier are registered for
4481   // serialization, if we're storing decls with identifiers.
4482   if (!WritingModule || !getLangOpts().CPlusPlus) {
4483     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4484     for (const auto &ID : PP.getIdentifierTable()) {
4485       const IdentifierInfo *II = ID.second;
4486       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4487         IIs.push_back(II);
4488     }
4489     // Sort the identifiers to visit based on their name.
4490     std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4491     for (const IdentifierInfo *II : IIs) {
4492       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4493                                      DEnd = SemaRef.IdResolver.end();
4494            D != DEnd; ++D) {
4495         GetDeclRef(*D);
4496       }
4497     }
4498   }
4499 
4500   // For method pool in the module, if it contains an entry for a selector,
4501   // the entry should be complete, containing everything introduced by that
4502   // module and all modules it imports. It's possible that the entry is out of
4503   // date, so we need to pull in the new content here.
4504 
4505   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4506   // safe, we copy all selectors out.
4507   llvm::SmallVector<Selector, 256> AllSelectors;
4508   for (auto &SelectorAndID : SelectorIDs)
4509     AllSelectors.push_back(SelectorAndID.first);
4510   for (auto &Selector : AllSelectors)
4511     SemaRef.updateOutOfDateSelector(Selector);
4512 
4513   // Form the record of special types.
4514   RecordData SpecialTypes;
4515   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4516   AddTypeRef(Context.getFILEType(), SpecialTypes);
4517   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4518   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4519   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4520   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4521   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4522   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4523 
4524   if (Chain) {
4525     // Write the mapping information describing our module dependencies and how
4526     // each of those modules were mapped into our own offset/ID space, so that
4527     // the reader can build the appropriate mapping to its own offset/ID space.
4528     // The map consists solely of a blob with the following format:
4529     // *(module-name-len:i16 module-name:len*i8
4530     //   source-location-offset:i32
4531     //   identifier-id:i32
4532     //   preprocessed-entity-id:i32
4533     //   macro-definition-id:i32
4534     //   submodule-id:i32
4535     //   selector-id:i32
4536     //   declaration-id:i32
4537     //   c++-base-specifiers-id:i32
4538     //   type-id:i32)
4539     //
4540     auto *Abbrev = new BitCodeAbbrev();
4541     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4542     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4543     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4544     SmallString<2048> Buffer;
4545     {
4546       llvm::raw_svector_ostream Out(Buffer);
4547       for (ModuleFile *M : Chain->ModuleMgr) {
4548         using namespace llvm::support;
4549         endian::Writer<little> LE(Out);
4550         StringRef FileName = M->FileName;
4551         LE.write<uint16_t>(FileName.size());
4552         Out.write(FileName.data(), FileName.size());
4553 
4554         // Note: if a base ID was uint max, it would not be possible to load
4555         // another module after it or have more than one entity inside it.
4556         uint32_t None = std::numeric_limits<uint32_t>::max();
4557 
4558         auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4559           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4560           if (ShouldWrite)
4561             LE.write<uint32_t>(BaseID);
4562           else
4563             LE.write<uint32_t>(None);
4564         };
4565 
4566         // These values should be unique within a chain, since they will be read
4567         // as keys into ContinuousRangeMaps.
4568         writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4569         writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4570         writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4571         writeBaseIDOrNone(M->BasePreprocessedEntityID,
4572                           M->NumPreprocessedEntities);
4573         writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4574         writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4575         writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4576         writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4577       }
4578     }
4579     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4580     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4581                               Buffer.data(), Buffer.size());
4582   }
4583 
4584   RecordData DeclUpdatesOffsetsRecord;
4585 
4586   // Keep writing types, declarations, and declaration update records
4587   // until we've emitted all of them.
4588   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4589   WriteTypeAbbrevs();
4590   WriteDeclAbbrevs();
4591   do {
4592     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4593     while (!DeclTypesToEmit.empty()) {
4594       DeclOrType DOT = DeclTypesToEmit.front();
4595       DeclTypesToEmit.pop();
4596       if (DOT.isType())
4597         WriteType(DOT.getType());
4598       else
4599         WriteDecl(Context, DOT.getDecl());
4600     }
4601   } while (!DeclUpdates.empty());
4602   Stream.ExitBlock();
4603 
4604   DoneWritingDeclsAndTypes = true;
4605 
4606   // These things can only be done once we've written out decls and types.
4607   WriteTypeDeclOffsets();
4608   if (!DeclUpdatesOffsetsRecord.empty())
4609     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4610   WriteFileDeclIDsMap();
4611   WriteSourceManagerBlock(Context.getSourceManager(), PP);
4612   WriteComments();
4613   WritePreprocessor(PP, isModule);
4614   WriteHeaderSearch(PP.getHeaderSearchInfo());
4615   WriteSelectors(SemaRef);
4616   WriteReferencedSelectorsPool(SemaRef);
4617   WriteLateParsedTemplates(SemaRef);
4618   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4619   WriteFPPragmaOptions(SemaRef.getFPOptions());
4620   WriteOpenCLExtensions(SemaRef);
4621   WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4622 
4623   // If we're emitting a module, write out the submodule information.
4624   if (WritingModule)
4625     WriteSubmodules(WritingModule);
4626   else if (!getLangOpts().CurrentModule.empty()) {
4627     // If we're building a PCH in the implementation of a module, we may need
4628     // the description of the current module.
4629     //
4630     // FIXME: We may need other modules that we did not load from an AST file,
4631     // such as if a module declares a 'conflicts' on a different module.
4632     Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
4633         getLangOpts().CurrentModule);
4634     if (M && !M->IsFromModuleFile)
4635       WriteSubmodules(M);
4636   }
4637 
4638   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4639 
4640   // Write the record containing external, unnamed definitions.
4641   if (!EagerlyDeserializedDecls.empty())
4642     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4643 
4644   // Write the record containing tentative definitions.
4645   if (!TentativeDefinitions.empty())
4646     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4647 
4648   // Write the record containing unused file scoped decls.
4649   if (!UnusedFileScopedDecls.empty())
4650     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4651 
4652   // Write the record containing weak undeclared identifiers.
4653   if (!WeakUndeclaredIdentifiers.empty())
4654     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4655                       WeakUndeclaredIdentifiers);
4656 
4657   // Write the record containing ext_vector type names.
4658   if (!ExtVectorDecls.empty())
4659     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4660 
4661   // Write the record containing VTable uses information.
4662   if (!VTableUses.empty())
4663     Stream.EmitRecord(VTABLE_USES, VTableUses);
4664 
4665   // Write the record containing potentially unused local typedefs.
4666   if (!UnusedLocalTypedefNameCandidates.empty())
4667     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4668                       UnusedLocalTypedefNameCandidates);
4669 
4670   // Write the record containing pending implicit instantiations.
4671   if (!PendingInstantiations.empty())
4672     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4673 
4674   // Write the record containing declaration references of Sema.
4675   if (!SemaDeclRefs.empty())
4676     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4677 
4678   // Write the record containing CUDA-specific declaration references.
4679   if (!CUDASpecialDeclRefs.empty())
4680     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4681 
4682   // Write the delegating constructors.
4683   if (!DelegatingCtorDecls.empty())
4684     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4685 
4686   // Write the known namespaces.
4687   if (!KnownNamespaces.empty())
4688     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4689 
4690   // Write the undefined internal functions and variables, and inline functions.
4691   if (!UndefinedButUsed.empty())
4692     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4693 
4694   if (!DeleteExprsToAnalyze.empty())
4695     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4696 
4697   // Write the visible updates to DeclContexts.
4698   for (auto *DC : UpdatedDeclContexts)
4699     WriteDeclContextVisibleUpdate(DC);
4700 
4701   if (!WritingModule) {
4702     // Write the submodules that were imported, if any.
4703     struct ModuleInfo {
4704       uint64_t ID;
4705       Module *M;
4706       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4707     };
4708     llvm::SmallVector<ModuleInfo, 64> Imports;
4709     for (const auto *I : Context.local_imports()) {
4710       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4711       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4712                          I->getImportedModule()));
4713     }
4714 
4715     if (!Imports.empty()) {
4716       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4717         return A.ID < B.ID;
4718       };
4719       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4720         return A.ID == B.ID;
4721       };
4722 
4723       // Sort and deduplicate module IDs.
4724       std::sort(Imports.begin(), Imports.end(), Cmp);
4725       Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4726                     Imports.end());
4727 
4728       RecordData ImportedModules;
4729       for (const auto &Import : Imports) {
4730         ImportedModules.push_back(Import.ID);
4731         // FIXME: If the module has macros imported then later has declarations
4732         // imported, this location won't be the right one as a location for the
4733         // declaration imports.
4734         AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4735       }
4736 
4737       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4738     }
4739   }
4740 
4741   WriteObjCCategories();
4742   if(!WritingModule) {
4743     WriteOptimizePragmaOptions(SemaRef);
4744     WriteMSStructPragmaOptions(SemaRef);
4745     WriteMSPointersToMembersPragmaOptions(SemaRef);
4746   }
4747 
4748   // Some simple statistics
4749   RecordData::value_type Record[] = {
4750       NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4751   Stream.EmitRecord(STATISTICS, Record);
4752   Stream.ExitBlock();
4753 
4754   // Write the module file extension blocks.
4755   for (const auto &ExtWriter : ModuleFileExtensionWriters)
4756     WriteModuleFileExtension(SemaRef, *ExtWriter);
4757 
4758   return Signature;
4759 }
4760 
4761 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4762   if (DeclUpdates.empty())
4763     return;
4764 
4765   DeclUpdateMap LocalUpdates;
4766   LocalUpdates.swap(DeclUpdates);
4767 
4768   for (auto &DeclUpdate : LocalUpdates) {
4769     const Decl *D = DeclUpdate.first;
4770 
4771     bool HasUpdatedBody = false;
4772     RecordData RecordData;
4773     ASTRecordWriter Record(*this, RecordData);
4774     for (auto &Update : DeclUpdate.second) {
4775       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4776 
4777       // An updated body is emitted last, so that the reader doesn't need
4778       // to skip over the lazy body to reach statements for other records.
4779       if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4780         HasUpdatedBody = true;
4781       else
4782         Record.push_back(Kind);
4783 
4784       switch (Kind) {
4785       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4786       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4787       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4788         assert(Update.getDecl() && "no decl to add?");
4789         Record.push_back(GetDeclRef(Update.getDecl()));
4790         break;
4791 
4792       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4793         break;
4794 
4795       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4796         Record.AddSourceLocation(Update.getLoc());
4797         break;
4798 
4799       case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4800         Record.AddStmt(const_cast<Expr *>(
4801             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4802         break;
4803 
4804       case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4805         Record.AddStmt(
4806             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4807         break;
4808 
4809       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4810         auto *RD = cast<CXXRecordDecl>(D);
4811         UpdatedDeclContexts.insert(RD->getPrimaryContext());
4812         Record.AddCXXDefinitionData(RD);
4813         Record.AddOffset(WriteDeclContextLexicalBlock(
4814             *Context, const_cast<CXXRecordDecl *>(RD)));
4815 
4816         // This state is sometimes updated by template instantiation, when we
4817         // switch from the specialization referring to the template declaration
4818         // to it referring to the template definition.
4819         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4820           Record.push_back(MSInfo->getTemplateSpecializationKind());
4821           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4822         } else {
4823           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4824           Record.push_back(Spec->getTemplateSpecializationKind());
4825           Record.AddSourceLocation(Spec->getPointOfInstantiation());
4826 
4827           // The instantiation might have been resolved to a partial
4828           // specialization. If so, record which one.
4829           auto From = Spec->getInstantiatedFrom();
4830           if (auto PartialSpec =
4831                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4832             Record.push_back(true);
4833             Record.AddDeclRef(PartialSpec);
4834             Record.AddTemplateArgumentList(
4835                 &Spec->getTemplateInstantiationArgs());
4836           } else {
4837             Record.push_back(false);
4838           }
4839         }
4840         Record.push_back(RD->getTagKind());
4841         Record.AddSourceLocation(RD->getLocation());
4842         Record.AddSourceLocation(RD->getLocStart());
4843         Record.AddSourceRange(RD->getBraceRange());
4844 
4845         // Instantiation may change attributes; write them all out afresh.
4846         Record.push_back(D->hasAttrs());
4847         if (D->hasAttrs())
4848           Record.AddAttributes(D->getAttrs());
4849 
4850         // FIXME: Ensure we don't get here for explicit instantiations.
4851         break;
4852       }
4853 
4854       case UPD_CXX_RESOLVED_DTOR_DELETE:
4855         Record.AddDeclRef(Update.getDecl());
4856         break;
4857 
4858       case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4859         addExceptionSpec(
4860             cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4861             Record);
4862         break;
4863 
4864       case UPD_CXX_DEDUCED_RETURN_TYPE:
4865         Record.push_back(GetOrCreateTypeID(Update.getType()));
4866         break;
4867 
4868       case UPD_DECL_MARKED_USED:
4869         break;
4870 
4871       case UPD_MANGLING_NUMBER:
4872       case UPD_STATIC_LOCAL_NUMBER:
4873         Record.push_back(Update.getNumber());
4874         break;
4875 
4876       case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4877         Record.AddSourceRange(
4878             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
4879         break;
4880 
4881       case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4882         Record.AddSourceRange(
4883             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4884         break;
4885 
4886       case UPD_DECL_EXPORTED:
4887         Record.push_back(getSubmoduleID(Update.getModule()));
4888         break;
4889 
4890       case UPD_ADDED_ATTR_TO_RECORD:
4891         Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
4892         break;
4893       }
4894     }
4895 
4896     if (HasUpdatedBody) {
4897       const auto *Def = cast<FunctionDecl>(D);
4898       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4899       Record.push_back(Def->isInlined());
4900       Record.AddSourceLocation(Def->getInnerLocStart());
4901       Record.AddFunctionDefinition(Def);
4902     }
4903 
4904     OffsetsRecord.push_back(GetDeclRef(D));
4905     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
4906   }
4907 }
4908 
4909 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4910   uint32_t Raw = Loc.getRawEncoding();
4911   Record.push_back((Raw << 1) | (Raw >> 31));
4912 }
4913 
4914 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4915   AddSourceLocation(Range.getBegin(), Record);
4916   AddSourceLocation(Range.getEnd(), Record);
4917 }
4918 
4919 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4920   Record->push_back(Value.getBitWidth());
4921   const uint64_t *Words = Value.getRawData();
4922   Record->append(Words, Words + Value.getNumWords());
4923 }
4924 
4925 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4926   Record->push_back(Value.isUnsigned());
4927   AddAPInt(Value);
4928 }
4929 
4930 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4931   AddAPInt(Value.bitcastToAPInt());
4932 }
4933 
4934 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4935   Record.push_back(getIdentifierRef(II));
4936 }
4937 
4938 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4939   if (!II)
4940     return 0;
4941 
4942   IdentID &ID = IdentifierIDs[II];
4943   if (ID == 0)
4944     ID = NextIdentID++;
4945   return ID;
4946 }
4947 
4948 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4949   // Don't emit builtin macros like __LINE__ to the AST file unless they
4950   // have been redefined by the header (in which case they are not
4951   // isBuiltinMacro).
4952   if (!MI || MI->isBuiltinMacro())
4953     return 0;
4954 
4955   MacroID &ID = MacroIDs[MI];
4956   if (ID == 0) {
4957     ID = NextMacroID++;
4958     MacroInfoToEmitData Info = { Name, MI, ID };
4959     MacroInfosToEmit.push_back(Info);
4960   }
4961   return ID;
4962 }
4963 
4964 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4965   if (!MI || MI->isBuiltinMacro())
4966     return 0;
4967 
4968   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4969   return MacroIDs[MI];
4970 }
4971 
4972 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4973   return IdentMacroDirectivesOffsetMap.lookup(Name);
4974 }
4975 
4976 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
4977   Record->push_back(Writer->getSelectorRef(SelRef));
4978 }
4979 
4980 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4981   if (Sel.getAsOpaquePtr() == nullptr) {
4982     return 0;
4983   }
4984 
4985   SelectorID SID = SelectorIDs[Sel];
4986   if (SID == 0 && Chain) {
4987     // This might trigger a ReadSelector callback, which will set the ID for
4988     // this selector.
4989     Chain->LoadSelector(Sel);
4990     SID = SelectorIDs[Sel];
4991   }
4992   if (SID == 0) {
4993     SID = NextSelectorID++;
4994     SelectorIDs[Sel] = SID;
4995   }
4996   return SID;
4997 }
4998 
4999 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5000   AddDeclRef(Temp->getDestructor());
5001 }
5002 
5003 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5004     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5005   switch (Kind) {
5006   case TemplateArgument::Expression:
5007     AddStmt(Arg.getAsExpr());
5008     break;
5009   case TemplateArgument::Type:
5010     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5011     break;
5012   case TemplateArgument::Template:
5013     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5014     AddSourceLocation(Arg.getTemplateNameLoc());
5015     break;
5016   case TemplateArgument::TemplateExpansion:
5017     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5018     AddSourceLocation(Arg.getTemplateNameLoc());
5019     AddSourceLocation(Arg.getTemplateEllipsisLoc());
5020     break;
5021   case TemplateArgument::Null:
5022   case TemplateArgument::Integral:
5023   case TemplateArgument::Declaration:
5024   case TemplateArgument::NullPtr:
5025   case TemplateArgument::Pack:
5026     // FIXME: Is this right?
5027     break;
5028   }
5029 }
5030 
5031 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5032   AddTemplateArgument(Arg.getArgument());
5033 
5034   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5035     bool InfoHasSameExpr
5036       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5037     Record->push_back(InfoHasSameExpr);
5038     if (InfoHasSameExpr)
5039       return; // Avoid storing the same expr twice.
5040   }
5041   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5042 }
5043 
5044 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5045   if (!TInfo) {
5046     AddTypeRef(QualType());
5047     return;
5048   }
5049 
5050   AddTypeLoc(TInfo->getTypeLoc());
5051 }
5052 
5053 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5054   AddTypeRef(TL.getType());
5055 
5056   TypeLocWriter TLW(*this);
5057   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5058     TLW.Visit(TL);
5059 }
5060 
5061 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5062   Record.push_back(GetOrCreateTypeID(T));
5063 }
5064 
5065 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5066   assert(Context);
5067   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5068     if (T.isNull())
5069       return TypeIdx();
5070     assert(!T.getLocalFastQualifiers());
5071 
5072     TypeIdx &Idx = TypeIdxs[T];
5073     if (Idx.getIndex() == 0) {
5074       if (DoneWritingDeclsAndTypes) {
5075         assert(0 && "New type seen after serializing all the types to emit!");
5076         return TypeIdx();
5077       }
5078 
5079       // We haven't seen this type before. Assign it a new ID and put it
5080       // into the queue of types to emit.
5081       Idx = TypeIdx(NextTypeID++);
5082       DeclTypesToEmit.push(T);
5083     }
5084     return Idx;
5085   });
5086 }
5087 
5088 TypeID ASTWriter::getTypeID(QualType T) const {
5089   assert(Context);
5090   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5091     if (T.isNull())
5092       return TypeIdx();
5093     assert(!T.getLocalFastQualifiers());
5094 
5095     TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5096     assert(I != TypeIdxs.end() && "Type not emitted!");
5097     return I->second;
5098   });
5099 }
5100 
5101 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5102   Record.push_back(GetDeclRef(D));
5103 }
5104 
5105 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5106   assert(WritingAST && "Cannot request a declaration ID before AST writing");
5107 
5108   if (!D) {
5109     return 0;
5110   }
5111 
5112   // If D comes from an AST file, its declaration ID is already known and
5113   // fixed.
5114   if (D->isFromASTFile())
5115     return D->getGlobalID();
5116 
5117   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5118   DeclID &ID = DeclIDs[D];
5119   if (ID == 0) {
5120     if (DoneWritingDeclsAndTypes) {
5121       assert(0 && "New decl seen after serializing all the decls to emit!");
5122       return 0;
5123     }
5124 
5125     // We haven't seen this declaration before. Give it a new ID and
5126     // enqueue it in the list of declarations to emit.
5127     ID = NextDeclID++;
5128     DeclTypesToEmit.push(const_cast<Decl *>(D));
5129   }
5130 
5131   return ID;
5132 }
5133 
5134 DeclID ASTWriter::getDeclID(const Decl *D) {
5135   if (!D)
5136     return 0;
5137 
5138   // If D comes from an AST file, its declaration ID is already known and
5139   // fixed.
5140   if (D->isFromASTFile())
5141     return D->getGlobalID();
5142 
5143   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5144   return DeclIDs[D];
5145 }
5146 
5147 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5148   assert(ID);
5149   assert(D);
5150 
5151   SourceLocation Loc = D->getLocation();
5152   if (Loc.isInvalid())
5153     return;
5154 
5155   // We only keep track of the file-level declarations of each file.
5156   if (!D->getLexicalDeclContext()->isFileContext())
5157     return;
5158   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5159   // a function/objc method, should not have TU as lexical context.
5160   if (isa<ParmVarDecl>(D))
5161     return;
5162 
5163   SourceManager &SM = Context->getSourceManager();
5164   SourceLocation FileLoc = SM.getFileLoc(Loc);
5165   assert(SM.isLocalSourceLocation(FileLoc));
5166   FileID FID;
5167   unsigned Offset;
5168   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5169   if (FID.isInvalid())
5170     return;
5171   assert(SM.getSLocEntry(FID).isFile());
5172 
5173   DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5174   if (!Info)
5175     Info = new DeclIDInFileInfo();
5176 
5177   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5178   LocDeclIDsTy &Decls = Info->DeclIDs;
5179 
5180   if (Decls.empty() || Decls.back().first <= Offset) {
5181     Decls.push_back(LocDecl);
5182     return;
5183   }
5184 
5185   LocDeclIDsTy::iterator I =
5186       std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5187 
5188   Decls.insert(I, LocDecl);
5189 }
5190 
5191 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5192   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
5193   Record->push_back(Name.getNameKind());
5194   switch (Name.getNameKind()) {
5195   case DeclarationName::Identifier:
5196     AddIdentifierRef(Name.getAsIdentifierInfo());
5197     break;
5198 
5199   case DeclarationName::ObjCZeroArgSelector:
5200   case DeclarationName::ObjCOneArgSelector:
5201   case DeclarationName::ObjCMultiArgSelector:
5202     AddSelectorRef(Name.getObjCSelector());
5203     break;
5204 
5205   case DeclarationName::CXXConstructorName:
5206   case DeclarationName::CXXDestructorName:
5207   case DeclarationName::CXXConversionFunctionName:
5208     AddTypeRef(Name.getCXXNameType());
5209     break;
5210 
5211   case DeclarationName::CXXOperatorName:
5212     Record->push_back(Name.getCXXOverloadedOperator());
5213     break;
5214 
5215   case DeclarationName::CXXLiteralOperatorName:
5216     AddIdentifierRef(Name.getCXXLiteralIdentifier());
5217     break;
5218 
5219   case DeclarationName::CXXUsingDirective:
5220     // No extra data to emit
5221     break;
5222   }
5223 }
5224 
5225 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5226   assert(needsAnonymousDeclarationNumber(D) &&
5227          "expected an anonymous declaration");
5228 
5229   // Number the anonymous declarations within this context, if we've not
5230   // already done so.
5231   auto It = AnonymousDeclarationNumbers.find(D);
5232   if (It == AnonymousDeclarationNumbers.end()) {
5233     auto *DC = D->getLexicalDeclContext();
5234     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5235       AnonymousDeclarationNumbers[ND] = Number;
5236     });
5237 
5238     It = AnonymousDeclarationNumbers.find(D);
5239     assert(It != AnonymousDeclarationNumbers.end() &&
5240            "declaration not found within its lexical context");
5241   }
5242 
5243   return It->second;
5244 }
5245 
5246 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5247                                             DeclarationName Name) {
5248   switch (Name.getNameKind()) {
5249   case DeclarationName::CXXConstructorName:
5250   case DeclarationName::CXXDestructorName:
5251   case DeclarationName::CXXConversionFunctionName:
5252     AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5253     break;
5254 
5255   case DeclarationName::CXXOperatorName:
5256     AddSourceLocation(SourceLocation::getFromRawEncoding(
5257         DNLoc.CXXOperatorName.BeginOpNameLoc));
5258     AddSourceLocation(
5259         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5260     break;
5261 
5262   case DeclarationName::CXXLiteralOperatorName:
5263     AddSourceLocation(SourceLocation::getFromRawEncoding(
5264         DNLoc.CXXLiteralOperatorName.OpNameLoc));
5265     break;
5266 
5267   case DeclarationName::Identifier:
5268   case DeclarationName::ObjCZeroArgSelector:
5269   case DeclarationName::ObjCOneArgSelector:
5270   case DeclarationName::ObjCMultiArgSelector:
5271   case DeclarationName::CXXUsingDirective:
5272     break;
5273   }
5274 }
5275 
5276 void ASTRecordWriter::AddDeclarationNameInfo(
5277     const DeclarationNameInfo &NameInfo) {
5278   AddDeclarationName(NameInfo.getName());
5279   AddSourceLocation(NameInfo.getLoc());
5280   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5281 }
5282 
5283 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5284   AddNestedNameSpecifierLoc(Info.QualifierLoc);
5285   Record->push_back(Info.NumTemplParamLists);
5286   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5287     AddTemplateParameterList(Info.TemplParamLists[i]);
5288 }
5289 
5290 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5291   // Nested name specifiers usually aren't too long. I think that 8 would
5292   // typically accommodate the vast majority.
5293   SmallVector<NestedNameSpecifier *, 8> NestedNames;
5294 
5295   // Push each of the NNS's onto a stack for serialization in reverse order.
5296   while (NNS) {
5297     NestedNames.push_back(NNS);
5298     NNS = NNS->getPrefix();
5299   }
5300 
5301   Record->push_back(NestedNames.size());
5302   while(!NestedNames.empty()) {
5303     NNS = NestedNames.pop_back_val();
5304     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5305     Record->push_back(Kind);
5306     switch (Kind) {
5307     case NestedNameSpecifier::Identifier:
5308       AddIdentifierRef(NNS->getAsIdentifier());
5309       break;
5310 
5311     case NestedNameSpecifier::Namespace:
5312       AddDeclRef(NNS->getAsNamespace());
5313       break;
5314 
5315     case NestedNameSpecifier::NamespaceAlias:
5316       AddDeclRef(NNS->getAsNamespaceAlias());
5317       break;
5318 
5319     case NestedNameSpecifier::TypeSpec:
5320     case NestedNameSpecifier::TypeSpecWithTemplate:
5321       AddTypeRef(QualType(NNS->getAsType(), 0));
5322       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5323       break;
5324 
5325     case NestedNameSpecifier::Global:
5326       // Don't need to write an associated value.
5327       break;
5328 
5329     case NestedNameSpecifier::Super:
5330       AddDeclRef(NNS->getAsRecordDecl());
5331       break;
5332     }
5333   }
5334 }
5335 
5336 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5337   // Nested name specifiers usually aren't too long. I think that 8 would
5338   // typically accommodate the vast majority.
5339   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5340 
5341   // Push each of the nested-name-specifiers's onto a stack for
5342   // serialization in reverse order.
5343   while (NNS) {
5344     NestedNames.push_back(NNS);
5345     NNS = NNS.getPrefix();
5346   }
5347 
5348   Record->push_back(NestedNames.size());
5349   while(!NestedNames.empty()) {
5350     NNS = NestedNames.pop_back_val();
5351     NestedNameSpecifier::SpecifierKind Kind
5352       = NNS.getNestedNameSpecifier()->getKind();
5353     Record->push_back(Kind);
5354     switch (Kind) {
5355     case NestedNameSpecifier::Identifier:
5356       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5357       AddSourceRange(NNS.getLocalSourceRange());
5358       break;
5359 
5360     case NestedNameSpecifier::Namespace:
5361       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5362       AddSourceRange(NNS.getLocalSourceRange());
5363       break;
5364 
5365     case NestedNameSpecifier::NamespaceAlias:
5366       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5367       AddSourceRange(NNS.getLocalSourceRange());
5368       break;
5369 
5370     case NestedNameSpecifier::TypeSpec:
5371     case NestedNameSpecifier::TypeSpecWithTemplate:
5372       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5373       AddTypeLoc(NNS.getTypeLoc());
5374       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5375       break;
5376 
5377     case NestedNameSpecifier::Global:
5378       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5379       break;
5380 
5381     case NestedNameSpecifier::Super:
5382       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5383       AddSourceRange(NNS.getLocalSourceRange());
5384       break;
5385     }
5386   }
5387 }
5388 
5389 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5390   TemplateName::NameKind Kind = Name.getKind();
5391   Record->push_back(Kind);
5392   switch (Kind) {
5393   case TemplateName::Template:
5394     AddDeclRef(Name.getAsTemplateDecl());
5395     break;
5396 
5397   case TemplateName::OverloadedTemplate: {
5398     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5399     Record->push_back(OvT->size());
5400     for (const auto &I : *OvT)
5401       AddDeclRef(I);
5402     break;
5403   }
5404 
5405   case TemplateName::QualifiedTemplate: {
5406     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5407     AddNestedNameSpecifier(QualT->getQualifier());
5408     Record->push_back(QualT->hasTemplateKeyword());
5409     AddDeclRef(QualT->getTemplateDecl());
5410     break;
5411   }
5412 
5413   case TemplateName::DependentTemplate: {
5414     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5415     AddNestedNameSpecifier(DepT->getQualifier());
5416     Record->push_back(DepT->isIdentifier());
5417     if (DepT->isIdentifier())
5418       AddIdentifierRef(DepT->getIdentifier());
5419     else
5420       Record->push_back(DepT->getOperator());
5421     break;
5422   }
5423 
5424   case TemplateName::SubstTemplateTemplateParm: {
5425     SubstTemplateTemplateParmStorage *subst
5426       = Name.getAsSubstTemplateTemplateParm();
5427     AddDeclRef(subst->getParameter());
5428     AddTemplateName(subst->getReplacement());
5429     break;
5430   }
5431 
5432   case TemplateName::SubstTemplateTemplateParmPack: {
5433     SubstTemplateTemplateParmPackStorage *SubstPack
5434       = Name.getAsSubstTemplateTemplateParmPack();
5435     AddDeclRef(SubstPack->getParameterPack());
5436     AddTemplateArgument(SubstPack->getArgumentPack());
5437     break;
5438   }
5439   }
5440 }
5441 
5442 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5443   Record->push_back(Arg.getKind());
5444   switch (Arg.getKind()) {
5445   case TemplateArgument::Null:
5446     break;
5447   case TemplateArgument::Type:
5448     AddTypeRef(Arg.getAsType());
5449     break;
5450   case TemplateArgument::Declaration:
5451     AddDeclRef(Arg.getAsDecl());
5452     AddTypeRef(Arg.getParamTypeForDecl());
5453     break;
5454   case TemplateArgument::NullPtr:
5455     AddTypeRef(Arg.getNullPtrType());
5456     break;
5457   case TemplateArgument::Integral:
5458     AddAPSInt(Arg.getAsIntegral());
5459     AddTypeRef(Arg.getIntegralType());
5460     break;
5461   case TemplateArgument::Template:
5462     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5463     break;
5464   case TemplateArgument::TemplateExpansion:
5465     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5466     if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5467       Record->push_back(*NumExpansions + 1);
5468     else
5469       Record->push_back(0);
5470     break;
5471   case TemplateArgument::Expression:
5472     AddStmt(Arg.getAsExpr());
5473     break;
5474   case TemplateArgument::Pack:
5475     Record->push_back(Arg.pack_size());
5476     for (const auto &P : Arg.pack_elements())
5477       AddTemplateArgument(P);
5478     break;
5479   }
5480 }
5481 
5482 void ASTRecordWriter::AddTemplateParameterList(
5483     const TemplateParameterList *TemplateParams) {
5484   assert(TemplateParams && "No TemplateParams!");
5485   AddSourceLocation(TemplateParams->getTemplateLoc());
5486   AddSourceLocation(TemplateParams->getLAngleLoc());
5487   AddSourceLocation(TemplateParams->getRAngleLoc());
5488   // TODO: Concepts
5489   Record->push_back(TemplateParams->size());
5490   for (const auto &P : *TemplateParams)
5491     AddDeclRef(P);
5492 }
5493 
5494 /// \brief Emit a template argument list.
5495 void ASTRecordWriter::AddTemplateArgumentList(
5496     const TemplateArgumentList *TemplateArgs) {
5497   assert(TemplateArgs && "No TemplateArgs!");
5498   Record->push_back(TemplateArgs->size());
5499   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5500     AddTemplateArgument(TemplateArgs->get(i));
5501 }
5502 
5503 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5504     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5505   assert(ASTTemplArgList && "No ASTTemplArgList!");
5506   AddSourceLocation(ASTTemplArgList->LAngleLoc);
5507   AddSourceLocation(ASTTemplArgList->RAngleLoc);
5508   Record->push_back(ASTTemplArgList->NumTemplateArgs);
5509   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5510   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5511     AddTemplateArgumentLoc(TemplArgs[i]);
5512 }
5513 
5514 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5515   Record->push_back(Set.size());
5516   for (ASTUnresolvedSet::const_iterator
5517          I = Set.begin(), E = Set.end(); I != E; ++I) {
5518     AddDeclRef(I.getDecl());
5519     Record->push_back(I.getAccess());
5520   }
5521 }
5522 
5523 // FIXME: Move this out of the main ASTRecordWriter interface.
5524 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5525   Record->push_back(Base.isVirtual());
5526   Record->push_back(Base.isBaseOfClass());
5527   Record->push_back(Base.getAccessSpecifierAsWritten());
5528   Record->push_back(Base.getInheritConstructors());
5529   AddTypeSourceInfo(Base.getTypeSourceInfo());
5530   AddSourceRange(Base.getSourceRange());
5531   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5532                                           : SourceLocation());
5533 }
5534 
5535 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5536                                       ArrayRef<CXXBaseSpecifier> Bases) {
5537   ASTWriter::RecordData Record;
5538   ASTRecordWriter Writer(W, Record);
5539   Writer.push_back(Bases.size());
5540 
5541   for (auto &Base : Bases)
5542     Writer.AddCXXBaseSpecifier(Base);
5543 
5544   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5545 }
5546 
5547 // FIXME: Move this out of the main ASTRecordWriter interface.
5548 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5549   AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5550 }
5551 
5552 static uint64_t
5553 EmitCXXCtorInitializers(ASTWriter &W,
5554                         ArrayRef<CXXCtorInitializer *> CtorInits) {
5555   ASTWriter::RecordData Record;
5556   ASTRecordWriter Writer(W, Record);
5557   Writer.push_back(CtorInits.size());
5558 
5559   for (auto *Init : CtorInits) {
5560     if (Init->isBaseInitializer()) {
5561       Writer.push_back(CTOR_INITIALIZER_BASE);
5562       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5563       Writer.push_back(Init->isBaseVirtual());
5564     } else if (Init->isDelegatingInitializer()) {
5565       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5566       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5567     } else if (Init->isMemberInitializer()){
5568       Writer.push_back(CTOR_INITIALIZER_MEMBER);
5569       Writer.AddDeclRef(Init->getMember());
5570     } else {
5571       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5572       Writer.AddDeclRef(Init->getIndirectMember());
5573     }
5574 
5575     Writer.AddSourceLocation(Init->getMemberLocation());
5576     Writer.AddStmt(Init->getInit());
5577     Writer.AddSourceLocation(Init->getLParenLoc());
5578     Writer.AddSourceLocation(Init->getRParenLoc());
5579     Writer.push_back(Init->isWritten());
5580     if (Init->isWritten()) {
5581       Writer.push_back(Init->getSourceOrder());
5582     } else {
5583       Writer.push_back(Init->getNumArrayIndices());
5584       for (auto *VD : Init->getArrayIndices())
5585         Writer.AddDeclRef(VD);
5586     }
5587   }
5588 
5589   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5590 }
5591 
5592 // FIXME: Move this out of the main ASTRecordWriter interface.
5593 void ASTRecordWriter::AddCXXCtorInitializers(
5594     ArrayRef<CXXCtorInitializer *> CtorInits) {
5595   AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5596 }
5597 
5598 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5599   auto &Data = D->data();
5600   Record->push_back(Data.IsLambda);
5601   Record->push_back(Data.UserDeclaredConstructor);
5602   Record->push_back(Data.UserDeclaredSpecialMembers);
5603   Record->push_back(Data.Aggregate);
5604   Record->push_back(Data.PlainOldData);
5605   Record->push_back(Data.Empty);
5606   Record->push_back(Data.Polymorphic);
5607   Record->push_back(Data.Abstract);
5608   Record->push_back(Data.IsStandardLayout);
5609   Record->push_back(Data.HasNoNonEmptyBases);
5610   Record->push_back(Data.HasPrivateFields);
5611   Record->push_back(Data.HasProtectedFields);
5612   Record->push_back(Data.HasPublicFields);
5613   Record->push_back(Data.HasMutableFields);
5614   Record->push_back(Data.HasVariantMembers);
5615   Record->push_back(Data.HasOnlyCMembers);
5616   Record->push_back(Data.HasInClassInitializer);
5617   Record->push_back(Data.HasUninitializedReferenceMember);
5618   Record->push_back(Data.HasUninitializedFields);
5619   Record->push_back(Data.HasInheritedConstructor);
5620   Record->push_back(Data.HasInheritedAssignment);
5621   Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5622   Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5623   Record->push_back(Data.NeedOverloadResolutionForDestructor);
5624   Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5625   Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5626   Record->push_back(Data.DefaultedDestructorIsDeleted);
5627   Record->push_back(Data.HasTrivialSpecialMembers);
5628   Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5629   Record->push_back(Data.HasIrrelevantDestructor);
5630   Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5631   Record->push_back(Data.HasDefaultedDefaultConstructor);
5632   Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5633   Record->push_back(Data.HasConstexprDefaultConstructor);
5634   Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5635   Record->push_back(Data.ComputedVisibleConversions);
5636   Record->push_back(Data.UserProvidedDefaultConstructor);
5637   Record->push_back(Data.DeclaredSpecialMembers);
5638   Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5639   Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5640   Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5641   Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5642   // IsLambda bit is already saved.
5643 
5644   Record->push_back(Data.NumBases);
5645   if (Data.NumBases > 0)
5646     AddCXXBaseSpecifiers(Data.bases());
5647 
5648   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5649   Record->push_back(Data.NumVBases);
5650   if (Data.NumVBases > 0)
5651     AddCXXBaseSpecifiers(Data.vbases());
5652 
5653   AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5654   AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5655   // Data.Definition is the owning decl, no need to write it.
5656   AddDeclRef(D->getFirstFriend());
5657 
5658   // Add lambda-specific data.
5659   if (Data.IsLambda) {
5660     auto &Lambda = D->getLambdaData();
5661     Record->push_back(Lambda.Dependent);
5662     Record->push_back(Lambda.IsGenericLambda);
5663     Record->push_back(Lambda.CaptureDefault);
5664     Record->push_back(Lambda.NumCaptures);
5665     Record->push_back(Lambda.NumExplicitCaptures);
5666     Record->push_back(Lambda.ManglingNumber);
5667     AddDeclRef(D->getLambdaContextDecl());
5668     AddTypeSourceInfo(Lambda.MethodTyInfo);
5669     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5670       const LambdaCapture &Capture = Lambda.Captures[I];
5671       AddSourceLocation(Capture.getLocation());
5672       Record->push_back(Capture.isImplicit());
5673       Record->push_back(Capture.getCaptureKind());
5674       switch (Capture.getCaptureKind()) {
5675       case LCK_StarThis:
5676       case LCK_This:
5677       case LCK_VLAType:
5678         break;
5679       case LCK_ByCopy:
5680       case LCK_ByRef:
5681         VarDecl *Var =
5682             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5683         AddDeclRef(Var);
5684         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5685                                                     : SourceLocation());
5686         break;
5687       }
5688     }
5689   }
5690 }
5691 
5692 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5693   assert(Reader && "Cannot remove chain");
5694   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5695   assert(FirstDeclID == NextDeclID &&
5696          FirstTypeID == NextTypeID &&
5697          FirstIdentID == NextIdentID &&
5698          FirstMacroID == NextMacroID &&
5699          FirstSubmoduleID == NextSubmoduleID &&
5700          FirstSelectorID == NextSelectorID &&
5701          "Setting chain after writing has started.");
5702 
5703   Chain = Reader;
5704 
5705   // Note, this will get called multiple times, once one the reader starts up
5706   // and again each time it's done reading a PCH or module.
5707   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5708   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5709   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5710   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5711   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5712   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5713   NextDeclID = FirstDeclID;
5714   NextTypeID = FirstTypeID;
5715   NextIdentID = FirstIdentID;
5716   NextMacroID = FirstMacroID;
5717   NextSelectorID = FirstSelectorID;
5718   NextSubmoduleID = FirstSubmoduleID;
5719 }
5720 
5721 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5722   // Always keep the highest ID. See \p TypeRead() for more information.
5723   IdentID &StoredID = IdentifierIDs[II];
5724   if (ID > StoredID)
5725     StoredID = ID;
5726 }
5727 
5728 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5729   // Always keep the highest ID. See \p TypeRead() for more information.
5730   MacroID &StoredID = MacroIDs[MI];
5731   if (ID > StoredID)
5732     StoredID = ID;
5733 }
5734 
5735 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5736   // Always take the highest-numbered type index. This copes with an interesting
5737   // case for chained AST writing where we schedule writing the type and then,
5738   // later, deserialize the type from another AST. In this case, we want to
5739   // keep the higher-numbered entry so that we can properly write it out to
5740   // the AST file.
5741   TypeIdx &StoredIdx = TypeIdxs[T];
5742   if (Idx.getIndex() >= StoredIdx.getIndex())
5743     StoredIdx = Idx;
5744 }
5745 
5746 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5747   // Always keep the highest ID. See \p TypeRead() for more information.
5748   SelectorID &StoredID = SelectorIDs[S];
5749   if (ID > StoredID)
5750     StoredID = ID;
5751 }
5752 
5753 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5754                                     MacroDefinitionRecord *MD) {
5755   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5756   MacroDefinitions[MD] = ID;
5757 }
5758 
5759 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5760   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5761   SubmoduleIDs[Mod] = ID;
5762 }
5763 
5764 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5765   if (Chain && Chain->isProcessingUpdateRecords()) return;
5766   assert(D->isCompleteDefinition());
5767   assert(!WritingAST && "Already writing the AST!");
5768   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5769     // We are interested when a PCH decl is modified.
5770     if (RD->isFromASTFile()) {
5771       // A forward reference was mutated into a definition. Rewrite it.
5772       // FIXME: This happens during template instantiation, should we
5773       // have created a new definition decl instead ?
5774       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5775              "completed a tag from another module but not by instantiation?");
5776       DeclUpdates[RD].push_back(
5777           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5778     }
5779   }
5780 }
5781 
5782 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5783   if (D->isFromASTFile())
5784     return true;
5785 
5786   // The predefined __va_list_tag struct is imported if we imported any decls.
5787   // FIXME: This is a gross hack.
5788   return D == D->getASTContext().getVaListTagDecl();
5789 }
5790 
5791 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5792   if (Chain && Chain->isProcessingUpdateRecords()) return;
5793   assert(DC->isLookupContext() &&
5794           "Should not add lookup results to non-lookup contexts!");
5795 
5796   // TU is handled elsewhere.
5797   if (isa<TranslationUnitDecl>(DC))
5798     return;
5799 
5800   // Namespaces are handled elsewhere, except for template instantiations of
5801   // FunctionTemplateDecls in namespaces. We are interested in cases where the
5802   // local instantiations are added to an imported context. Only happens when
5803   // adding ADL lookup candidates, for example templated friends.
5804   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5805       !isa<FunctionTemplateDecl>(D))
5806     return;
5807 
5808   // We're only interested in cases where a local declaration is added to an
5809   // imported context.
5810   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5811     return;
5812 
5813   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5814   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5815   assert(!WritingAST && "Already writing the AST!");
5816   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5817     // We're adding a visible declaration to a predefined decl context. Ensure
5818     // that we write out all of its lookup results so we don't get a nasty
5819     // surprise when we try to emit its lookup table.
5820     for (auto *Child : DC->decls())
5821       UpdatingVisibleDecls.push_back(Child);
5822   }
5823   UpdatingVisibleDecls.push_back(D);
5824 }
5825 
5826 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5827   if (Chain && Chain->isProcessingUpdateRecords()) return;
5828   assert(D->isImplicit());
5829 
5830   // We're only interested in cases where a local declaration is added to an
5831   // imported context.
5832   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5833     return;
5834 
5835   if (!isa<CXXMethodDecl>(D))
5836     return;
5837 
5838   // A decl coming from PCH was modified.
5839   assert(RD->isCompleteDefinition());
5840   assert(!WritingAST && "Already writing the AST!");
5841   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5842 }
5843 
5844 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5845   if (Chain && Chain->isProcessingUpdateRecords()) return;
5846   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5847   if (!Chain) return;
5848   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5849     // If we don't already know the exception specification for this redecl
5850     // chain, add an update record for it.
5851     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5852                                       ->getType()
5853                                       ->castAs<FunctionProtoType>()
5854                                       ->getExceptionSpecType()))
5855       DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5856   });
5857 }
5858 
5859 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5860   if (Chain && Chain->isProcessingUpdateRecords()) return;
5861   assert(!WritingAST && "Already writing the AST!");
5862   if (!Chain) return;
5863   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5864     DeclUpdates[D].push_back(
5865         DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5866   });
5867 }
5868 
5869 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5870                                        const FunctionDecl *Delete) {
5871   if (Chain && Chain->isProcessingUpdateRecords()) return;
5872   assert(!WritingAST && "Already writing the AST!");
5873   assert(Delete && "Not given an operator delete");
5874   if (!Chain) return;
5875   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5876     DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5877   });
5878 }
5879 
5880 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5881   if (Chain && Chain->isProcessingUpdateRecords()) return;
5882   assert(!WritingAST && "Already writing the AST!");
5883   if (!D->isFromASTFile())
5884     return; // Declaration not imported from PCH.
5885 
5886   // Implicit function decl from a PCH was defined.
5887   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5888 }
5889 
5890 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5891   if (Chain && Chain->isProcessingUpdateRecords()) return;
5892   assert(!WritingAST && "Already writing the AST!");
5893   if (!D->isFromASTFile())
5894     return;
5895 
5896   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5897 }
5898 
5899 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5900   if (Chain && Chain->isProcessingUpdateRecords()) return;
5901   assert(!WritingAST && "Already writing the AST!");
5902   if (!D->isFromASTFile())
5903     return;
5904 
5905   // Since the actual instantiation is delayed, this really means that we need
5906   // to update the instantiation location.
5907   DeclUpdates[D].push_back(
5908       DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5909        D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5910 }
5911 
5912 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5913   if (Chain && Chain->isProcessingUpdateRecords()) return;
5914   assert(!WritingAST && "Already writing the AST!");
5915   if (!D->isFromASTFile())
5916     return;
5917 
5918   DeclUpdates[D].push_back(
5919       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5920 }
5921 
5922 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5923   assert(!WritingAST && "Already writing the AST!");
5924   if (!D->isFromASTFile())
5925     return;
5926 
5927   DeclUpdates[D].push_back(
5928       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5929 }
5930 
5931 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5932                                              const ObjCInterfaceDecl *IFD) {
5933   if (Chain && Chain->isProcessingUpdateRecords()) return;
5934   assert(!WritingAST && "Already writing the AST!");
5935   if (!IFD->isFromASTFile())
5936     return; // Declaration not imported from PCH.
5937 
5938   assert(IFD->getDefinition() && "Category on a class without a definition?");
5939   ObjCClassesWithCategories.insert(
5940     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5941 }
5942 
5943 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5944   if (Chain && Chain->isProcessingUpdateRecords()) return;
5945   assert(!WritingAST && "Already writing the AST!");
5946 
5947   // If there is *any* declaration of the entity that's not from an AST file,
5948   // we can skip writing the update record. We make sure that isUsed() triggers
5949   // completion of the redeclaration chain of the entity.
5950   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5951     if (IsLocalDecl(Prev))
5952       return;
5953 
5954   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5955 }
5956 
5957 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5958   if (Chain && Chain->isProcessingUpdateRecords()) return;
5959   assert(!WritingAST && "Already writing the AST!");
5960   if (!D->isFromASTFile())
5961     return;
5962 
5963   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5964 }
5965 
5966 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5967                                                      const Attr *Attr) {
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(
5974       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
5975 }
5976 
5977 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5978   if (Chain && Chain->isProcessingUpdateRecords()) return;
5979   assert(!WritingAST && "Already writing the AST!");
5980   assert(D->isHidden() && "expected a hidden declaration");
5981   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
5982 }
5983 
5984 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5985                                        const RecordDecl *Record) {
5986   if (Chain && Chain->isProcessingUpdateRecords()) return;
5987   assert(!WritingAST && "Already writing the AST!");
5988   if (!Record->isFromASTFile())
5989     return;
5990   DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5991 }
5992