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