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