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