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/Sema/Sema.h"
17 #include "clang/Sema/IdentifierResolver.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLocVisitor.h"
27 #include "clang/Serialization/ASTReader.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/PreprocessingRecord.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Basic/FileManager.h"
33 #include "clang/Basic/FileSystemStatCache.h"
34 #include "clang/Basic/OnDiskHashTable.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/SourceManagerInternals.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/Version.h"
39 #include "clang/Basic/VersionTuple.h"
40 #include "llvm/ADT/APFloat.h"
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Bitcode/BitstreamWriter.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include <algorithm>
48 #include <cstdio>
49 #include <string.h>
50 #include <utility>
51 using namespace clang;
52 using namespace clang::serialization;
53 
54 template <typename T, typename Allocator>
55 static StringRef data(const std::vector<T, Allocator> &v) {
56   if (v.empty()) return StringRef();
57   return StringRef(reinterpret_cast<const char*>(&v[0]),
58                          sizeof(T) * v.size());
59 }
60 
61 template <typename T>
62 static StringRef data(const SmallVectorImpl<T> &v) {
63   return StringRef(reinterpret_cast<const char*>(v.data()),
64                          sizeof(T) * v.size());
65 }
66 
67 //===----------------------------------------------------------------------===//
68 // Type serialization
69 //===----------------------------------------------------------------------===//
70 
71 namespace {
72   class ASTTypeWriter {
73     ASTWriter &Writer;
74     ASTWriter::RecordDataImpl &Record;
75 
76   public:
77     /// \brief Type code that corresponds to the record generated.
78     TypeCode Code;
79 
80     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
81       : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
82 
83     void VisitArrayType(const ArrayType *T);
84     void VisitFunctionType(const FunctionType *T);
85     void VisitTagType(const TagType *T);
86 
87 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
88 #define ABSTRACT_TYPE(Class, Base)
89 #include "clang/AST/TypeNodes.def"
90   };
91 }
92 
93 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
94   llvm_unreachable("Built-in types are never serialized");
95 }
96 
97 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
98   Writer.AddTypeRef(T->getElementType(), Record);
99   Code = TYPE_COMPLEX;
100 }
101 
102 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
103   Writer.AddTypeRef(T->getPointeeType(), Record);
104   Code = TYPE_POINTER;
105 }
106 
107 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
108   Writer.AddTypeRef(T->getPointeeType(), Record);
109   Code = TYPE_BLOCK_POINTER;
110 }
111 
112 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
113   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
114   Record.push_back(T->isSpelledAsLValue());
115   Code = TYPE_LVALUE_REFERENCE;
116 }
117 
118 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
119   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
120   Code = TYPE_RVALUE_REFERENCE;
121 }
122 
123 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
124   Writer.AddTypeRef(T->getPointeeType(), Record);
125   Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
126   Code = TYPE_MEMBER_POINTER;
127 }
128 
129 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
130   Writer.AddTypeRef(T->getElementType(), Record);
131   Record.push_back(T->getSizeModifier()); // FIXME: stable values
132   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
133 }
134 
135 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
136   VisitArrayType(T);
137   Writer.AddAPInt(T->getSize(), Record);
138   Code = TYPE_CONSTANT_ARRAY;
139 }
140 
141 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
142   VisitArrayType(T);
143   Code = TYPE_INCOMPLETE_ARRAY;
144 }
145 
146 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
147   VisitArrayType(T);
148   Writer.AddSourceLocation(T->getLBracketLoc(), Record);
149   Writer.AddSourceLocation(T->getRBracketLoc(), Record);
150   Writer.AddStmt(T->getSizeExpr());
151   Code = TYPE_VARIABLE_ARRAY;
152 }
153 
154 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
155   Writer.AddTypeRef(T->getElementType(), Record);
156   Record.push_back(T->getNumElements());
157   Record.push_back(T->getVectorKind());
158   Code = TYPE_VECTOR;
159 }
160 
161 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
162   VisitVectorType(T);
163   Code = TYPE_EXT_VECTOR;
164 }
165 
166 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
167   Writer.AddTypeRef(T->getResultType(), Record);
168   FunctionType::ExtInfo C = T->getExtInfo();
169   Record.push_back(C.getNoReturn());
170   Record.push_back(C.getHasRegParm());
171   Record.push_back(C.getRegParm());
172   // FIXME: need to stabilize encoding of calling convention...
173   Record.push_back(C.getCC());
174   Record.push_back(C.getProducesResult());
175 }
176 
177 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
178   VisitFunctionType(T);
179   Code = TYPE_FUNCTION_NO_PROTO;
180 }
181 
182 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
183   VisitFunctionType(T);
184   Record.push_back(T->getNumArgs());
185   for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
186     Writer.AddTypeRef(T->getArgType(I), Record);
187   Record.push_back(T->isVariadic());
188   Record.push_back(T->getTypeQuals());
189   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
190   Record.push_back(T->getExceptionSpecType());
191   if (T->getExceptionSpecType() == EST_Dynamic) {
192     Record.push_back(T->getNumExceptions());
193     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
194       Writer.AddTypeRef(T->getExceptionType(I), Record);
195   } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
196     Writer.AddStmt(T->getNoexceptExpr());
197   }
198   Code = TYPE_FUNCTION_PROTO;
199 }
200 
201 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
202   Writer.AddDeclRef(T->getDecl(), Record);
203   Code = TYPE_UNRESOLVED_USING;
204 }
205 
206 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
207   Writer.AddDeclRef(T->getDecl(), Record);
208   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
209   Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
210   Code = TYPE_TYPEDEF;
211 }
212 
213 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
214   Writer.AddStmt(T->getUnderlyingExpr());
215   Code = TYPE_TYPEOF_EXPR;
216 }
217 
218 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
219   Writer.AddTypeRef(T->getUnderlyingType(), Record);
220   Code = TYPE_TYPEOF;
221 }
222 
223 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
224   Writer.AddStmt(T->getUnderlyingExpr());
225   Code = TYPE_DECLTYPE;
226 }
227 
228 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
229   Writer.AddTypeRef(T->getBaseType(), Record);
230   Writer.AddTypeRef(T->getUnderlyingType(), Record);
231   Record.push_back(T->getUTTKind());
232   Code = TYPE_UNARY_TRANSFORM;
233 }
234 
235 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
236   Writer.AddTypeRef(T->getDeducedType(), Record);
237   Code = TYPE_AUTO;
238 }
239 
240 void ASTTypeWriter::VisitTagType(const TagType *T) {
241   Record.push_back(T->isDependentType());
242   Writer.AddDeclRef(T->getDecl(), Record);
243   assert(!T->isBeingDefined() &&
244          "Cannot serialize in the middle of a type definition");
245 }
246 
247 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
248   VisitTagType(T);
249   Code = TYPE_RECORD;
250 }
251 
252 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
253   VisitTagType(T);
254   Code = TYPE_ENUM;
255 }
256 
257 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
258   Writer.AddTypeRef(T->getModifiedType(), Record);
259   Writer.AddTypeRef(T->getEquivalentType(), Record);
260   Record.push_back(T->getAttrKind());
261   Code = TYPE_ATTRIBUTED;
262 }
263 
264 void
265 ASTTypeWriter::VisitSubstTemplateTypeParmType(
266                                         const SubstTemplateTypeParmType *T) {
267   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
268   Writer.AddTypeRef(T->getReplacementType(), Record);
269   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
270 }
271 
272 void
273 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
274                                       const SubstTemplateTypeParmPackType *T) {
275   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
276   Writer.AddTemplateArgument(T->getArgumentPack(), Record);
277   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
278 }
279 
280 void
281 ASTTypeWriter::VisitTemplateSpecializationType(
282                                        const TemplateSpecializationType *T) {
283   Record.push_back(T->isDependentType());
284   Writer.AddTemplateName(T->getTemplateName(), Record);
285   Record.push_back(T->getNumArgs());
286   for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
287          ArgI != ArgE; ++ArgI)
288     Writer.AddTemplateArgument(*ArgI, Record);
289   Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
290                     T->isCanonicalUnqualified() ? QualType()
291                                                 : T->getCanonicalTypeInternal(),
292                     Record);
293   Code = TYPE_TEMPLATE_SPECIALIZATION;
294 }
295 
296 void
297 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
298   VisitArrayType(T);
299   Writer.AddStmt(T->getSizeExpr());
300   Writer.AddSourceRange(T->getBracketsRange(), Record);
301   Code = TYPE_DEPENDENT_SIZED_ARRAY;
302 }
303 
304 void
305 ASTTypeWriter::VisitDependentSizedExtVectorType(
306                                         const DependentSizedExtVectorType *T) {
307   // FIXME: Serialize this type (C++ only)
308   llvm_unreachable("Cannot serialize dependent sized extended vector types");
309 }
310 
311 void
312 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
313   Record.push_back(T->getDepth());
314   Record.push_back(T->getIndex());
315   Record.push_back(T->isParameterPack());
316   Writer.AddDeclRef(T->getDecl(), Record);
317   Code = TYPE_TEMPLATE_TYPE_PARM;
318 }
319 
320 void
321 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
322   Record.push_back(T->getKeyword());
323   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
324   Writer.AddIdentifierRef(T->getIdentifier(), Record);
325   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
326                                                 : T->getCanonicalTypeInternal(),
327                     Record);
328   Code = TYPE_DEPENDENT_NAME;
329 }
330 
331 void
332 ASTTypeWriter::VisitDependentTemplateSpecializationType(
333                                 const DependentTemplateSpecializationType *T) {
334   Record.push_back(T->getKeyword());
335   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
336   Writer.AddIdentifierRef(T->getIdentifier(), Record);
337   Record.push_back(T->getNumArgs());
338   for (DependentTemplateSpecializationType::iterator
339          I = T->begin(), E = T->end(); I != E; ++I)
340     Writer.AddTemplateArgument(*I, Record);
341   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
342 }
343 
344 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
345   Writer.AddTypeRef(T->getPattern(), Record);
346   if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
347     Record.push_back(*NumExpansions + 1);
348   else
349     Record.push_back(0);
350   Code = TYPE_PACK_EXPANSION;
351 }
352 
353 void ASTTypeWriter::VisitParenType(const ParenType *T) {
354   Writer.AddTypeRef(T->getInnerType(), Record);
355   Code = TYPE_PAREN;
356 }
357 
358 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
359   Record.push_back(T->getKeyword());
360   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
361   Writer.AddTypeRef(T->getNamedType(), Record);
362   Code = TYPE_ELABORATED;
363 }
364 
365 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
366   Writer.AddDeclRef(T->getDecl(), Record);
367   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
368   Code = TYPE_INJECTED_CLASS_NAME;
369 }
370 
371 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
372   Writer.AddDeclRef(T->getDecl(), Record);
373   Code = TYPE_OBJC_INTERFACE;
374 }
375 
376 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
377   Writer.AddTypeRef(T->getBaseType(), Record);
378   Record.push_back(T->getNumProtocols());
379   for (ObjCObjectType::qual_iterator I = T->qual_begin(),
380        E = T->qual_end(); I != E; ++I)
381     Writer.AddDeclRef(*I, Record);
382   Code = TYPE_OBJC_OBJECT;
383 }
384 
385 void
386 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
387   Writer.AddTypeRef(T->getPointeeType(), Record);
388   Code = TYPE_OBJC_OBJECT_POINTER;
389 }
390 
391 void
392 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
393   Writer.AddTypeRef(T->getValueType(), Record);
394   Code = TYPE_ATOMIC;
395 }
396 
397 namespace {
398 
399 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
400   ASTWriter &Writer;
401   ASTWriter::RecordDataImpl &Record;
402 
403 public:
404   TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
405     : Writer(Writer), Record(Record) { }
406 
407 #define ABSTRACT_TYPELOC(CLASS, PARENT)
408 #define TYPELOC(CLASS, PARENT) \
409     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
410 #include "clang/AST/TypeLocNodes.def"
411 
412   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
413   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
414 };
415 
416 }
417 
418 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
419   // nothing to do
420 }
421 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
422   Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
423   if (TL.needsExtraLocalData()) {
424     Record.push_back(TL.getWrittenTypeSpec());
425     Record.push_back(TL.getWrittenSignSpec());
426     Record.push_back(TL.getWrittenWidthSpec());
427     Record.push_back(TL.hasModeAttr());
428   }
429 }
430 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
431   Writer.AddSourceLocation(TL.getNameLoc(), Record);
432 }
433 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
434   Writer.AddSourceLocation(TL.getStarLoc(), Record);
435 }
436 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
437   Writer.AddSourceLocation(TL.getCaretLoc(), Record);
438 }
439 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
440   Writer.AddSourceLocation(TL.getAmpLoc(), Record);
441 }
442 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
443   Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
444 }
445 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
446   Writer.AddSourceLocation(TL.getStarLoc(), Record);
447   Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
448 }
449 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
450   Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
451   Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
452   Record.push_back(TL.getSizeExpr() ? 1 : 0);
453   if (TL.getSizeExpr())
454     Writer.AddStmt(TL.getSizeExpr());
455 }
456 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
457   VisitArrayTypeLoc(TL);
458 }
459 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
460   VisitArrayTypeLoc(TL);
461 }
462 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
463   VisitArrayTypeLoc(TL);
464 }
465 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
466                                             DependentSizedArrayTypeLoc TL) {
467   VisitArrayTypeLoc(TL);
468 }
469 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
470                                         DependentSizedExtVectorTypeLoc TL) {
471   Writer.AddSourceLocation(TL.getNameLoc(), Record);
472 }
473 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
474   Writer.AddSourceLocation(TL.getNameLoc(), Record);
475 }
476 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
477   Writer.AddSourceLocation(TL.getNameLoc(), Record);
478 }
479 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
480   Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
481   Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
482   Record.push_back(TL.getTrailingReturn());
483   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
484     Writer.AddDeclRef(TL.getArg(i), Record);
485 }
486 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
487   VisitFunctionTypeLoc(TL);
488 }
489 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
490   VisitFunctionTypeLoc(TL);
491 }
492 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
493   Writer.AddSourceLocation(TL.getNameLoc(), Record);
494 }
495 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
496   Writer.AddSourceLocation(TL.getNameLoc(), Record);
497 }
498 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
499   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
500   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
501   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
502 }
503 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
504   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
505   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
506   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
507   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
508 }
509 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
510   Writer.AddSourceLocation(TL.getNameLoc(), Record);
511 }
512 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
513   Writer.AddSourceLocation(TL.getKWLoc(), Record);
514   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
515   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
516   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
517 }
518 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
519   Writer.AddSourceLocation(TL.getNameLoc(), Record);
520 }
521 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
522   Writer.AddSourceLocation(TL.getNameLoc(), Record);
523 }
524 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
525   Writer.AddSourceLocation(TL.getNameLoc(), Record);
526 }
527 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
528   Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
529   if (TL.hasAttrOperand()) {
530     SourceRange range = TL.getAttrOperandParensRange();
531     Writer.AddSourceLocation(range.getBegin(), Record);
532     Writer.AddSourceLocation(range.getEnd(), Record);
533   }
534   if (TL.hasAttrExprOperand()) {
535     Expr *operand = TL.getAttrExprOperand();
536     Record.push_back(operand ? 1 : 0);
537     if (operand) Writer.AddStmt(operand);
538   } else if (TL.hasAttrEnumOperand()) {
539     Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
540   }
541 }
542 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
543   Writer.AddSourceLocation(TL.getNameLoc(), Record);
544 }
545 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
546                                             SubstTemplateTypeParmTypeLoc TL) {
547   Writer.AddSourceLocation(TL.getNameLoc(), Record);
548 }
549 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
550                                           SubstTemplateTypeParmPackTypeLoc TL) {
551   Writer.AddSourceLocation(TL.getNameLoc(), Record);
552 }
553 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
554                                            TemplateSpecializationTypeLoc TL) {
555   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
556   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
557   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
558   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
559     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
560                                       TL.getArgLoc(i).getLocInfo(), Record);
561 }
562 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
563   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
564   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
565 }
566 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
567   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
568   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
569 }
570 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
571   Writer.AddSourceLocation(TL.getNameLoc(), Record);
572 }
573 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
574   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
575   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
576   Writer.AddSourceLocation(TL.getNameLoc(), Record);
577 }
578 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
579        DependentTemplateSpecializationTypeLoc TL) {
580   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
581   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
582   Writer.AddSourceLocation(TL.getNameLoc(), Record);
583   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
584   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
585   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
586     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
587                                       TL.getArgLoc(I).getLocInfo(), Record);
588 }
589 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
590   Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
591 }
592 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
593   Writer.AddSourceLocation(TL.getNameLoc(), Record);
594 }
595 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
596   Record.push_back(TL.hasBaseTypeAsWritten());
597   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
598   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
599   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
600     Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
601 }
602 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
603   Writer.AddSourceLocation(TL.getStarLoc(), Record);
604 }
605 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
606   Writer.AddSourceLocation(TL.getKWLoc(), Record);
607   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
608   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
609 }
610 
611 //===----------------------------------------------------------------------===//
612 // ASTWriter Implementation
613 //===----------------------------------------------------------------------===//
614 
615 static void EmitBlockID(unsigned ID, const char *Name,
616                         llvm::BitstreamWriter &Stream,
617                         ASTWriter::RecordDataImpl &Record) {
618   Record.clear();
619   Record.push_back(ID);
620   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
621 
622   // Emit the block name if present.
623   if (Name == 0 || Name[0] == 0) return;
624   Record.clear();
625   while (*Name)
626     Record.push_back(*Name++);
627   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
628 }
629 
630 static void EmitRecordID(unsigned ID, const char *Name,
631                          llvm::BitstreamWriter &Stream,
632                          ASTWriter::RecordDataImpl &Record) {
633   Record.clear();
634   Record.push_back(ID);
635   while (*Name)
636     Record.push_back(*Name++);
637   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
638 }
639 
640 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
641                           ASTWriter::RecordDataImpl &Record) {
642 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
643   RECORD(STMT_STOP);
644   RECORD(STMT_NULL_PTR);
645   RECORD(STMT_NULL);
646   RECORD(STMT_COMPOUND);
647   RECORD(STMT_CASE);
648   RECORD(STMT_DEFAULT);
649   RECORD(STMT_LABEL);
650   RECORD(STMT_IF);
651   RECORD(STMT_SWITCH);
652   RECORD(STMT_WHILE);
653   RECORD(STMT_DO);
654   RECORD(STMT_FOR);
655   RECORD(STMT_GOTO);
656   RECORD(STMT_INDIRECT_GOTO);
657   RECORD(STMT_CONTINUE);
658   RECORD(STMT_BREAK);
659   RECORD(STMT_RETURN);
660   RECORD(STMT_DECL);
661   RECORD(STMT_ASM);
662   RECORD(EXPR_PREDEFINED);
663   RECORD(EXPR_DECL_REF);
664   RECORD(EXPR_INTEGER_LITERAL);
665   RECORD(EXPR_FLOATING_LITERAL);
666   RECORD(EXPR_IMAGINARY_LITERAL);
667   RECORD(EXPR_STRING_LITERAL);
668   RECORD(EXPR_CHARACTER_LITERAL);
669   RECORD(EXPR_PAREN);
670   RECORD(EXPR_UNARY_OPERATOR);
671   RECORD(EXPR_SIZEOF_ALIGN_OF);
672   RECORD(EXPR_ARRAY_SUBSCRIPT);
673   RECORD(EXPR_CALL);
674   RECORD(EXPR_MEMBER);
675   RECORD(EXPR_BINARY_OPERATOR);
676   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
677   RECORD(EXPR_CONDITIONAL_OPERATOR);
678   RECORD(EXPR_IMPLICIT_CAST);
679   RECORD(EXPR_CSTYLE_CAST);
680   RECORD(EXPR_COMPOUND_LITERAL);
681   RECORD(EXPR_EXT_VECTOR_ELEMENT);
682   RECORD(EXPR_INIT_LIST);
683   RECORD(EXPR_DESIGNATED_INIT);
684   RECORD(EXPR_IMPLICIT_VALUE_INIT);
685   RECORD(EXPR_VA_ARG);
686   RECORD(EXPR_ADDR_LABEL);
687   RECORD(EXPR_STMT);
688   RECORD(EXPR_CHOOSE);
689   RECORD(EXPR_GNU_NULL);
690   RECORD(EXPR_SHUFFLE_VECTOR);
691   RECORD(EXPR_BLOCK);
692   RECORD(EXPR_BLOCK_DECL_REF);
693   RECORD(EXPR_GENERIC_SELECTION);
694   RECORD(EXPR_OBJC_STRING_LITERAL);
695   RECORD(EXPR_OBJC_ENCODE);
696   RECORD(EXPR_OBJC_SELECTOR_EXPR);
697   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
698   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
699   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
700   RECORD(EXPR_OBJC_KVC_REF_EXPR);
701   RECORD(EXPR_OBJC_MESSAGE_EXPR);
702   RECORD(STMT_OBJC_FOR_COLLECTION);
703   RECORD(STMT_OBJC_CATCH);
704   RECORD(STMT_OBJC_FINALLY);
705   RECORD(STMT_OBJC_AT_TRY);
706   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
707   RECORD(STMT_OBJC_AT_THROW);
708   RECORD(EXPR_CXX_OPERATOR_CALL);
709   RECORD(EXPR_CXX_CONSTRUCT);
710   RECORD(EXPR_CXX_STATIC_CAST);
711   RECORD(EXPR_CXX_DYNAMIC_CAST);
712   RECORD(EXPR_CXX_REINTERPRET_CAST);
713   RECORD(EXPR_CXX_CONST_CAST);
714   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
715   RECORD(EXPR_CXX_BOOL_LITERAL);
716   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
717   RECORD(EXPR_CXX_TYPEID_EXPR);
718   RECORD(EXPR_CXX_TYPEID_TYPE);
719   RECORD(EXPR_CXX_UUIDOF_EXPR);
720   RECORD(EXPR_CXX_UUIDOF_TYPE);
721   RECORD(EXPR_CXX_THIS);
722   RECORD(EXPR_CXX_THROW);
723   RECORD(EXPR_CXX_DEFAULT_ARG);
724   RECORD(EXPR_CXX_BIND_TEMPORARY);
725   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
726   RECORD(EXPR_CXX_NEW);
727   RECORD(EXPR_CXX_DELETE);
728   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
729   RECORD(EXPR_EXPR_WITH_CLEANUPS);
730   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
731   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
732   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
733   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
734   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
735   RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
736   RECORD(EXPR_CXX_NOEXCEPT);
737   RECORD(EXPR_OPAQUE_VALUE);
738   RECORD(EXPR_BINARY_TYPE_TRAIT);
739   RECORD(EXPR_PACK_EXPANSION);
740   RECORD(EXPR_SIZEOF_PACK);
741   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
742   RECORD(EXPR_CUDA_KERNEL_CALL);
743 #undef RECORD
744 }
745 
746 void ASTWriter::WriteBlockInfoBlock() {
747   RecordData Record;
748   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
749 
750 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
751 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
752 
753   // AST Top-Level Block.
754   BLOCK(AST_BLOCK);
755   RECORD(ORIGINAL_FILE_NAME);
756   RECORD(ORIGINAL_FILE_ID);
757   RECORD(TYPE_OFFSET);
758   RECORD(DECL_OFFSET);
759   RECORD(LANGUAGE_OPTIONS);
760   RECORD(METADATA);
761   RECORD(IDENTIFIER_OFFSET);
762   RECORD(IDENTIFIER_TABLE);
763   RECORD(EXTERNAL_DEFINITIONS);
764   RECORD(SPECIAL_TYPES);
765   RECORD(STATISTICS);
766   RECORD(TENTATIVE_DEFINITIONS);
767   RECORD(UNUSED_FILESCOPED_DECLS);
768   RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
769   RECORD(SELECTOR_OFFSETS);
770   RECORD(METHOD_POOL);
771   RECORD(PP_COUNTER_VALUE);
772   RECORD(SOURCE_LOCATION_OFFSETS);
773   RECORD(SOURCE_LOCATION_PRELOADS);
774   RECORD(STAT_CACHE);
775   RECORD(EXT_VECTOR_DECLS);
776   RECORD(VERSION_CONTROL_BRANCH_REVISION);
777   RECORD(PPD_ENTITIES_OFFSETS);
778   RECORD(IMPORTS);
779   RECORD(REFERENCED_SELECTOR_POOL);
780   RECORD(TU_UPDATE_LEXICAL);
781   RECORD(REDECLS_UPDATE_LATEST);
782   RECORD(SEMA_DECL_REFS);
783   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
784   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
785   RECORD(DECL_REPLACEMENTS);
786   RECORD(UPDATE_VISIBLE);
787   RECORD(DECL_UPDATE_OFFSETS);
788   RECORD(DECL_UPDATES);
789   RECORD(CXX_BASE_SPECIFIER_OFFSETS);
790   RECORD(DIAG_PRAGMA_MAPPINGS);
791   RECORD(CUDA_SPECIAL_DECL_REFS);
792   RECORD(HEADER_SEARCH_TABLE);
793   RECORD(ORIGINAL_PCH_DIR);
794   RECORD(FP_PRAGMA_OPTIONS);
795   RECORD(OPENCL_EXTENSIONS);
796   RECORD(DELEGATING_CTORS);
797   RECORD(FILE_SOURCE_LOCATION_OFFSETS);
798   RECORD(KNOWN_NAMESPACES);
799   RECORD(MODULE_OFFSET_MAP);
800   RECORD(SOURCE_MANAGER_LINE_TABLE);
801 
802   // SourceManager Block.
803   BLOCK(SOURCE_MANAGER_BLOCK);
804   RECORD(SM_SLOC_FILE_ENTRY);
805   RECORD(SM_SLOC_BUFFER_ENTRY);
806   RECORD(SM_SLOC_BUFFER_BLOB);
807   RECORD(SM_SLOC_EXPANSION_ENTRY);
808 
809   // Preprocessor Block.
810   BLOCK(PREPROCESSOR_BLOCK);
811   RECORD(PP_MACRO_OBJECT_LIKE);
812   RECORD(PP_MACRO_FUNCTION_LIKE);
813   RECORD(PP_TOKEN);
814 
815   // Decls and Types block.
816   BLOCK(DECLTYPES_BLOCK);
817   RECORD(TYPE_EXT_QUAL);
818   RECORD(TYPE_COMPLEX);
819   RECORD(TYPE_POINTER);
820   RECORD(TYPE_BLOCK_POINTER);
821   RECORD(TYPE_LVALUE_REFERENCE);
822   RECORD(TYPE_RVALUE_REFERENCE);
823   RECORD(TYPE_MEMBER_POINTER);
824   RECORD(TYPE_CONSTANT_ARRAY);
825   RECORD(TYPE_INCOMPLETE_ARRAY);
826   RECORD(TYPE_VARIABLE_ARRAY);
827   RECORD(TYPE_VECTOR);
828   RECORD(TYPE_EXT_VECTOR);
829   RECORD(TYPE_FUNCTION_PROTO);
830   RECORD(TYPE_FUNCTION_NO_PROTO);
831   RECORD(TYPE_TYPEDEF);
832   RECORD(TYPE_TYPEOF_EXPR);
833   RECORD(TYPE_TYPEOF);
834   RECORD(TYPE_RECORD);
835   RECORD(TYPE_ENUM);
836   RECORD(TYPE_OBJC_INTERFACE);
837   RECORD(TYPE_OBJC_OBJECT);
838   RECORD(TYPE_OBJC_OBJECT_POINTER);
839   RECORD(TYPE_DECLTYPE);
840   RECORD(TYPE_ELABORATED);
841   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
842   RECORD(TYPE_UNRESOLVED_USING);
843   RECORD(TYPE_INJECTED_CLASS_NAME);
844   RECORD(TYPE_OBJC_OBJECT);
845   RECORD(TYPE_TEMPLATE_TYPE_PARM);
846   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
847   RECORD(TYPE_DEPENDENT_NAME);
848   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
849   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
850   RECORD(TYPE_PAREN);
851   RECORD(TYPE_PACK_EXPANSION);
852   RECORD(TYPE_ATTRIBUTED);
853   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
854   RECORD(TYPE_ATOMIC);
855   RECORD(DECL_TYPEDEF);
856   RECORD(DECL_ENUM);
857   RECORD(DECL_RECORD);
858   RECORD(DECL_ENUM_CONSTANT);
859   RECORD(DECL_FUNCTION);
860   RECORD(DECL_OBJC_METHOD);
861   RECORD(DECL_OBJC_INTERFACE);
862   RECORD(DECL_OBJC_PROTOCOL);
863   RECORD(DECL_OBJC_IVAR);
864   RECORD(DECL_OBJC_AT_DEFS_FIELD);
865   RECORD(DECL_OBJC_CLASS);
866   RECORD(DECL_OBJC_FORWARD_PROTOCOL);
867   RECORD(DECL_OBJC_CATEGORY);
868   RECORD(DECL_OBJC_CATEGORY_IMPL);
869   RECORD(DECL_OBJC_IMPLEMENTATION);
870   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
871   RECORD(DECL_OBJC_PROPERTY);
872   RECORD(DECL_OBJC_PROPERTY_IMPL);
873   RECORD(DECL_FIELD);
874   RECORD(DECL_VAR);
875   RECORD(DECL_IMPLICIT_PARAM);
876   RECORD(DECL_PARM_VAR);
877   RECORD(DECL_FILE_SCOPE_ASM);
878   RECORD(DECL_BLOCK);
879   RECORD(DECL_CONTEXT_LEXICAL);
880   RECORD(DECL_CONTEXT_VISIBLE);
881   RECORD(DECL_NAMESPACE);
882   RECORD(DECL_NAMESPACE_ALIAS);
883   RECORD(DECL_USING);
884   RECORD(DECL_USING_SHADOW);
885   RECORD(DECL_USING_DIRECTIVE);
886   RECORD(DECL_UNRESOLVED_USING_VALUE);
887   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
888   RECORD(DECL_LINKAGE_SPEC);
889   RECORD(DECL_CXX_RECORD);
890   RECORD(DECL_CXX_METHOD);
891   RECORD(DECL_CXX_CONSTRUCTOR);
892   RECORD(DECL_CXX_DESTRUCTOR);
893   RECORD(DECL_CXX_CONVERSION);
894   RECORD(DECL_ACCESS_SPEC);
895   RECORD(DECL_FRIEND);
896   RECORD(DECL_FRIEND_TEMPLATE);
897   RECORD(DECL_CLASS_TEMPLATE);
898   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
899   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
900   RECORD(DECL_FUNCTION_TEMPLATE);
901   RECORD(DECL_TEMPLATE_TYPE_PARM);
902   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
903   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
904   RECORD(DECL_STATIC_ASSERT);
905   RECORD(DECL_CXX_BASE_SPECIFIERS);
906   RECORD(DECL_INDIRECTFIELD);
907   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
908 
909   // Statements and Exprs can occur in the Decls and Types block.
910   AddStmtsExprs(Stream, Record);
911 
912   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
913   RECORD(PPD_MACRO_EXPANSION);
914   RECORD(PPD_MACRO_DEFINITION);
915   RECORD(PPD_INCLUSION_DIRECTIVE);
916 
917 #undef RECORD
918 #undef BLOCK
919   Stream.ExitBlock();
920 }
921 
922 /// \brief Adjusts the given filename to only write out the portion of the
923 /// filename that is not part of the system root directory.
924 ///
925 /// \param Filename the file name to adjust.
926 ///
927 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
928 /// the returned filename will be adjusted by this system root.
929 ///
930 /// \returns either the original filename (if it needs no adjustment) or the
931 /// adjusted filename (which points into the @p Filename parameter).
932 static const char *
933 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
934   assert(Filename && "No file name to adjust?");
935 
936   if (isysroot.empty())
937     return Filename;
938 
939   // Verify that the filename and the system root have the same prefix.
940   unsigned Pos = 0;
941   for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
942     if (Filename[Pos] != isysroot[Pos])
943       return Filename; // Prefixes don't match.
944 
945   // We hit the end of the filename before we hit the end of the system root.
946   if (!Filename[Pos])
947     return Filename;
948 
949   // If the file name has a '/' at the current position, skip over the '/'.
950   // We distinguish sysroot-based includes from absolute includes by the
951   // absence of '/' at the beginning of sysroot-based includes.
952   if (Filename[Pos] == '/')
953     ++Pos;
954 
955   return Filename + Pos;
956 }
957 
958 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
959 void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot,
960                               const std::string &OutputFile) {
961   using namespace llvm;
962 
963   // Metadata
964   const TargetInfo &Target = Context.getTargetInfo();
965   BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
966   MetaAbbrev->Add(BitCodeAbbrevOp(METADATA));
967   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
968   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
969   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
970   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
971   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
972   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
973   unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
974 
975   RecordData Record;
976   Record.push_back(METADATA);
977   Record.push_back(VERSION_MAJOR);
978   Record.push_back(VERSION_MINOR);
979   Record.push_back(CLANG_VERSION_MAJOR);
980   Record.push_back(CLANG_VERSION_MINOR);
981   Record.push_back(!isysroot.empty());
982   const std::string &Triple = Target.getTriple().getTriple();
983   Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple);
984 
985   if (Chain) {
986     serialization::ModuleManager &Mgr = Chain->getModuleManager();
987     llvm::SmallVector<char, 128> ModulePaths;
988     Record.clear();
989 
990     for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
991          M != MEnd; ++M) {
992       // Skip modules that weren't directly imported.
993       if (!(*M)->isDirectlyImported())
994         continue;
995 
996       Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
997       // FIXME: Write import location, once it matters.
998       // FIXME: This writes the absolute path for AST files we depend on.
999       const std::string &FileName = (*M)->FileName;
1000       Record.push_back(FileName.size());
1001       Record.append(FileName.begin(), FileName.end());
1002     }
1003     Stream.EmitRecord(IMPORTS, Record);
1004   }
1005 
1006   // Original file name and file ID
1007   SourceManager &SM = Context.getSourceManager();
1008   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1009     BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1010     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
1011     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1012     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1013 
1014     llvm::SmallString<128> MainFilePath(MainFile->getName());
1015 
1016     llvm::sys::fs::make_absolute(MainFilePath);
1017 
1018     const char *MainFileNameStr = MainFilePath.c_str();
1019     MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1020                                                       isysroot);
1021     RecordData Record;
1022     Record.push_back(ORIGINAL_FILE_NAME);
1023     Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1024 
1025     Record.clear();
1026     Record.push_back(SM.getMainFileID().getOpaqueValue());
1027     Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1028   }
1029 
1030   // Original PCH directory
1031   if (!OutputFile.empty() && OutputFile != "-") {
1032     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1033     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1034     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1035     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1036 
1037     llvm::SmallString<128> OutputPath(OutputFile);
1038 
1039     llvm::sys::fs::make_absolute(OutputPath);
1040     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1041 
1042     RecordData Record;
1043     Record.push_back(ORIGINAL_PCH_DIR);
1044     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1045   }
1046 
1047   // Repository branch/version information.
1048   BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
1049   RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
1050   RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1051   unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
1052   Record.clear();
1053   Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
1054   Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
1055                             getClangFullRepositoryVersion());
1056 }
1057 
1058 /// \brief Write the LangOptions structure.
1059 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1060   RecordData Record;
1061 #define LANGOPT(Name, Bits, Default, Description) \
1062   Record.push_back(LangOpts.Name);
1063 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1064   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1065 #include "clang/Basic/LangOptions.def"
1066 
1067   Record.push_back(LangOpts.CurrentModule.size());
1068   Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1069   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1070 }
1071 
1072 //===----------------------------------------------------------------------===//
1073 // stat cache Serialization
1074 //===----------------------------------------------------------------------===//
1075 
1076 namespace {
1077 // Trait used for the on-disk hash table of stat cache results.
1078 class ASTStatCacheTrait {
1079 public:
1080   typedef const char * key_type;
1081   typedef key_type key_type_ref;
1082 
1083   typedef struct stat data_type;
1084   typedef const data_type &data_type_ref;
1085 
1086   static unsigned ComputeHash(const char *path) {
1087     return llvm::HashString(path);
1088   }
1089 
1090   std::pair<unsigned,unsigned>
1091     EmitKeyDataLength(raw_ostream& Out, const char *path,
1092                       data_type_ref Data) {
1093     unsigned StrLen = strlen(path);
1094     clang::io::Emit16(Out, StrLen);
1095     unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1096     clang::io::Emit8(Out, DataLen);
1097     return std::make_pair(StrLen + 1, DataLen);
1098   }
1099 
1100   void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1101     Out.write(path, KeyLen);
1102   }
1103 
1104   void EmitData(raw_ostream &Out, key_type_ref,
1105                 data_type_ref Data, unsigned DataLen) {
1106     using namespace clang::io;
1107     uint64_t Start = Out.tell(); (void)Start;
1108 
1109     Emit32(Out, (uint32_t) Data.st_ino);
1110     Emit32(Out, (uint32_t) Data.st_dev);
1111     Emit16(Out, (uint16_t) Data.st_mode);
1112     Emit64(Out, (uint64_t) Data.st_mtime);
1113     Emit64(Out, (uint64_t) Data.st_size);
1114 
1115     assert(Out.tell() - Start == DataLen && "Wrong data length");
1116   }
1117 };
1118 } // end anonymous namespace
1119 
1120 /// \brief Write the stat() system call cache to the AST file.
1121 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1122   // Build the on-disk hash table containing information about every
1123   // stat() call.
1124   OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1125   unsigned NumStatEntries = 0;
1126   for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1127                                 StatEnd = StatCalls.end();
1128        Stat != StatEnd; ++Stat, ++NumStatEntries) {
1129     StringRef Filename = Stat->first();
1130     Generator.insert(Filename.data(), Stat->second);
1131   }
1132 
1133   // Create the on-disk hash table in a buffer.
1134   llvm::SmallString<4096> StatCacheData;
1135   uint32_t BucketOffset;
1136   {
1137     llvm::raw_svector_ostream Out(StatCacheData);
1138     // Make sure that no bucket is at offset 0
1139     clang::io::Emit32(Out, 0);
1140     BucketOffset = Generator.Emit(Out);
1141   }
1142 
1143   // Create a blob abbreviation
1144   using namespace llvm;
1145   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1146   Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1147   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1148   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1149   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1150   unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1151 
1152   // Write the stat cache
1153   RecordData Record;
1154   Record.push_back(STAT_CACHE);
1155   Record.push_back(BucketOffset);
1156   Record.push_back(NumStatEntries);
1157   Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1158 }
1159 
1160 //===----------------------------------------------------------------------===//
1161 // Source Manager Serialization
1162 //===----------------------------------------------------------------------===//
1163 
1164 /// \brief Create an abbreviation for the SLocEntry that refers to a
1165 /// file.
1166 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1167   using namespace llvm;
1168   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1169   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1170   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1171   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1172   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1173   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1174   // FileEntry fields.
1175   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1176   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1177   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden
1178   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1179   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1180   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1181   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1182   return Stream.EmitAbbrev(Abbrev);
1183 }
1184 
1185 /// \brief Create an abbreviation for the SLocEntry that refers to a
1186 /// buffer.
1187 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1188   using namespace llvm;
1189   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1190   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1191   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1192   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1193   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1194   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1195   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1196   return Stream.EmitAbbrev(Abbrev);
1197 }
1198 
1199 /// \brief Create an abbreviation for the SLocEntry that refers to a
1200 /// buffer's blob.
1201 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1202   using namespace llvm;
1203   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1204   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1205   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1206   return Stream.EmitAbbrev(Abbrev);
1207 }
1208 
1209 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1210 /// expansion.
1211 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1212   using namespace llvm;
1213   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1214   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1215   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1216   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1217   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1218   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1219   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1220   return Stream.EmitAbbrev(Abbrev);
1221 }
1222 
1223 namespace {
1224   // Trait used for the on-disk hash table of header search information.
1225   class HeaderFileInfoTrait {
1226     ASTWriter &Writer;
1227     const HeaderSearch &HS;
1228 
1229     // Keep track of the framework names we've used during serialization.
1230     SmallVector<char, 128> FrameworkStringData;
1231     llvm::StringMap<unsigned> FrameworkNameOffset;
1232 
1233   public:
1234     HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1235       : Writer(Writer), HS(HS) { }
1236 
1237     typedef const char *key_type;
1238     typedef key_type key_type_ref;
1239 
1240     typedef HeaderFileInfo data_type;
1241     typedef const data_type &data_type_ref;
1242 
1243     static unsigned ComputeHash(const char *path) {
1244       // The hash is based only on the filename portion of the key, so that the
1245       // reader can match based on filenames when symlinking or excess path
1246       // elements ("foo/../", "../") change the form of the name. However,
1247       // complete path is still the key.
1248       return llvm::HashString(llvm::sys::path::filename(path));
1249     }
1250 
1251     std::pair<unsigned,unsigned>
1252     EmitKeyDataLength(raw_ostream& Out, const char *path,
1253                       data_type_ref Data) {
1254       unsigned StrLen = strlen(path);
1255       clang::io::Emit16(Out, StrLen);
1256       unsigned DataLen = 1 + 2 + 4 + 4;
1257       clang::io::Emit8(Out, DataLen);
1258       return std::make_pair(StrLen + 1, DataLen);
1259     }
1260 
1261     void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
1262       Out.write(path, KeyLen);
1263     }
1264 
1265     void EmitData(raw_ostream &Out, key_type_ref,
1266                   data_type_ref Data, unsigned DataLen) {
1267       using namespace clang::io;
1268       uint64_t Start = Out.tell(); (void)Start;
1269 
1270       unsigned char Flags = (Data.isImport << 5)
1271                           | (Data.isPragmaOnce << 4)
1272                           | (Data.DirInfo << 2)
1273                           | (Data.Resolved << 1)
1274                           | Data.IndexHeaderMapHeader;
1275       Emit8(Out, (uint8_t)Flags);
1276       Emit16(Out, (uint16_t) Data.NumIncludes);
1277 
1278       if (!Data.ControllingMacro)
1279         Emit32(Out, (uint32_t)Data.ControllingMacroID);
1280       else
1281         Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1282 
1283       unsigned Offset = 0;
1284       if (!Data.Framework.empty()) {
1285         // If this header refers into a framework, save the framework name.
1286         llvm::StringMap<unsigned>::iterator Pos
1287           = FrameworkNameOffset.find(Data.Framework);
1288         if (Pos == FrameworkNameOffset.end()) {
1289           Offset = FrameworkStringData.size() + 1;
1290           FrameworkStringData.append(Data.Framework.begin(),
1291                                      Data.Framework.end());
1292           FrameworkStringData.push_back(0);
1293 
1294           FrameworkNameOffset[Data.Framework] = Offset;
1295         } else
1296           Offset = Pos->second;
1297       }
1298       Emit32(Out, Offset);
1299 
1300       assert(Out.tell() - Start == DataLen && "Wrong data length");
1301     }
1302 
1303     const char *strings_begin() const { return FrameworkStringData.begin(); }
1304     const char *strings_end() const { return FrameworkStringData.end(); }
1305   };
1306 } // end anonymous namespace
1307 
1308 /// \brief Write the header search block for the list of files that
1309 ///
1310 /// \param HS The header search structure to save.
1311 ///
1312 /// \param Chain Whether we're creating a chained AST file.
1313 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1314   SmallVector<const FileEntry *, 16> FilesByUID;
1315   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1316 
1317   if (FilesByUID.size() > HS.header_file_size())
1318     FilesByUID.resize(HS.header_file_size());
1319 
1320   HeaderFileInfoTrait GeneratorTrait(*this, HS);
1321   OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1322   SmallVector<const char *, 4> SavedStrings;
1323   unsigned NumHeaderSearchEntries = 0;
1324   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1325     const FileEntry *File = FilesByUID[UID];
1326     if (!File)
1327       continue;
1328 
1329     // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1330     // from the external source if it was not provided already.
1331     const HeaderFileInfo &HFI = HS.getFileInfo(File);
1332     if (HFI.External && Chain)
1333       continue;
1334 
1335     // Turn the file name into an absolute path, if it isn't already.
1336     const char *Filename = File->getName();
1337     Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1338 
1339     // If we performed any translation on the file name at all, we need to
1340     // save this string, since the generator will refer to it later.
1341     if (Filename != File->getName()) {
1342       Filename = strdup(Filename);
1343       SavedStrings.push_back(Filename);
1344     }
1345 
1346     Generator.insert(Filename, HFI, GeneratorTrait);
1347     ++NumHeaderSearchEntries;
1348   }
1349 
1350   // Create the on-disk hash table in a buffer.
1351   llvm::SmallString<4096> TableData;
1352   uint32_t BucketOffset;
1353   {
1354     llvm::raw_svector_ostream Out(TableData);
1355     // Make sure that no bucket is at offset 0
1356     clang::io::Emit32(Out, 0);
1357     BucketOffset = Generator.Emit(Out, GeneratorTrait);
1358   }
1359 
1360   // Create a blob abbreviation
1361   using namespace llvm;
1362   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1363   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1364   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1365   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1366   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1367   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1368   unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1369 
1370   // Write the header search table
1371   RecordData Record;
1372   Record.push_back(HEADER_SEARCH_TABLE);
1373   Record.push_back(BucketOffset);
1374   Record.push_back(NumHeaderSearchEntries);
1375   Record.push_back(TableData.size());
1376   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1377   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1378 
1379   // Free all of the strings we had to duplicate.
1380   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1381     free((void*)SavedStrings[I]);
1382 }
1383 
1384 /// \brief Writes the block containing the serialized form of the
1385 /// source manager.
1386 ///
1387 /// TODO: We should probably use an on-disk hash table (stored in a
1388 /// blob), indexed based on the file name, so that we only create
1389 /// entries for files that we actually need. In the common case (no
1390 /// errors), we probably won't have to create file entries for any of
1391 /// the files in the AST.
1392 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1393                                         const Preprocessor &PP,
1394                                         StringRef isysroot) {
1395   RecordData Record;
1396 
1397   // Enter the source manager block.
1398   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1399 
1400   // Abbreviations for the various kinds of source-location entries.
1401   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1402   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1403   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1404   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1405 
1406   // Write out the source location entry table. We skip the first
1407   // entry, which is always the same dummy entry.
1408   std::vector<uint32_t> SLocEntryOffsets;
1409   // Write out the offsets of only source location file entries.
1410   // We will go through them in ASTReader::validateFileEntries().
1411   std::vector<uint32_t> SLocFileEntryOffsets;
1412   RecordData PreloadSLocs;
1413   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1414   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1415        I != N; ++I) {
1416     // Get this source location entry.
1417     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1418 
1419     // Record the offset of this source-location entry.
1420     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1421 
1422     // Figure out which record code to use.
1423     unsigned Code;
1424     if (SLoc->isFile()) {
1425       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1426       if (Cache->OrigEntry) {
1427         Code = SM_SLOC_FILE_ENTRY;
1428         SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
1429       } else
1430         Code = SM_SLOC_BUFFER_ENTRY;
1431     } else
1432       Code = SM_SLOC_EXPANSION_ENTRY;
1433     Record.clear();
1434     Record.push_back(Code);
1435 
1436     // Starting offset of this entry within this module, so skip the dummy.
1437     Record.push_back(SLoc->getOffset() - 2);
1438     if (SLoc->isFile()) {
1439       const SrcMgr::FileInfo &File = SLoc->getFile();
1440       Record.push_back(File.getIncludeLoc().getRawEncoding());
1441       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1442       Record.push_back(File.hasLineDirectives());
1443 
1444       const SrcMgr::ContentCache *Content = File.getContentCache();
1445       if (Content->OrigEntry) {
1446         assert(Content->OrigEntry == Content->ContentsEntry &&
1447                "Writing to AST an overridden file is not supported");
1448 
1449         // The source location entry is a file. The blob associated
1450         // with this entry is the file name.
1451 
1452         // Emit size/modification time for this file.
1453         Record.push_back(Content->OrigEntry->getSize());
1454         Record.push_back(Content->OrigEntry->getModificationTime());
1455         Record.push_back(Content->BufferOverridden);
1456         Record.push_back(File.NumCreatedFIDs);
1457 
1458         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc);
1459         if (FDI != FileDeclIDs.end()) {
1460           Record.push_back(FDI->second->FirstDeclIndex);
1461           Record.push_back(FDI->second->DeclIDs.size());
1462         } else {
1463           Record.push_back(0);
1464           Record.push_back(0);
1465         }
1466 
1467         // Turn the file name into an absolute path, if it isn't already.
1468         const char *Filename = Content->OrigEntry->getName();
1469         llvm::SmallString<128> FilePath(Filename);
1470 
1471         // Ask the file manager to fixup the relative path for us. This will
1472         // honor the working directory.
1473         SourceMgr.getFileManager().FixupRelativePath(FilePath);
1474 
1475         // FIXME: This call to make_absolute shouldn't be necessary, the
1476         // call to FixupRelativePath should always return an absolute path.
1477         llvm::sys::fs::make_absolute(FilePath);
1478         Filename = FilePath.c_str();
1479 
1480         Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1481         Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1482 
1483         if (Content->BufferOverridden) {
1484           Record.clear();
1485           Record.push_back(SM_SLOC_BUFFER_BLOB);
1486           const llvm::MemoryBuffer *Buffer
1487             = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1488           Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1489                                     StringRef(Buffer->getBufferStart(),
1490                                               Buffer->getBufferSize() + 1));
1491         }
1492       } else {
1493         // The source location entry is a buffer. The blob associated
1494         // with this entry contains the contents of the buffer.
1495 
1496         // We add one to the size so that we capture the trailing NULL
1497         // that is required by llvm::MemoryBuffer::getMemBuffer (on
1498         // the reader side).
1499         const llvm::MemoryBuffer *Buffer
1500           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1501         const char *Name = Buffer->getBufferIdentifier();
1502         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1503                                   StringRef(Name, strlen(Name) + 1));
1504         Record.clear();
1505         Record.push_back(SM_SLOC_BUFFER_BLOB);
1506         Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1507                                   StringRef(Buffer->getBufferStart(),
1508                                                   Buffer->getBufferSize() + 1));
1509 
1510         if (strcmp(Name, "<built-in>") == 0) {
1511           PreloadSLocs.push_back(SLocEntryOffsets.size());
1512         }
1513       }
1514     } else {
1515       // The source location entry is a macro expansion.
1516       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1517       Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1518       Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1519       Record.push_back(Expansion.isMacroArgExpansion() ? 0
1520                              : Expansion.getExpansionLocEnd().getRawEncoding());
1521 
1522       // Compute the token length for this macro expansion.
1523       unsigned NextOffset = SourceMgr.getNextLocalOffset();
1524       if (I + 1 != N)
1525         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1526       Record.push_back(NextOffset - SLoc->getOffset() - 1);
1527       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1528     }
1529   }
1530 
1531   Stream.ExitBlock();
1532 
1533   if (SLocEntryOffsets.empty())
1534     return;
1535 
1536   // Write the source-location offsets table into the AST block. This
1537   // table is used for lazily loading source-location information.
1538   using namespace llvm;
1539   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1540   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1541   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1542   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1543   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1544   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1545 
1546   Record.clear();
1547   Record.push_back(SOURCE_LOCATION_OFFSETS);
1548   Record.push_back(SLocEntryOffsets.size());
1549   Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1550   Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1551 
1552   Abbrev = new BitCodeAbbrev();
1553   Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
1554   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1555   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1556   unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1557 
1558   Record.clear();
1559   Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
1560   Record.push_back(SLocFileEntryOffsets.size());
1561   Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
1562                             data(SLocFileEntryOffsets));
1563 
1564   // Write the source location entry preloads array, telling the AST
1565   // reader which source locations entries it should load eagerly.
1566   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1567 
1568   // Write the line table. It depends on remapping working, so it must come
1569   // after the source location offsets.
1570   if (SourceMgr.hasLineTable()) {
1571     LineTableInfo &LineTable = SourceMgr.getLineTable();
1572 
1573     Record.clear();
1574     // Emit the file names
1575     Record.push_back(LineTable.getNumFilenames());
1576     for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1577       // Emit the file name
1578       const char *Filename = LineTable.getFilename(I);
1579       Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1580       unsigned FilenameLen = Filename? strlen(Filename) : 0;
1581       Record.push_back(FilenameLen);
1582       if (FilenameLen)
1583         Record.insert(Record.end(), Filename, Filename + FilenameLen);
1584     }
1585 
1586     // Emit the line entries
1587     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1588          L != LEnd; ++L) {
1589       // Only emit entries for local files.
1590       if (L->first < 0)
1591         continue;
1592 
1593       // Emit the file ID
1594       Record.push_back(L->first);
1595 
1596       // Emit the line entries
1597       Record.push_back(L->second.size());
1598       for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1599                                          LEEnd = L->second.end();
1600            LE != LEEnd; ++LE) {
1601         Record.push_back(LE->FileOffset);
1602         Record.push_back(LE->LineNo);
1603         Record.push_back(LE->FilenameID);
1604         Record.push_back((unsigned)LE->FileKind);
1605         Record.push_back(LE->IncludeOffset);
1606       }
1607     }
1608     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1609   }
1610 }
1611 
1612 //===----------------------------------------------------------------------===//
1613 // Preprocessor Serialization
1614 //===----------------------------------------------------------------------===//
1615 
1616 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1617   const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1618     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1619   const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1620     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1621   return X.first->getName().compare(Y.first->getName());
1622 }
1623 
1624 /// \brief Writes the block containing the serialized form of the
1625 /// preprocessor.
1626 ///
1627 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1628   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1629   if (PPRec)
1630     WritePreprocessorDetail(*PPRec);
1631 
1632   RecordData Record;
1633 
1634   // If the preprocessor __COUNTER__ value has been bumped, remember it.
1635   if (PP.getCounterValue() != 0) {
1636     Record.push_back(PP.getCounterValue());
1637     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1638     Record.clear();
1639   }
1640 
1641   // Enter the preprocessor block.
1642   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1643 
1644   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1645   // FIXME: use diagnostics subsystem for localization etc.
1646   if (PP.SawDateOrTime())
1647     fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1648 
1649 
1650   // Loop over all the macro definitions that are live at the end of the file,
1651   // emitting each to the PP section.
1652 
1653   // Construct the list of macro definitions that need to be serialized.
1654   SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1655     MacrosToEmit;
1656   llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1657   for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1658                                     E = PP.macro_end(Chain == 0);
1659        I != E; ++I) {
1660     if (!IsModule || I->second->isPublic()) {
1661       MacroDefinitionsSeen.insert(I->first);
1662       MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1663     }
1664   }
1665 
1666   // Sort the set of macro definitions that need to be serialized by the
1667   // name of the macro, to provide a stable ordering.
1668   llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1669                        &compareMacroDefinitions);
1670 
1671   // Resolve any identifiers that defined macros at the time they were
1672   // deserialized, adding them to the list of macros to emit (if appropriate).
1673   for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1674     IdentifierInfo *Name
1675       = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1676     if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1677       MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1678   }
1679 
1680   for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1681     const IdentifierInfo *Name = MacrosToEmit[I].first;
1682     MacroInfo *MI = MacrosToEmit[I].second;
1683     if (!MI)
1684       continue;
1685 
1686     // Don't emit builtin macros like __LINE__ to the AST file unless they have
1687     // been redefined by the header (in which case they are not isBuiltinMacro).
1688     // Also skip macros from a AST file if we're chaining.
1689 
1690     // FIXME: There is a (probably minor) optimization we could do here, if
1691     // the macro comes from the original PCH but the identifier comes from a
1692     // chained PCH, by storing the offset into the original PCH rather than
1693     // writing the macro definition a second time.
1694     if (MI->isBuiltinMacro() ||
1695         (Chain &&
1696          Name->isFromAST() && !Name->hasChangedSinceDeserialization() &&
1697          MI->isFromAST() && !MI->hasChangedAfterLoad()))
1698       continue;
1699 
1700     AddIdentifierRef(Name, Record);
1701     MacroOffsets[Name] = Stream.GetCurrentBitNo();
1702     Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1703     Record.push_back(MI->isUsed());
1704     Record.push_back(MI->isPublic());
1705     AddSourceLocation(MI->getVisibilityLocation(), Record);
1706     unsigned Code;
1707     if (MI->isObjectLike()) {
1708       Code = PP_MACRO_OBJECT_LIKE;
1709     } else {
1710       Code = PP_MACRO_FUNCTION_LIKE;
1711 
1712       Record.push_back(MI->isC99Varargs());
1713       Record.push_back(MI->isGNUVarargs());
1714       Record.push_back(MI->getNumArgs());
1715       for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1716            I != E; ++I)
1717         AddIdentifierRef(*I, Record);
1718     }
1719 
1720     // If we have a detailed preprocessing record, record the macro definition
1721     // ID that corresponds to this macro.
1722     if (PPRec)
1723       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
1724 
1725     Stream.EmitRecord(Code, Record);
1726     Record.clear();
1727 
1728     // Emit the tokens array.
1729     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1730       // Note that we know that the preprocessor does not have any annotation
1731       // tokens in it because they are created by the parser, and thus can't be
1732       // in a macro definition.
1733       const Token &Tok = MI->getReplacementToken(TokNo);
1734 
1735       Record.push_back(Tok.getLocation().getRawEncoding());
1736       Record.push_back(Tok.getLength());
1737 
1738       // FIXME: When reading literal tokens, reconstruct the literal pointer if
1739       // it is needed.
1740       AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1741       // FIXME: Should translate token kind to a stable encoding.
1742       Record.push_back(Tok.getKind());
1743       // FIXME: Should translate token flags to a stable encoding.
1744       Record.push_back(Tok.getFlags());
1745 
1746       Stream.EmitRecord(PP_TOKEN, Record);
1747       Record.clear();
1748     }
1749     ++NumMacros;
1750   }
1751   Stream.ExitBlock();
1752 }
1753 
1754 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1755   if (PPRec.local_begin() == PPRec.local_end())
1756     return;
1757 
1758   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
1759 
1760   // Enter the preprocessor block.
1761   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1762 
1763   // If the preprocessor has a preprocessing record, emit it.
1764   unsigned NumPreprocessingRecords = 0;
1765   using namespace llvm;
1766 
1767   // Set up the abbreviation for
1768   unsigned InclusionAbbrev = 0;
1769   {
1770     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1771     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1772     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1773     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1774     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1775     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1776     InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1777   }
1778 
1779   unsigned FirstPreprocessorEntityID
1780     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
1781     + NUM_PREDEF_PP_ENTITY_IDS;
1782   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
1783   RecordData Record;
1784   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
1785                                   EEnd = PPRec.local_end();
1786        E != EEnd;
1787        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
1788     Record.clear();
1789 
1790     PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
1791                                                      Stream.GetCurrentBitNo()));
1792 
1793     if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1794       // Record this macro definition's ID.
1795       MacroDefinitions[MD] = NextPreprocessorEntityID;
1796 
1797       AddIdentifierRef(MD->getName(), Record);
1798       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1799       continue;
1800     }
1801 
1802     if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
1803       Record.push_back(ME->isBuiltinMacro());
1804       if (ME->isBuiltinMacro())
1805         AddIdentifierRef(ME->getName(), Record);
1806       else
1807         Record.push_back(MacroDefinitions[ME->getDefinition()]);
1808       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
1809       continue;
1810     }
1811 
1812     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1813       Record.push_back(PPD_INCLUSION_DIRECTIVE);
1814       Record.push_back(ID->getFileName().size());
1815       Record.push_back(ID->wasInQuotes());
1816       Record.push_back(static_cast<unsigned>(ID->getKind()));
1817       llvm::SmallString<64> Buffer;
1818       Buffer += ID->getFileName();
1819       Buffer += ID->getFile()->getName();
1820       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1821       continue;
1822     }
1823 
1824     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1825   }
1826   Stream.ExitBlock();
1827 
1828   // Write the offsets table for the preprocessing record.
1829   if (NumPreprocessingRecords > 0) {
1830     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
1831 
1832     // Write the offsets table for identifier IDs.
1833     using namespace llvm;
1834     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1835     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
1836     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
1837     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1838     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1839 
1840     Record.clear();
1841     Record.push_back(PPD_ENTITIES_OFFSETS);
1842     Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
1843     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
1844                               data(PreprocessedEntityOffsets));
1845   }
1846 }
1847 
1848 /// \brief Compute the number of modules within the given tree (including the
1849 /// given module).
1850 static unsigned getNumberOfModules(Module *Mod) {
1851   unsigned ChildModules = 0;
1852   for (llvm::StringMap<Module *>::iterator Sub = Mod->SubModules.begin(),
1853                                         SubEnd = Mod->SubModules.end();
1854        Sub != SubEnd; ++Sub)
1855     ChildModules += getNumberOfModules(Sub->getValue());
1856 
1857   return ChildModules + 1;
1858 }
1859 
1860 void ASTWriter::WriteSubmodules(Module *WritingModule) {
1861   // Determine the dependencies of our module and each of it's submodules.
1862   // FIXME: This feels like it belongs somewhere else, but there are no
1863   // other consumers of this information.
1864   SourceManager &SrcMgr = PP->getSourceManager();
1865   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
1866   for (ASTContext::import_iterator I = Context->local_import_begin(),
1867                                 IEnd = Context->local_import_end();
1868        I != IEnd; ++I) {
1869     assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
1870     if (Module *ImportedFrom
1871           = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
1872                                                          SrcMgr))) {
1873       ImportedFrom->Imports.push_back(I->getImportedModule());
1874     }
1875   }
1876 
1877   // Enter the submodule description block.
1878   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
1879 
1880   // Write the abbreviations needed for the submodules block.
1881   using namespace llvm;
1882   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1883   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
1884   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
1885   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
1886   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
1887   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
1888   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
1889   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
1890   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1891   unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
1892 
1893   Abbrev = new BitCodeAbbrev();
1894   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA));
1895   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1896   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
1897 
1898   Abbrev = new BitCodeAbbrev();
1899   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
1900   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1901   unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
1902 
1903   // Write the submodule metadata block.
1904   RecordData Record;
1905   Record.push_back(getNumberOfModules(WritingModule));
1906   Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
1907   Stream.EmitRecord(SUBMODULE_METADATA, Record);
1908 
1909   // Write all of the submodules.
1910   std::queue<Module *> Q;
1911   Q.push(WritingModule);
1912   while (!Q.empty()) {
1913     Module *Mod = Q.front();
1914     Q.pop();
1915     assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
1916     SubmoduleIDs[Mod] = NextSubmoduleID++;
1917 
1918     // Emit the definition of the block.
1919     Record.clear();
1920     Record.push_back(SUBMODULE_DEFINITION);
1921     if (Mod->Parent) {
1922       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
1923       Record.push_back(SubmoduleIDs[Mod->Parent]);
1924     } else {
1925       Record.push_back(0);
1926     }
1927     Record.push_back(Mod->IsFramework);
1928     Record.push_back(Mod->IsExplicit);
1929     Record.push_back(Mod->InferSubmodules);
1930     Record.push_back(Mod->InferExplicitSubmodules);
1931     Record.push_back(Mod->InferExportWildcard);
1932     Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
1933 
1934     // Emit the umbrella header, if there is one.
1935     if (Mod->UmbrellaHeader) {
1936       Record.clear();
1937       Record.push_back(SUBMODULE_UMBRELLA);
1938       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
1939                                 Mod->UmbrellaHeader->getName());
1940     }
1941 
1942     // Emit the headers.
1943     for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
1944       Record.clear();
1945       Record.push_back(SUBMODULE_HEADER);
1946       Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
1947                                 Mod->Headers[I]->getName());
1948     }
1949 
1950     // Emit the imports.
1951     if (!Mod->Imports.empty()) {
1952       Record.clear();
1953       for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
1954         unsigned ImportedID = SubmoduleIDs[Mod->Imports[I]];
1955         assert(ImportedID && "Unknown submodule!");
1956         Record.push_back(ImportedID);
1957       }
1958       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
1959     }
1960 
1961     // Emit the exports.
1962     if (!Mod->Exports.empty()) {
1963       Record.clear();
1964       for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
1965         unsigned ExportedID = SubmoduleIDs[Mod->Exports[I].getPointer()];
1966         assert((ExportedID || !Mod->Exports[I].getPointer()) &&
1967                "Unknown submodule!");
1968         Record.push_back(ExportedID);
1969         Record.push_back(Mod->Exports[I].getInt());
1970       }
1971       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
1972     }
1973 
1974     // Queue up the submodules of this module.
1975     llvm::SmallVector<StringRef, 2> SubModules;
1976 
1977     // Sort the submodules first, so we get a predictable ordering in the AST
1978     // file.
1979     for (llvm::StringMap<Module *>::iterator
1980               Sub = Mod->SubModules.begin(),
1981            SubEnd = Mod->SubModules.end();
1982          Sub != SubEnd; ++Sub)
1983       SubModules.push_back(Sub->getKey());
1984     llvm::array_pod_sort(SubModules.begin(), SubModules.end());
1985 
1986     for (unsigned I = 0, N = SubModules.size(); I != N; ++I)
1987       Q.push(Mod->SubModules[SubModules[I]]);
1988   }
1989 
1990   Stream.ExitBlock();
1991 }
1992 
1993 serialization::SubmoduleID
1994 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
1995   if (Loc.isInvalid() || SubmoduleIDs.empty())
1996     return 0; // No submodule
1997 
1998   // Find the module that owns this location.
1999   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2000   Module *OwningMod
2001     = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2002   if (!OwningMod)
2003     return 0;
2004 
2005   // Check whether we known about this submodule.
2006   llvm::DenseMap<Module *, unsigned>::iterator Known
2007     = SubmoduleIDs.find(OwningMod);
2008   if (Known == SubmoduleIDs.end())
2009     return 0;
2010 
2011   return Known->second;
2012 }
2013 
2014 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) {
2015   RecordData Record;
2016   for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2017          I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2018          I != E; ++I) {
2019     const DiagnosticsEngine::DiagStatePoint &point = *I;
2020     if (point.Loc.isInvalid())
2021       continue;
2022 
2023     Record.push_back(point.Loc.getRawEncoding());
2024     for (DiagnosticsEngine::DiagState::const_iterator
2025            I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2026       if (I->second.isPragma()) {
2027         Record.push_back(I->first);
2028         Record.push_back(I->second.getMapping());
2029       }
2030     }
2031     Record.push_back(-1); // mark the end of the diag/map pairs for this
2032                           // location.
2033   }
2034 
2035   if (!Record.empty())
2036     Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2037 }
2038 
2039 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2040   if (CXXBaseSpecifiersOffsets.empty())
2041     return;
2042 
2043   RecordData Record;
2044 
2045   // Create a blob abbreviation for the C++ base specifiers offsets.
2046   using namespace llvm;
2047 
2048   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2049   Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2050   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2051   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2052   unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2053 
2054   // Write the base specifier offsets table.
2055   Record.clear();
2056   Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2057   Record.push_back(CXXBaseSpecifiersOffsets.size());
2058   Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2059                             data(CXXBaseSpecifiersOffsets));
2060 }
2061 
2062 //===----------------------------------------------------------------------===//
2063 // Type Serialization
2064 //===----------------------------------------------------------------------===//
2065 
2066 /// \brief Write the representation of a type to the AST stream.
2067 void ASTWriter::WriteType(QualType T) {
2068   TypeIdx &Idx = TypeIdxs[T];
2069   if (Idx.getIndex() == 0) // we haven't seen this type before.
2070     Idx = TypeIdx(NextTypeID++);
2071 
2072   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2073 
2074   // Record the offset for this type.
2075   unsigned Index = Idx.getIndex() - FirstTypeID;
2076   if (TypeOffsets.size() == Index)
2077     TypeOffsets.push_back(Stream.GetCurrentBitNo());
2078   else if (TypeOffsets.size() < Index) {
2079     TypeOffsets.resize(Index + 1);
2080     TypeOffsets[Index] = Stream.GetCurrentBitNo();
2081   }
2082 
2083   RecordData Record;
2084 
2085   // Emit the type's representation.
2086   ASTTypeWriter W(*this, Record);
2087 
2088   if (T.hasLocalNonFastQualifiers()) {
2089     Qualifiers Qs = T.getLocalQualifiers();
2090     AddTypeRef(T.getLocalUnqualifiedType(), Record);
2091     Record.push_back(Qs.getAsOpaqueValue());
2092     W.Code = TYPE_EXT_QUAL;
2093   } else {
2094     switch (T->getTypeClass()) {
2095       // For all of the concrete, non-dependent types, call the
2096       // appropriate visitor function.
2097 #define TYPE(Class, Base) \
2098     case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2099 #define ABSTRACT_TYPE(Class, Base)
2100 #include "clang/AST/TypeNodes.def"
2101     }
2102   }
2103 
2104   // Emit the serialized record.
2105   Stream.EmitRecord(W.Code, Record);
2106 
2107   // Flush any expressions that were written as part of this type.
2108   FlushStmts();
2109 }
2110 
2111 //===----------------------------------------------------------------------===//
2112 // Declaration Serialization
2113 //===----------------------------------------------------------------------===//
2114 
2115 /// \brief Write the block containing all of the declaration IDs
2116 /// lexically declared within the given DeclContext.
2117 ///
2118 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2119 /// bistream, or 0 if no block was written.
2120 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2121                                                  DeclContext *DC) {
2122   if (DC->decls_empty())
2123     return 0;
2124 
2125   uint64_t Offset = Stream.GetCurrentBitNo();
2126   RecordData Record;
2127   Record.push_back(DECL_CONTEXT_LEXICAL);
2128   SmallVector<KindDeclIDPair, 64> Decls;
2129   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2130          D != DEnd; ++D)
2131     Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
2132 
2133   ++NumLexicalDeclContexts;
2134   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2135   return Offset;
2136 }
2137 
2138 void ASTWriter::WriteTypeDeclOffsets() {
2139   using namespace llvm;
2140   RecordData Record;
2141 
2142   // Write the type offsets array
2143   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2144   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2145   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2146   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2147   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2148   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2149   Record.clear();
2150   Record.push_back(TYPE_OFFSET);
2151   Record.push_back(TypeOffsets.size());
2152   Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2153   Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2154 
2155   // Write the declaration offsets array
2156   Abbrev = new BitCodeAbbrev();
2157   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2158   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2159   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2160   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2161   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2162   Record.clear();
2163   Record.push_back(DECL_OFFSET);
2164   Record.push_back(DeclOffsets.size());
2165   Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2166   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2167 }
2168 
2169 void ASTWriter::WriteFileDeclIDsMap() {
2170   using namespace llvm;
2171   RecordData Record;
2172 
2173   // Join the vectors of DeclIDs from all files.
2174   SmallVector<DeclID, 256> FileSortedIDs;
2175   for (FileDeclIDsTy::iterator
2176          FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2177     DeclIDInFileInfo &Info = *FI->second;
2178     Info.FirstDeclIndex = FileSortedIDs.size();
2179     for (LocDeclIDsTy::iterator
2180            DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2181       FileSortedIDs.push_back(DI->second);
2182   }
2183 
2184   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2185   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2186   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2187   unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2188   Record.push_back(FILE_SORTED_DECLS);
2189   Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2190 }
2191 
2192 //===----------------------------------------------------------------------===//
2193 // Global Method Pool and Selector Serialization
2194 //===----------------------------------------------------------------------===//
2195 
2196 namespace {
2197 // Trait used for the on-disk hash table used in the method pool.
2198 class ASTMethodPoolTrait {
2199   ASTWriter &Writer;
2200 
2201 public:
2202   typedef Selector key_type;
2203   typedef key_type key_type_ref;
2204 
2205   struct data_type {
2206     SelectorID ID;
2207     ObjCMethodList Instance, Factory;
2208   };
2209   typedef const data_type& data_type_ref;
2210 
2211   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2212 
2213   static unsigned ComputeHash(Selector Sel) {
2214     return serialization::ComputeHash(Sel);
2215   }
2216 
2217   std::pair<unsigned,unsigned>
2218     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2219                       data_type_ref Methods) {
2220     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2221     clang::io::Emit16(Out, KeyLen);
2222     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2223     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2224          Method = Method->Next)
2225       if (Method->Method)
2226         DataLen += 4;
2227     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2228          Method = Method->Next)
2229       if (Method->Method)
2230         DataLen += 4;
2231     clang::io::Emit16(Out, DataLen);
2232     return std::make_pair(KeyLen, DataLen);
2233   }
2234 
2235   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2236     uint64_t Start = Out.tell();
2237     assert((Start >> 32) == 0 && "Selector key offset too large");
2238     Writer.SetSelectorOffset(Sel, Start);
2239     unsigned N = Sel.getNumArgs();
2240     clang::io::Emit16(Out, N);
2241     if (N == 0)
2242       N = 1;
2243     for (unsigned I = 0; I != N; ++I)
2244       clang::io::Emit32(Out,
2245                     Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2246   }
2247 
2248   void EmitData(raw_ostream& Out, key_type_ref,
2249                 data_type_ref Methods, unsigned DataLen) {
2250     uint64_t Start = Out.tell(); (void)Start;
2251     clang::io::Emit32(Out, Methods.ID);
2252     unsigned NumInstanceMethods = 0;
2253     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2254          Method = Method->Next)
2255       if (Method->Method)
2256         ++NumInstanceMethods;
2257 
2258     unsigned NumFactoryMethods = 0;
2259     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2260          Method = Method->Next)
2261       if (Method->Method)
2262         ++NumFactoryMethods;
2263 
2264     clang::io::Emit16(Out, NumInstanceMethods);
2265     clang::io::Emit16(Out, NumFactoryMethods);
2266     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2267          Method = Method->Next)
2268       if (Method->Method)
2269         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2270     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2271          Method = Method->Next)
2272       if (Method->Method)
2273         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2274 
2275     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2276   }
2277 };
2278 } // end anonymous namespace
2279 
2280 /// \brief Write ObjC data: selectors and the method pool.
2281 ///
2282 /// The method pool contains both instance and factory methods, stored
2283 /// in an on-disk hash table indexed by the selector. The hash table also
2284 /// contains an empty entry for every other selector known to Sema.
2285 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2286   using namespace llvm;
2287 
2288   // Do we have to do anything at all?
2289   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2290     return;
2291   unsigned NumTableEntries = 0;
2292   // Create and write out the blob that contains selectors and the method pool.
2293   {
2294     OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2295     ASTMethodPoolTrait Trait(*this);
2296 
2297     // Create the on-disk hash table representation. We walk through every
2298     // selector we've seen and look it up in the method pool.
2299     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2300     for (llvm::DenseMap<Selector, SelectorID>::iterator
2301              I = SelectorIDs.begin(), E = SelectorIDs.end();
2302          I != E; ++I) {
2303       Selector S = I->first;
2304       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2305       ASTMethodPoolTrait::data_type Data = {
2306         I->second,
2307         ObjCMethodList(),
2308         ObjCMethodList()
2309       };
2310       if (F != SemaRef.MethodPool.end()) {
2311         Data.Instance = F->second.first;
2312         Data.Factory = F->second.second;
2313       }
2314       // Only write this selector if it's not in an existing AST or something
2315       // changed.
2316       if (Chain && I->second < FirstSelectorID) {
2317         // Selector already exists. Did it change?
2318         bool changed = false;
2319         for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2320              M = M->Next) {
2321           if (!M->Method->isFromASTFile())
2322             changed = true;
2323         }
2324         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2325              M = M->Next) {
2326           if (!M->Method->isFromASTFile())
2327             changed = true;
2328         }
2329         if (!changed)
2330           continue;
2331       } else if (Data.Instance.Method || Data.Factory.Method) {
2332         // A new method pool entry.
2333         ++NumTableEntries;
2334       }
2335       Generator.insert(S, Data, Trait);
2336     }
2337 
2338     // Create the on-disk hash table in a buffer.
2339     llvm::SmallString<4096> MethodPool;
2340     uint32_t BucketOffset;
2341     {
2342       ASTMethodPoolTrait Trait(*this);
2343       llvm::raw_svector_ostream Out(MethodPool);
2344       // Make sure that no bucket is at offset 0
2345       clang::io::Emit32(Out, 0);
2346       BucketOffset = Generator.Emit(Out, Trait);
2347     }
2348 
2349     // Create a blob abbreviation
2350     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2351     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2352     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2353     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2354     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2355     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2356 
2357     // Write the method pool
2358     RecordData Record;
2359     Record.push_back(METHOD_POOL);
2360     Record.push_back(BucketOffset);
2361     Record.push_back(NumTableEntries);
2362     Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2363 
2364     // Create a blob abbreviation for the selector table offsets.
2365     Abbrev = new BitCodeAbbrev();
2366     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2367     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2368     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2369     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2370     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2371 
2372     // Write the selector offsets table.
2373     Record.clear();
2374     Record.push_back(SELECTOR_OFFSETS);
2375     Record.push_back(SelectorOffsets.size());
2376     Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2377     Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2378                               data(SelectorOffsets));
2379   }
2380 }
2381 
2382 /// \brief Write the selectors referenced in @selector expression into AST file.
2383 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2384   using namespace llvm;
2385   if (SemaRef.ReferencedSelectors.empty())
2386     return;
2387 
2388   RecordData Record;
2389 
2390   // Note: this writes out all references even for a dependent AST. But it is
2391   // very tricky to fix, and given that @selector shouldn't really appear in
2392   // headers, probably not worth it. It's not a correctness issue.
2393   for (DenseMap<Selector, SourceLocation>::iterator S =
2394        SemaRef.ReferencedSelectors.begin(),
2395        E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2396     Selector Sel = (*S).first;
2397     SourceLocation Loc = (*S).second;
2398     AddSelectorRef(Sel, Record);
2399     AddSourceLocation(Loc, Record);
2400   }
2401   Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2402 }
2403 
2404 //===----------------------------------------------------------------------===//
2405 // Identifier Table Serialization
2406 //===----------------------------------------------------------------------===//
2407 
2408 namespace {
2409 class ASTIdentifierTableTrait {
2410   ASTWriter &Writer;
2411   Preprocessor &PP;
2412   IdentifierResolver &IdResolver;
2413   bool IsModule;
2414 
2415   /// \brief Determines whether this is an "interesting" identifier
2416   /// that needs a full IdentifierInfo structure written into the hash
2417   /// table.
2418   bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) {
2419     if (II->isPoisoned() ||
2420         II->isExtensionToken() ||
2421         II->getObjCOrBuiltinID() ||
2422         II->hasRevertedTokenIDToIdentifier() ||
2423         II->getFETokenInfo<void>())
2424       return true;
2425 
2426     return hasMacroDefinition(II, Macro);
2427   }
2428 
2429   bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) {
2430     if (!II->hasMacroDefinition())
2431       return false;
2432 
2433     if (Macro || (Macro = PP.getMacroInfo(II)))
2434       return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
2435 
2436     return false;
2437   }
2438 
2439 public:
2440   typedef IdentifierInfo* key_type;
2441   typedef key_type  key_type_ref;
2442 
2443   typedef IdentID data_type;
2444   typedef data_type data_type_ref;
2445 
2446   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
2447                           IdentifierResolver &IdResolver, bool IsModule)
2448     : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
2449 
2450   static unsigned ComputeHash(const IdentifierInfo* II) {
2451     return llvm::HashString(II->getName());
2452   }
2453 
2454   std::pair<unsigned,unsigned>
2455   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
2456     unsigned KeyLen = II->getLength() + 1;
2457     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2458     MacroInfo *Macro = 0;
2459     if (isInterestingIdentifier(II, Macro)) {
2460       DataLen += 2; // 2 bytes for builtin ID, flags
2461       if (hasMacroDefinition(II, Macro))
2462         DataLen += 8;
2463 
2464       for (IdentifierResolver::iterator D = IdResolver.begin(II),
2465                                      DEnd = IdResolver.end();
2466            D != DEnd; ++D)
2467         DataLen += sizeof(DeclID);
2468     }
2469     clang::io::Emit16(Out, DataLen);
2470     // We emit the key length after the data length so that every
2471     // string is preceded by a 16-bit length. This matches the PTH
2472     // format for storing identifiers.
2473     clang::io::Emit16(Out, KeyLen);
2474     return std::make_pair(KeyLen, DataLen);
2475   }
2476 
2477   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
2478                unsigned KeyLen) {
2479     // Record the location of the key data.  This is used when generating
2480     // the mapping from persistent IDs to strings.
2481     Writer.SetIdentifierOffset(II, Out.tell());
2482     Out.write(II->getNameStart(), KeyLen);
2483   }
2484 
2485   void EmitData(raw_ostream& Out, IdentifierInfo* II,
2486                 IdentID ID, unsigned) {
2487     MacroInfo *Macro = 0;
2488     if (!isInterestingIdentifier(II, Macro)) {
2489       clang::io::Emit32(Out, ID << 1);
2490       return;
2491     }
2492 
2493     clang::io::Emit32(Out, (ID << 1) | 0x01);
2494     uint32_t Bits = 0;
2495     bool HasMacroDefinition = hasMacroDefinition(II, Macro);
2496     Bits = (uint32_t)II->getObjCOrBuiltinID();
2497     Bits = (Bits << 1) | unsigned(HasMacroDefinition);
2498     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2499     Bits = (Bits << 1) | unsigned(II->isPoisoned());
2500     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2501     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2502     clang::io::Emit16(Out, Bits);
2503 
2504     if (HasMacroDefinition) {
2505       clang::io::Emit32(Out, Writer.getMacroOffset(II));
2506       clang::io::Emit32(Out,
2507         Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc()));
2508     }
2509 
2510     // Emit the declaration IDs in reverse order, because the
2511     // IdentifierResolver provides the declarations as they would be
2512     // visible (e.g., the function "stat" would come before the struct
2513     // "stat"), but the ASTReader adds declarations to the end of the list
2514     // (so we need to see the struct "status" before the function "status").
2515     // Only emit declarations that aren't from a chained PCH, though.
2516     SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
2517                                   IdResolver.end());
2518     for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2519                                                 DEnd = Decls.rend();
2520          D != DEnd; ++D)
2521       clang::io::Emit32(Out, Writer.getDeclID(*D));
2522   }
2523 };
2524 } // end anonymous namespace
2525 
2526 /// \brief Write the identifier table into the AST file.
2527 ///
2528 /// The identifier table consists of a blob containing string data
2529 /// (the actual identifiers themselves) and a separate "offsets" index
2530 /// that maps identifier IDs to locations within the blob.
2531 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
2532                                      IdentifierResolver &IdResolver,
2533                                      bool IsModule) {
2534   using namespace llvm;
2535 
2536   // Create and write out the blob that contains the identifier
2537   // strings.
2538   {
2539     OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2540     ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2541 
2542     // Look for any identifiers that were named while processing the
2543     // headers, but are otherwise not needed. We add these to the hash
2544     // table to enable checking of the predefines buffer in the case
2545     // where the user adds new macro definitions when building the AST
2546     // file.
2547     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2548                                 IDEnd = PP.getIdentifierTable().end();
2549          ID != IDEnd; ++ID)
2550       getIdentifierRef(ID->second);
2551 
2552     // Create the on-disk hash table representation. We only store offsets
2553     // for identifiers that appear here for the first time.
2554     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2555     for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2556            ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2557          ID != IDEnd; ++ID) {
2558       assert(ID->first && "NULL identifier in identifier table");
2559       if (!Chain || !ID->first->isFromAST() ||
2560           ID->first->hasChangedSinceDeserialization())
2561         Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
2562                          Trait);
2563     }
2564 
2565     // Create the on-disk hash table in a buffer.
2566     llvm::SmallString<4096> IdentifierTable;
2567     uint32_t BucketOffset;
2568     {
2569       ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
2570       llvm::raw_svector_ostream Out(IdentifierTable);
2571       // Make sure that no bucket is at offset 0
2572       clang::io::Emit32(Out, 0);
2573       BucketOffset = Generator.Emit(Out, Trait);
2574     }
2575 
2576     // Create a blob abbreviation
2577     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2578     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2579     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2580     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2581     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2582 
2583     // Write the identifier table
2584     RecordData Record;
2585     Record.push_back(IDENTIFIER_TABLE);
2586     Record.push_back(BucketOffset);
2587     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2588   }
2589 
2590   // Write the offsets table for identifier IDs.
2591   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2592   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2593   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2594   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2595   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2596   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2597 
2598   RecordData Record;
2599   Record.push_back(IDENTIFIER_OFFSET);
2600   Record.push_back(IdentifierOffsets.size());
2601   Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
2602   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2603                             data(IdentifierOffsets));
2604 }
2605 
2606 //===----------------------------------------------------------------------===//
2607 // DeclContext's Name Lookup Table Serialization
2608 //===----------------------------------------------------------------------===//
2609 
2610 namespace {
2611 // Trait used for the on-disk hash table used in the method pool.
2612 class ASTDeclContextNameLookupTrait {
2613   ASTWriter &Writer;
2614 
2615 public:
2616   typedef DeclarationName key_type;
2617   typedef key_type key_type_ref;
2618 
2619   typedef DeclContext::lookup_result data_type;
2620   typedef const data_type& data_type_ref;
2621 
2622   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2623 
2624   unsigned ComputeHash(DeclarationName Name) {
2625     llvm::FoldingSetNodeID ID;
2626     ID.AddInteger(Name.getNameKind());
2627 
2628     switch (Name.getNameKind()) {
2629     case DeclarationName::Identifier:
2630       ID.AddString(Name.getAsIdentifierInfo()->getName());
2631       break;
2632     case DeclarationName::ObjCZeroArgSelector:
2633     case DeclarationName::ObjCOneArgSelector:
2634     case DeclarationName::ObjCMultiArgSelector:
2635       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2636       break;
2637     case DeclarationName::CXXConstructorName:
2638     case DeclarationName::CXXDestructorName:
2639     case DeclarationName::CXXConversionFunctionName:
2640       break;
2641     case DeclarationName::CXXOperatorName:
2642       ID.AddInteger(Name.getCXXOverloadedOperator());
2643       break;
2644     case DeclarationName::CXXLiteralOperatorName:
2645       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2646     case DeclarationName::CXXUsingDirective:
2647       break;
2648     }
2649 
2650     return ID.ComputeHash();
2651   }
2652 
2653   std::pair<unsigned,unsigned>
2654     EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
2655                       data_type_ref Lookup) {
2656     unsigned KeyLen = 1;
2657     switch (Name.getNameKind()) {
2658     case DeclarationName::Identifier:
2659     case DeclarationName::ObjCZeroArgSelector:
2660     case DeclarationName::ObjCOneArgSelector:
2661     case DeclarationName::ObjCMultiArgSelector:
2662     case DeclarationName::CXXLiteralOperatorName:
2663       KeyLen += 4;
2664       break;
2665     case DeclarationName::CXXOperatorName:
2666       KeyLen += 1;
2667       break;
2668     case DeclarationName::CXXConstructorName:
2669     case DeclarationName::CXXDestructorName:
2670     case DeclarationName::CXXConversionFunctionName:
2671     case DeclarationName::CXXUsingDirective:
2672       break;
2673     }
2674     clang::io::Emit16(Out, KeyLen);
2675 
2676     // 2 bytes for num of decls and 4 for each DeclID.
2677     unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2678     clang::io::Emit16(Out, DataLen);
2679 
2680     return std::make_pair(KeyLen, DataLen);
2681   }
2682 
2683   void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
2684     using namespace clang::io;
2685 
2686     assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2687     Emit8(Out, Name.getNameKind());
2688     switch (Name.getNameKind()) {
2689     case DeclarationName::Identifier:
2690       Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2691       break;
2692     case DeclarationName::ObjCZeroArgSelector:
2693     case DeclarationName::ObjCOneArgSelector:
2694     case DeclarationName::ObjCMultiArgSelector:
2695       Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2696       break;
2697     case DeclarationName::CXXOperatorName:
2698       assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2699       Emit8(Out, Name.getCXXOverloadedOperator());
2700       break;
2701     case DeclarationName::CXXLiteralOperatorName:
2702       Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2703       break;
2704     case DeclarationName::CXXConstructorName:
2705     case DeclarationName::CXXDestructorName:
2706     case DeclarationName::CXXConversionFunctionName:
2707     case DeclarationName::CXXUsingDirective:
2708       break;
2709     }
2710   }
2711 
2712   void EmitData(raw_ostream& Out, key_type_ref,
2713                 data_type Lookup, unsigned DataLen) {
2714     uint64_t Start = Out.tell(); (void)Start;
2715     clang::io::Emit16(Out, Lookup.second - Lookup.first);
2716     for (; Lookup.first != Lookup.second; ++Lookup.first)
2717       clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2718 
2719     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2720   }
2721 };
2722 } // end anonymous namespace
2723 
2724 /// \brief Write the block containing all of the declaration IDs
2725 /// visible from the given DeclContext.
2726 ///
2727 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2728 /// bitstream, or 0 if no block was written.
2729 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2730                                                  DeclContext *DC) {
2731   if (DC->getPrimaryContext() != DC)
2732     return 0;
2733 
2734   // Since there is no name lookup into functions or methods, don't bother to
2735   // build a visible-declarations table for these entities.
2736   if (DC->isFunctionOrMethod())
2737     return 0;
2738 
2739   // If not in C++, we perform name lookup for the translation unit via the
2740   // IdentifierInfo chains, don't bother to build a visible-declarations table.
2741   // FIXME: In C++ we need the visible declarations in order to "see" the
2742   // friend declarations, is there a way to do this without writing the table ?
2743   if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2744     return 0;
2745 
2746   // Force the DeclContext to build a its name-lookup table.
2747   if (!DC->hasExternalVisibleStorage())
2748     DC->lookup(DeclarationName());
2749 
2750   // Serialize the contents of the mapping used for lookup. Note that,
2751   // although we have two very different code paths, the serialized
2752   // representation is the same for both cases: a declaration name,
2753   // followed by a size, followed by references to the visible
2754   // declarations that have that name.
2755   uint64_t Offset = Stream.GetCurrentBitNo();
2756   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2757   if (!Map || Map->empty())
2758     return 0;
2759 
2760   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2761   ASTDeclContextNameLookupTrait Trait(*this);
2762 
2763   // Create the on-disk hash table representation.
2764   DeclarationName ConversionName;
2765   llvm::SmallVector<NamedDecl *, 4> ConversionDecls;
2766   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2767        D != DEnd; ++D) {
2768     DeclarationName Name = D->first;
2769     DeclContext::lookup_result Result = D->second.getLookupResult();
2770     if (Result.first != Result.second) {
2771       if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2772         // Hash all conversion function names to the same name. The actual
2773         // type information in conversion function name is not used in the
2774         // key (since such type information is not stable across different
2775         // modules), so the intended effect is to coalesce all of the conversion
2776         // functions under a single key.
2777         if (!ConversionName)
2778           ConversionName = Name;
2779         ConversionDecls.append(Result.first, Result.second);
2780         continue;
2781       }
2782 
2783       Generator.insert(Name, Result, Trait);
2784     }
2785   }
2786 
2787   // Add the conversion functions
2788   if (!ConversionDecls.empty()) {
2789     Generator.insert(ConversionName,
2790                      DeclContext::lookup_result(ConversionDecls.begin(),
2791                                                 ConversionDecls.end()),
2792                      Trait);
2793   }
2794 
2795   // Create the on-disk hash table in a buffer.
2796   llvm::SmallString<4096> LookupTable;
2797   uint32_t BucketOffset;
2798   {
2799     llvm::raw_svector_ostream Out(LookupTable);
2800     // Make sure that no bucket is at offset 0
2801     clang::io::Emit32(Out, 0);
2802     BucketOffset = Generator.Emit(Out, Trait);
2803   }
2804 
2805   // Write the lookup table
2806   RecordData Record;
2807   Record.push_back(DECL_CONTEXT_VISIBLE);
2808   Record.push_back(BucketOffset);
2809   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2810                             LookupTable.str());
2811 
2812   Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2813   ++NumVisibleDeclContexts;
2814   return Offset;
2815 }
2816 
2817 /// \brief Write an UPDATE_VISIBLE block for the given context.
2818 ///
2819 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2820 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2821 /// (in C++) and for namespaces.
2822 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2823   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2824   if (!Map || Map->empty())
2825     return;
2826 
2827   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2828   ASTDeclContextNameLookupTrait Trait(*this);
2829 
2830   // Create the hash table.
2831   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2832        D != DEnd; ++D) {
2833     DeclarationName Name = D->first;
2834     DeclContext::lookup_result Result = D->second.getLookupResult();
2835     // For any name that appears in this table, the results are complete, i.e.
2836     // they overwrite results from previous PCHs. Merging is always a mess.
2837     if (Result.first != Result.second)
2838       Generator.insert(Name, Result, Trait);
2839   }
2840 
2841   // Create the on-disk hash table in a buffer.
2842   llvm::SmallString<4096> LookupTable;
2843   uint32_t BucketOffset;
2844   {
2845     llvm::raw_svector_ostream Out(LookupTable);
2846     // Make sure that no bucket is at offset 0
2847     clang::io::Emit32(Out, 0);
2848     BucketOffset = Generator.Emit(Out, Trait);
2849   }
2850 
2851   // Write the lookup table
2852   RecordData Record;
2853   Record.push_back(UPDATE_VISIBLE);
2854   Record.push_back(getDeclID(cast<Decl>(DC)));
2855   Record.push_back(BucketOffset);
2856   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2857 }
2858 
2859 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
2860 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2861   RecordData Record;
2862   Record.push_back(Opts.fp_contract);
2863   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2864 }
2865 
2866 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
2867 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2868   if (!SemaRef.Context.getLangOptions().OpenCL)
2869     return;
2870 
2871   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2872   RecordData Record;
2873 #define OPENCLEXT(nm)  Record.push_back(Opts.nm);
2874 #include "clang/Basic/OpenCLExtensions.def"
2875   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2876 }
2877 
2878 //===----------------------------------------------------------------------===//
2879 // General Serialization Routines
2880 //===----------------------------------------------------------------------===//
2881 
2882 /// \brief Write a record containing the given attributes.
2883 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2884   Record.push_back(Attrs.size());
2885   for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2886     const Attr * A = *i;
2887     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2888     AddSourceRange(A->getRange(), Record);
2889 
2890 #include "clang/Serialization/AttrPCHWrite.inc"
2891 
2892   }
2893 }
2894 
2895 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
2896   Record.push_back(Str.size());
2897   Record.insert(Record.end(), Str.begin(), Str.end());
2898 }
2899 
2900 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
2901                                 RecordDataImpl &Record) {
2902   Record.push_back(Version.getMajor());
2903   if (llvm::Optional<unsigned> Minor = Version.getMinor())
2904     Record.push_back(*Minor + 1);
2905   else
2906     Record.push_back(0);
2907   if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
2908     Record.push_back(*Subminor + 1);
2909   else
2910     Record.push_back(0);
2911 }
2912 
2913 /// \brief Note that the identifier II occurs at the given offset
2914 /// within the identifier table.
2915 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2916   IdentID ID = IdentifierIDs[II];
2917   // Only store offsets new to this AST file. Other identifier names are looked
2918   // up earlier in the chain and thus don't need an offset.
2919   if (ID >= FirstIdentID)
2920     IdentifierOffsets[ID - FirstIdentID] = Offset;
2921 }
2922 
2923 /// \brief Note that the selector Sel occurs at the given offset
2924 /// within the method pool/selector table.
2925 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2926   unsigned ID = SelectorIDs[Sel];
2927   assert(ID && "Unknown selector");
2928   // Don't record offsets for selectors that are also available in a different
2929   // file.
2930   if (ID < FirstSelectorID)
2931     return;
2932   SelectorOffsets[ID - FirstSelectorID] = Offset;
2933 }
2934 
2935 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2936   : Stream(Stream), Context(0), PP(0), Chain(0), WritingAST(false),
2937     FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
2938     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2939     FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
2940     FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
2941     NextSubmoduleID(FirstSubmoduleID),
2942     FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
2943     CollectedStmts(&StmtsToEmit),
2944     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2945     NumVisibleDeclContexts(0),
2946     NextCXXBaseSpecifiersID(1),
2947     DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
2948     DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
2949     DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
2950     DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
2951     DeclTypedefAbbrev(0),
2952     DeclVarAbbrev(0), DeclFieldAbbrev(0),
2953     DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
2954 {
2955 }
2956 
2957 ASTWriter::~ASTWriter() {
2958   for (FileDeclIDsTy::iterator
2959          I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
2960     delete I->second;
2961 }
2962 
2963 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2964                          const std::string &OutputFile,
2965                          Module *WritingModule, StringRef isysroot) {
2966   WritingAST = true;
2967 
2968   // Emit the file header.
2969   Stream.Emit((unsigned)'C', 8);
2970   Stream.Emit((unsigned)'P', 8);
2971   Stream.Emit((unsigned)'C', 8);
2972   Stream.Emit((unsigned)'H', 8);
2973 
2974   WriteBlockInfoBlock();
2975 
2976   Context = &SemaRef.Context;
2977   PP = &SemaRef.PP;
2978   WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule);
2979   Context = 0;
2980   PP = 0;
2981 
2982   WritingAST = false;
2983 }
2984 
2985 template<typename Vector>
2986 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
2987                                ASTWriter::RecordData &Record) {
2988   for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
2989        I != E; ++I)  {
2990     Writer.AddDeclRef(*I, Record);
2991   }
2992 }
2993 
2994 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2995                              StringRef isysroot,
2996                              const std::string &OutputFile,
2997                              Module *WritingModule) {
2998   using namespace llvm;
2999 
3000   // Make sure that the AST reader knows to finalize itself.
3001   if (Chain)
3002     Chain->finalizeForWriting();
3003 
3004   ASTContext &Context = SemaRef.Context;
3005   Preprocessor &PP = SemaRef.PP;
3006 
3007   // Set up predefined declaration IDs.
3008   DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
3009   if (Context.ObjCIdDecl)
3010     DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
3011   if (Context.ObjCSelDecl)
3012     DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
3013   if (Context.ObjCClassDecl)
3014     DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
3015   if (Context.Int128Decl)
3016     DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3017   if (Context.UInt128Decl)
3018     DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
3019   if (Context.ObjCInstanceTypeDecl)
3020     DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
3021 
3022   if (!Chain) {
3023     // Make sure that we emit IdentifierInfos (and any attached
3024     // declarations) for builtins. We don't need to do this when we're
3025     // emitting chained PCH files, because all of the builtins will be
3026     // in the original PCH file.
3027     // FIXME: Modules won't like this at all.
3028     IdentifierTable &Table = PP.getIdentifierTable();
3029     SmallVector<const char *, 32> BuiltinNames;
3030     Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
3031                                         Context.getLangOptions().NoBuiltin);
3032     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3033       getIdentifierRef(&Table.get(BuiltinNames[I]));
3034   }
3035 
3036   // If there are any out-of-date identifiers, bring them up to date.
3037   if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
3038     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3039                                 IDEnd = PP.getIdentifierTable().end();
3040          ID != IDEnd; ++ID)
3041       if (ID->second->isOutOfDate())
3042         ExtSource->updateOutOfDateIdentifier(*ID->second);
3043   }
3044 
3045   // Build a record containing all of the tentative definitions in this file, in
3046   // TentativeDefinitions order.  Generally, this record will be empty for
3047   // headers.
3048   RecordData TentativeDefinitions;
3049   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
3050 
3051   // Build a record containing all of the file scoped decls in this file.
3052   RecordData UnusedFileScopedDecls;
3053   AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3054                      UnusedFileScopedDecls);
3055 
3056   // Build a record containing all of the delegating constructors we still need
3057   // to resolve.
3058   RecordData DelegatingCtorDecls;
3059   AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
3060 
3061   // Write the set of weak, undeclared identifiers. We always write the
3062   // entire table, since later PCH files in a PCH chain are only interested in
3063   // the results at the end of the chain.
3064   RecordData WeakUndeclaredIdentifiers;
3065   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
3066     for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
3067          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3068          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3069       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3070       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3071       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3072       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3073     }
3074   }
3075 
3076   // Build a record containing all of the locally-scoped external
3077   // declarations in this header file. Generally, this record will be
3078   // empty.
3079   RecordData LocallyScopedExternalDecls;
3080   // FIXME: This is filling in the AST file in densemap order which is
3081   // nondeterminstic!
3082   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3083          TD = SemaRef.LocallyScopedExternalDecls.begin(),
3084          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3085        TD != TDEnd; ++TD) {
3086     if (!TD->second->isFromASTFile())
3087       AddDeclRef(TD->second, LocallyScopedExternalDecls);
3088   }
3089 
3090   // Build a record containing all of the ext_vector declarations.
3091   RecordData ExtVectorDecls;
3092   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
3093 
3094   // Build a record containing all of the VTable uses information.
3095   RecordData VTableUses;
3096   if (!SemaRef.VTableUses.empty()) {
3097     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3098       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3099       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3100       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3101     }
3102   }
3103 
3104   // Build a record containing all of dynamic classes declarations.
3105   RecordData DynamicClasses;
3106   AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
3107 
3108   // Build a record containing all of pending implicit instantiations.
3109   RecordData PendingInstantiations;
3110   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3111          I = SemaRef.PendingInstantiations.begin(),
3112          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3113     AddDeclRef(I->first, PendingInstantiations);
3114     AddSourceLocation(I->second, PendingInstantiations);
3115   }
3116   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3117          "There are local ones at end of translation unit!");
3118 
3119   // Build a record containing some declaration references.
3120   RecordData SemaDeclRefs;
3121   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3122     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3123     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3124   }
3125 
3126   RecordData CUDASpecialDeclRefs;
3127   if (Context.getcudaConfigureCallDecl()) {
3128     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3129   }
3130 
3131   // Build a record containing all of the known namespaces.
3132   RecordData KnownNamespaces;
3133   for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3134             I = SemaRef.KnownNamespaces.begin(),
3135          IEnd = SemaRef.KnownNamespaces.end();
3136        I != IEnd; ++I) {
3137     if (!I->second)
3138       AddDeclRef(I->first, KnownNamespaces);
3139   }
3140 
3141   // Write the remaining AST contents.
3142   RecordData Record;
3143   Stream.EnterSubblock(AST_BLOCK_ID, 5);
3144   WriteMetadata(Context, isysroot, OutputFile);
3145   WriteLanguageOptions(Context.getLangOptions());
3146   if (StatCalls && isysroot.empty())
3147     WriteStatCache(*StatCalls);
3148 
3149   // Create a lexical update block containing all of the declarations in the
3150   // translation unit that do not come from other AST files.
3151   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3152   SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3153   for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3154                                   E = TU->noload_decls_end();
3155        I != E; ++I) {
3156     if (!(*I)->isFromASTFile())
3157       NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
3158   }
3159 
3160   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3161   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3162   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3163   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3164   Record.clear();
3165   Record.push_back(TU_UPDATE_LEXICAL);
3166   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3167                             data(NewGlobalDecls));
3168 
3169   // And a visible updates block for the translation unit.
3170   Abv = new llvm::BitCodeAbbrev();
3171   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3172   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3173   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3174   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3175   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3176   WriteDeclContextVisibleUpdate(TU);
3177 
3178   // If the translation unit has an anonymous namespace, and we don't already
3179   // have an update block for it, write it as an update block.
3180   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
3181     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
3182     if (Record.empty()) {
3183       Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
3184       Record.push_back(reinterpret_cast<uint64_t>(NS));
3185     }
3186   }
3187 
3188   // Resolve any declaration pointers within the declaration updates block.
3189   ResolveDeclUpdatesBlocks();
3190 
3191   // Form the record of special types.
3192   RecordData SpecialTypes;
3193   AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes);
3194   AddTypeRef(Context.ObjCProtoType, SpecialTypes);
3195   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
3196   AddTypeRef(Context.getFILEType(), SpecialTypes);
3197   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
3198   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
3199   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
3200   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
3201   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
3202   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
3203 
3204   // If we're emitting a module, write out the submodule information.
3205   if (WritingModule)
3206     WriteSubmodules(WritingModule);
3207 
3208   // Keep writing types and declarations until all types and
3209   // declarations have been written.
3210   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3211   WriteDeclsBlockAbbrevs();
3212   for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
3213                                   E = DeclsToRewrite.end();
3214        I != E; ++I)
3215     DeclTypesToEmit.push(const_cast<Decl*>(*I));
3216   while (!DeclTypesToEmit.empty()) {
3217     DeclOrType DOT = DeclTypesToEmit.front();
3218     DeclTypesToEmit.pop();
3219     if (DOT.isType())
3220       WriteType(DOT.getType());
3221     else
3222       WriteDecl(Context, DOT.getDecl());
3223   }
3224   Stream.ExitBlock();
3225 
3226   WriteFileDeclIDsMap();
3227   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
3228 
3229   if (Chain) {
3230     // Write the mapping information describing our module dependencies and how
3231     // each of those modules were mapped into our own offset/ID space, so that
3232     // the reader can build the appropriate mapping to its own offset/ID space.
3233     // The map consists solely of a blob with the following format:
3234     // *(module-name-len:i16 module-name:len*i8
3235     //   source-location-offset:i32
3236     //   identifier-id:i32
3237     //   preprocessed-entity-id:i32
3238     //   macro-definition-id:i32
3239     //   submodule-id:i32
3240     //   selector-id:i32
3241     //   declaration-id:i32
3242     //   c++-base-specifiers-id:i32
3243     //   type-id:i32)
3244     //
3245     llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3246     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
3247     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3248     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
3249     llvm::SmallString<2048> Buffer;
3250     {
3251       llvm::raw_svector_ostream Out(Buffer);
3252       for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
3253                                            MEnd = Chain->ModuleMgr.end();
3254            M != MEnd; ++M) {
3255         StringRef FileName = (*M)->FileName;
3256         io::Emit16(Out, FileName.size());
3257         Out.write(FileName.data(), FileName.size());
3258         io::Emit32(Out, (*M)->SLocEntryBaseOffset);
3259         io::Emit32(Out, (*M)->BaseIdentifierID);
3260         io::Emit32(Out, (*M)->BasePreprocessedEntityID);
3261         io::Emit32(Out, (*M)->BaseSubmoduleID);
3262         io::Emit32(Out, (*M)->BaseSelectorID);
3263         io::Emit32(Out, (*M)->BaseDeclID);
3264         io::Emit32(Out, (*M)->BaseTypeIndex);
3265       }
3266     }
3267     Record.clear();
3268     Record.push_back(MODULE_OFFSET_MAP);
3269     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
3270                               Buffer.data(), Buffer.size());
3271   }
3272   WritePreprocessor(PP, WritingModule != 0);
3273   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
3274   WriteSelectors(SemaRef);
3275   WriteReferencedSelectorsPool(SemaRef);
3276   WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0);
3277   WriteFPPragmaOptions(SemaRef.getFPOptions());
3278   WriteOpenCLExtensions(SemaRef);
3279 
3280   WriteTypeDeclOffsets();
3281   WritePragmaDiagnosticMappings(Context.getDiagnostics());
3282 
3283   WriteCXXBaseSpecifiersOffsets();
3284 
3285   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
3286 
3287   /// Build a record containing first declarations from a chained PCH and the
3288   /// most recent declarations in this AST that they point to.
3289   RecordData FirstLatestDeclIDs;
3290   for (FirstLatestDeclMap::iterator I = FirstLatestDecls.begin(),
3291                                     E = FirstLatestDecls.end();
3292        I != E; ++I) {
3293     AddDeclRef(I->first, FirstLatestDeclIDs);
3294     AddDeclRef(I->second, FirstLatestDeclIDs);
3295   }
3296 
3297   if (!FirstLatestDeclIDs.empty())
3298     Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3299 
3300   // Write the record containing external, unnamed definitions.
3301   if (!ExternalDefinitions.empty())
3302     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3303 
3304   // Write the record containing tentative definitions.
3305   if (!TentativeDefinitions.empty())
3306     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3307 
3308   // Write the record containing unused file scoped decls.
3309   if (!UnusedFileScopedDecls.empty())
3310     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3311 
3312   // Write the record containing weak undeclared identifiers.
3313   if (!WeakUndeclaredIdentifiers.empty())
3314     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3315                       WeakUndeclaredIdentifiers);
3316 
3317   // Write the record containing locally-scoped external definitions.
3318   if (!LocallyScopedExternalDecls.empty())
3319     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3320                       LocallyScopedExternalDecls);
3321 
3322   // Write the record containing ext_vector type names.
3323   if (!ExtVectorDecls.empty())
3324     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3325 
3326   // Write the record containing VTable uses information.
3327   if (!VTableUses.empty())
3328     Stream.EmitRecord(VTABLE_USES, VTableUses);
3329 
3330   // Write the record containing dynamic classes declarations.
3331   if (!DynamicClasses.empty())
3332     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3333 
3334   // Write the record containing pending implicit instantiations.
3335   if (!PendingInstantiations.empty())
3336     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3337 
3338   // Write the record containing declaration references of Sema.
3339   if (!SemaDeclRefs.empty())
3340     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3341 
3342   // Write the record containing CUDA-specific declaration references.
3343   if (!CUDASpecialDeclRefs.empty())
3344     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
3345 
3346   // Write the delegating constructors.
3347   if (!DelegatingCtorDecls.empty())
3348     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
3349 
3350   // Write the known namespaces.
3351   if (!KnownNamespaces.empty())
3352     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
3353 
3354   // Write the visible updates to DeclContexts.
3355   for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3356        I = UpdatedDeclContexts.begin(),
3357        E = UpdatedDeclContexts.end();
3358        I != E; ++I)
3359     WriteDeclContextVisibleUpdate(*I);
3360 
3361   if (!WritingModule) {
3362     // Write the submodules that were imported, if any.
3363     RecordData ImportedModules;
3364     for (ASTContext::import_iterator I = Context.local_import_begin(),
3365                                   IEnd = Context.local_import_end();
3366          I != IEnd; ++I) {
3367       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
3368       ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
3369     }
3370     if (!ImportedModules.empty()) {
3371       // Sort module IDs.
3372       llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
3373 
3374       // Unique module IDs.
3375       ImportedModules.erase(std::unique(ImportedModules.begin(),
3376                                         ImportedModules.end()),
3377                             ImportedModules.end());
3378 
3379       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
3380     }
3381   }
3382 
3383   WriteDeclUpdatesBlocks();
3384   WriteDeclReplacementsBlock();
3385   WriteChainedObjCCategories();
3386 
3387   // Some simple statistics
3388   Record.clear();
3389   Record.push_back(NumStatements);
3390   Record.push_back(NumMacros);
3391   Record.push_back(NumLexicalDeclContexts);
3392   Record.push_back(NumVisibleDeclContexts);
3393   Stream.EmitRecord(STATISTICS, Record);
3394   Stream.ExitBlock();
3395 }
3396 
3397 /// \brief Go through the declaration update blocks and resolve declaration
3398 /// pointers into declaration IDs.
3399 void ASTWriter::ResolveDeclUpdatesBlocks() {
3400   for (DeclUpdateMap::iterator
3401        I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3402     const Decl *D = I->first;
3403     UpdateRecord &URec = I->second;
3404 
3405     if (isRewritten(D))
3406       continue; // The decl will be written completely
3407 
3408     unsigned Idx = 0, N = URec.size();
3409     while (Idx < N) {
3410       switch ((DeclUpdateKind)URec[Idx++]) {
3411       case UPD_CXX_SET_DEFINITIONDATA:
3412       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
3413       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3414       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
3415         URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
3416         ++Idx;
3417         break;
3418 
3419       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3420         ++Idx;
3421         break;
3422       }
3423     }
3424   }
3425 }
3426 
3427 void ASTWriter::WriteDeclUpdatesBlocks() {
3428   if (DeclUpdates.empty())
3429     return;
3430 
3431   RecordData OffsetsRecord;
3432   Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
3433   for (DeclUpdateMap::iterator
3434          I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3435     const Decl *D = I->first;
3436     UpdateRecord &URec = I->second;
3437 
3438     if (isRewritten(D))
3439       continue; // The decl will be written completely,no need to store updates.
3440 
3441     uint64_t Offset = Stream.GetCurrentBitNo();
3442     Stream.EmitRecord(DECL_UPDATES, URec);
3443 
3444     OffsetsRecord.push_back(GetDeclRef(D));
3445     OffsetsRecord.push_back(Offset);
3446   }
3447   Stream.ExitBlock();
3448   Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3449 }
3450 
3451 void ASTWriter::WriteDeclReplacementsBlock() {
3452   if (ReplacedDecls.empty())
3453     return;
3454 
3455   RecordData Record;
3456   for (SmallVector<ReplacedDeclInfo, 16>::iterator
3457            I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3458     Record.push_back(I->ID);
3459     Record.push_back(I->Offset);
3460     Record.push_back(I->Loc);
3461   }
3462   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3463 }
3464 
3465 void ASTWriter::WriteChainedObjCCategories() {
3466   if (LocalChainedObjCCategories.empty())
3467     return;
3468 
3469   RecordData Record;
3470   for (SmallVector<ChainedObjCCategoriesData, 16>::iterator
3471          I = LocalChainedObjCCategories.begin(),
3472          E = LocalChainedObjCCategories.end(); I != E; ++I) {
3473     ChainedObjCCategoriesData &Data = *I;
3474     if (isRewritten(Data.Interface))
3475       continue;
3476 
3477     assert(Data.Interface->getCategoryList());
3478     serialization::DeclID
3479         HeadCatID = getDeclID(Data.Interface->getCategoryList());
3480 
3481     Record.push_back(getDeclID(Data.Interface));
3482     Record.push_back(HeadCatID);
3483     Record.push_back(getDeclID(Data.TailCategory));
3484   }
3485   Stream.EmitRecord(OBJC_CHAINED_CATEGORIES, Record);
3486 }
3487 
3488 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3489   Record.push_back(Loc.getRawEncoding());
3490 }
3491 
3492 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3493   AddSourceLocation(Range.getBegin(), Record);
3494   AddSourceLocation(Range.getEnd(), Record);
3495 }
3496 
3497 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3498   Record.push_back(Value.getBitWidth());
3499   const uint64_t *Words = Value.getRawData();
3500   Record.append(Words, Words + Value.getNumWords());
3501 }
3502 
3503 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3504   Record.push_back(Value.isUnsigned());
3505   AddAPInt(Value, Record);
3506 }
3507 
3508 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3509   AddAPInt(Value.bitcastToAPInt(), Record);
3510 }
3511 
3512 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3513   Record.push_back(getIdentifierRef(II));
3514 }
3515 
3516 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3517   if (II == 0)
3518     return 0;
3519 
3520   IdentID &ID = IdentifierIDs[II];
3521   if (ID == 0)
3522     ID = NextIdentID++;
3523   return ID;
3524 }
3525 
3526 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3527   Record.push_back(getSelectorRef(SelRef));
3528 }
3529 
3530 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3531   if (Sel.getAsOpaquePtr() == 0) {
3532     return 0;
3533   }
3534 
3535   SelectorID &SID = SelectorIDs[Sel];
3536   if (SID == 0 && Chain) {
3537     // This might trigger a ReadSelector callback, which will set the ID for
3538     // this selector.
3539     Chain->LoadSelector(Sel);
3540   }
3541   if (SID == 0) {
3542     SID = NextSelectorID++;
3543   }
3544   return SID;
3545 }
3546 
3547 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3548   AddDeclRef(Temp->getDestructor(), Record);
3549 }
3550 
3551 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3552                                       CXXBaseSpecifier const *BasesEnd,
3553                                         RecordDataImpl &Record) {
3554   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3555   CXXBaseSpecifiersToWrite.push_back(
3556                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3557                                                         Bases, BasesEnd));
3558   Record.push_back(NextCXXBaseSpecifiersID++);
3559 }
3560 
3561 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3562                                            const TemplateArgumentLocInfo &Arg,
3563                                            RecordDataImpl &Record) {
3564   switch (Kind) {
3565   case TemplateArgument::Expression:
3566     AddStmt(Arg.getAsExpr());
3567     break;
3568   case TemplateArgument::Type:
3569     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3570     break;
3571   case TemplateArgument::Template:
3572     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3573     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3574     break;
3575   case TemplateArgument::TemplateExpansion:
3576     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3577     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3578     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3579     break;
3580   case TemplateArgument::Null:
3581   case TemplateArgument::Integral:
3582   case TemplateArgument::Declaration:
3583   case TemplateArgument::Pack:
3584     break;
3585   }
3586 }
3587 
3588 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3589                                        RecordDataImpl &Record) {
3590   AddTemplateArgument(Arg.getArgument(), Record);
3591 
3592   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3593     bool InfoHasSameExpr
3594       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3595     Record.push_back(InfoHasSameExpr);
3596     if (InfoHasSameExpr)
3597       return; // Avoid storing the same expr twice.
3598   }
3599   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3600                              Record);
3601 }
3602 
3603 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3604                                   RecordDataImpl &Record) {
3605   if (TInfo == 0) {
3606     AddTypeRef(QualType(), Record);
3607     return;
3608   }
3609 
3610   AddTypeLoc(TInfo->getTypeLoc(), Record);
3611 }
3612 
3613 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3614   AddTypeRef(TL.getType(), Record);
3615 
3616   TypeLocWriter TLW(*this, Record);
3617   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3618     TLW.Visit(TL);
3619 }
3620 
3621 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3622   Record.push_back(GetOrCreateTypeID(T));
3623 }
3624 
3625 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
3626   return MakeTypeID(*Context, T,
3627               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3628 }
3629 
3630 TypeID ASTWriter::getTypeID(QualType T) const {
3631   return MakeTypeID(*Context, T,
3632               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3633 }
3634 
3635 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3636   if (T.isNull())
3637     return TypeIdx();
3638   assert(!T.getLocalFastQualifiers());
3639 
3640   TypeIdx &Idx = TypeIdxs[T];
3641   if (Idx.getIndex() == 0) {
3642     // We haven't seen this type before. Assign it a new ID and put it
3643     // into the queue of types to emit.
3644     Idx = TypeIdx(NextTypeID++);
3645     DeclTypesToEmit.push(T);
3646   }
3647   return Idx;
3648 }
3649 
3650 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3651   if (T.isNull())
3652     return TypeIdx();
3653   assert(!T.getLocalFastQualifiers());
3654 
3655   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3656   assert(I != TypeIdxs.end() && "Type not emitted!");
3657   return I->second;
3658 }
3659 
3660 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3661   Record.push_back(GetDeclRef(D));
3662 }
3663 
3664 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3665   assert(WritingAST && "Cannot request a declaration ID before AST writing");
3666 
3667   if (D == 0) {
3668     return 0;
3669   }
3670   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3671   DeclID &ID = DeclIDs[D];
3672   if (ID == 0) {
3673     // We haven't seen this declaration before. Give it a new ID and
3674     // enqueue it in the list of declarations to emit.
3675     ID = NextDeclID++;
3676     DeclTypesToEmit.push(const_cast<Decl *>(D));
3677   }
3678 
3679   return ID;
3680 }
3681 
3682 DeclID ASTWriter::getDeclID(const Decl *D) {
3683   if (D == 0)
3684     return 0;
3685 
3686   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3687   return DeclIDs[D];
3688 }
3689 
3690 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
3691                                std::pair<unsigned, serialization::DeclID> R) {
3692   return L.first < R.first;
3693 }
3694 
3695 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
3696   assert(ID);
3697   assert(D);
3698 
3699   SourceLocation Loc = D->getLocation();
3700   if (Loc.isInvalid())
3701     return;
3702 
3703   // We only keep track of the file-level declarations of each file.
3704   if (!D->getLexicalDeclContext()->isFileContext())
3705     return;
3706 
3707   SourceManager &SM = Context->getSourceManager();
3708   SourceLocation FileLoc = SM.getFileLoc(Loc);
3709   assert(SM.isLocalSourceLocation(FileLoc));
3710   FileID FID;
3711   unsigned Offset;
3712   llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
3713   if (FID.isInvalid())
3714     return;
3715   const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID);
3716   assert(Entry->isFile());
3717 
3718   DeclIDInFileInfo *&Info = FileDeclIDs[Entry];
3719   if (!Info)
3720     Info = new DeclIDInFileInfo();
3721 
3722   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
3723   LocDeclIDsTy &Decls = Info->DeclIDs;
3724 
3725   if (Decls.empty() || Decls.back().first <= Offset) {
3726     Decls.push_back(LocDecl);
3727     return;
3728   }
3729 
3730   LocDeclIDsTy::iterator
3731     I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
3732 
3733   Decls.insert(I, LocDecl);
3734 }
3735 
3736 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3737   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
3738   Record.push_back(Name.getNameKind());
3739   switch (Name.getNameKind()) {
3740   case DeclarationName::Identifier:
3741     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3742     break;
3743 
3744   case DeclarationName::ObjCZeroArgSelector:
3745   case DeclarationName::ObjCOneArgSelector:
3746   case DeclarationName::ObjCMultiArgSelector:
3747     AddSelectorRef(Name.getObjCSelector(), Record);
3748     break;
3749 
3750   case DeclarationName::CXXConstructorName:
3751   case DeclarationName::CXXDestructorName:
3752   case DeclarationName::CXXConversionFunctionName:
3753     AddTypeRef(Name.getCXXNameType(), Record);
3754     break;
3755 
3756   case DeclarationName::CXXOperatorName:
3757     Record.push_back(Name.getCXXOverloadedOperator());
3758     break;
3759 
3760   case DeclarationName::CXXLiteralOperatorName:
3761     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3762     break;
3763 
3764   case DeclarationName::CXXUsingDirective:
3765     // No extra data to emit
3766     break;
3767   }
3768 }
3769 
3770 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3771                                      DeclarationName Name, RecordDataImpl &Record) {
3772   switch (Name.getNameKind()) {
3773   case DeclarationName::CXXConstructorName:
3774   case DeclarationName::CXXDestructorName:
3775   case DeclarationName::CXXConversionFunctionName:
3776     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3777     break;
3778 
3779   case DeclarationName::CXXOperatorName:
3780     AddSourceLocation(
3781        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3782        Record);
3783     AddSourceLocation(
3784         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3785         Record);
3786     break;
3787 
3788   case DeclarationName::CXXLiteralOperatorName:
3789     AddSourceLocation(
3790      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3791      Record);
3792     break;
3793 
3794   case DeclarationName::Identifier:
3795   case DeclarationName::ObjCZeroArgSelector:
3796   case DeclarationName::ObjCOneArgSelector:
3797   case DeclarationName::ObjCMultiArgSelector:
3798   case DeclarationName::CXXUsingDirective:
3799     break;
3800   }
3801 }
3802 
3803 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3804                                        RecordDataImpl &Record) {
3805   AddDeclarationName(NameInfo.getName(), Record);
3806   AddSourceLocation(NameInfo.getLoc(), Record);
3807   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3808 }
3809 
3810 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3811                                  RecordDataImpl &Record) {
3812   AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3813   Record.push_back(Info.NumTemplParamLists);
3814   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3815     AddTemplateParameterList(Info.TemplParamLists[i], Record);
3816 }
3817 
3818 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3819                                        RecordDataImpl &Record) {
3820   // Nested name specifiers usually aren't too long. I think that 8 would
3821   // typically accommodate the vast majority.
3822   SmallVector<NestedNameSpecifier *, 8> NestedNames;
3823 
3824   // Push each of the NNS's onto a stack for serialization in reverse order.
3825   while (NNS) {
3826     NestedNames.push_back(NNS);
3827     NNS = NNS->getPrefix();
3828   }
3829 
3830   Record.push_back(NestedNames.size());
3831   while(!NestedNames.empty()) {
3832     NNS = NestedNames.pop_back_val();
3833     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3834     Record.push_back(Kind);
3835     switch (Kind) {
3836     case NestedNameSpecifier::Identifier:
3837       AddIdentifierRef(NNS->getAsIdentifier(), Record);
3838       break;
3839 
3840     case NestedNameSpecifier::Namespace:
3841       AddDeclRef(NNS->getAsNamespace(), Record);
3842       break;
3843 
3844     case NestedNameSpecifier::NamespaceAlias:
3845       AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3846       break;
3847 
3848     case NestedNameSpecifier::TypeSpec:
3849     case NestedNameSpecifier::TypeSpecWithTemplate:
3850       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3851       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3852       break;
3853 
3854     case NestedNameSpecifier::Global:
3855       // Don't need to write an associated value.
3856       break;
3857     }
3858   }
3859 }
3860 
3861 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3862                                           RecordDataImpl &Record) {
3863   // Nested name specifiers usually aren't too long. I think that 8 would
3864   // typically accommodate the vast majority.
3865   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3866 
3867   // Push each of the nested-name-specifiers's onto a stack for
3868   // serialization in reverse order.
3869   while (NNS) {
3870     NestedNames.push_back(NNS);
3871     NNS = NNS.getPrefix();
3872   }
3873 
3874   Record.push_back(NestedNames.size());
3875   while(!NestedNames.empty()) {
3876     NNS = NestedNames.pop_back_val();
3877     NestedNameSpecifier::SpecifierKind Kind
3878       = NNS.getNestedNameSpecifier()->getKind();
3879     Record.push_back(Kind);
3880     switch (Kind) {
3881     case NestedNameSpecifier::Identifier:
3882       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3883       AddSourceRange(NNS.getLocalSourceRange(), Record);
3884       break;
3885 
3886     case NestedNameSpecifier::Namespace:
3887       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3888       AddSourceRange(NNS.getLocalSourceRange(), Record);
3889       break;
3890 
3891     case NestedNameSpecifier::NamespaceAlias:
3892       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3893       AddSourceRange(NNS.getLocalSourceRange(), Record);
3894       break;
3895 
3896     case NestedNameSpecifier::TypeSpec:
3897     case NestedNameSpecifier::TypeSpecWithTemplate:
3898       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3899       AddTypeLoc(NNS.getTypeLoc(), Record);
3900       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3901       break;
3902 
3903     case NestedNameSpecifier::Global:
3904       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3905       break;
3906     }
3907   }
3908 }
3909 
3910 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3911   TemplateName::NameKind Kind = Name.getKind();
3912   Record.push_back(Kind);
3913   switch (Kind) {
3914   case TemplateName::Template:
3915     AddDeclRef(Name.getAsTemplateDecl(), Record);
3916     break;
3917 
3918   case TemplateName::OverloadedTemplate: {
3919     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3920     Record.push_back(OvT->size());
3921     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3922            I != E; ++I)
3923       AddDeclRef(*I, Record);
3924     break;
3925   }
3926 
3927   case TemplateName::QualifiedTemplate: {
3928     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3929     AddNestedNameSpecifier(QualT->getQualifier(), Record);
3930     Record.push_back(QualT->hasTemplateKeyword());
3931     AddDeclRef(QualT->getTemplateDecl(), Record);
3932     break;
3933   }
3934 
3935   case TemplateName::DependentTemplate: {
3936     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3937     AddNestedNameSpecifier(DepT->getQualifier(), Record);
3938     Record.push_back(DepT->isIdentifier());
3939     if (DepT->isIdentifier())
3940       AddIdentifierRef(DepT->getIdentifier(), Record);
3941     else
3942       Record.push_back(DepT->getOperator());
3943     break;
3944   }
3945 
3946   case TemplateName::SubstTemplateTemplateParm: {
3947     SubstTemplateTemplateParmStorage *subst
3948       = Name.getAsSubstTemplateTemplateParm();
3949     AddDeclRef(subst->getParameter(), Record);
3950     AddTemplateName(subst->getReplacement(), Record);
3951     break;
3952   }
3953 
3954   case TemplateName::SubstTemplateTemplateParmPack: {
3955     SubstTemplateTemplateParmPackStorage *SubstPack
3956       = Name.getAsSubstTemplateTemplateParmPack();
3957     AddDeclRef(SubstPack->getParameterPack(), Record);
3958     AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3959     break;
3960   }
3961   }
3962 }
3963 
3964 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3965                                     RecordDataImpl &Record) {
3966   Record.push_back(Arg.getKind());
3967   switch (Arg.getKind()) {
3968   case TemplateArgument::Null:
3969     break;
3970   case TemplateArgument::Type:
3971     AddTypeRef(Arg.getAsType(), Record);
3972     break;
3973   case TemplateArgument::Declaration:
3974     AddDeclRef(Arg.getAsDecl(), Record);
3975     break;
3976   case TemplateArgument::Integral:
3977     AddAPSInt(*Arg.getAsIntegral(), Record);
3978     AddTypeRef(Arg.getIntegralType(), Record);
3979     break;
3980   case TemplateArgument::Template:
3981     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3982     break;
3983   case TemplateArgument::TemplateExpansion:
3984     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3985     if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3986       Record.push_back(*NumExpansions + 1);
3987     else
3988       Record.push_back(0);
3989     break;
3990   case TemplateArgument::Expression:
3991     AddStmt(Arg.getAsExpr());
3992     break;
3993   case TemplateArgument::Pack:
3994     Record.push_back(Arg.pack_size());
3995     for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3996            I != E; ++I)
3997       AddTemplateArgument(*I, Record);
3998     break;
3999   }
4000 }
4001 
4002 void
4003 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
4004                                     RecordDataImpl &Record) {
4005   assert(TemplateParams && "No TemplateParams!");
4006   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4007   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4008   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4009   Record.push_back(TemplateParams->size());
4010   for (TemplateParameterList::const_iterator
4011          P = TemplateParams->begin(), PEnd = TemplateParams->end();
4012          P != PEnd; ++P)
4013     AddDeclRef(*P, Record);
4014 }
4015 
4016 /// \brief Emit a template argument list.
4017 void
4018 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
4019                                    RecordDataImpl &Record) {
4020   assert(TemplateArgs && "No TemplateArgs!");
4021   Record.push_back(TemplateArgs->size());
4022   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
4023     AddTemplateArgument(TemplateArgs->get(i), Record);
4024 }
4025 
4026 
4027 void
4028 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
4029   Record.push_back(Set.size());
4030   for (UnresolvedSetImpl::const_iterator
4031          I = Set.begin(), E = Set.end(); I != E; ++I) {
4032     AddDeclRef(I.getDecl(), Record);
4033     Record.push_back(I.getAccess());
4034   }
4035 }
4036 
4037 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
4038                                     RecordDataImpl &Record) {
4039   Record.push_back(Base.isVirtual());
4040   Record.push_back(Base.isBaseOfClass());
4041   Record.push_back(Base.getAccessSpecifierAsWritten());
4042   Record.push_back(Base.getInheritConstructors());
4043   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
4044   AddSourceRange(Base.getSourceRange(), Record);
4045   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
4046                                           : SourceLocation(),
4047                     Record);
4048 }
4049 
4050 void ASTWriter::FlushCXXBaseSpecifiers() {
4051   RecordData Record;
4052   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
4053     Record.clear();
4054 
4055     // Record the offset of this base-specifier set.
4056     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
4057     if (Index == CXXBaseSpecifiersOffsets.size())
4058       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
4059     else {
4060       if (Index > CXXBaseSpecifiersOffsets.size())
4061         CXXBaseSpecifiersOffsets.resize(Index + 1);
4062       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
4063     }
4064 
4065     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
4066                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
4067     Record.push_back(BEnd - B);
4068     for (; B != BEnd; ++B)
4069       AddCXXBaseSpecifier(*B, Record);
4070     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
4071 
4072     // Flush any expressions that were written as part of the base specifiers.
4073     FlushStmts();
4074   }
4075 
4076   CXXBaseSpecifiersToWrite.clear();
4077 }
4078 
4079 void ASTWriter::AddCXXCtorInitializers(
4080                              const CXXCtorInitializer * const *CtorInitializers,
4081                              unsigned NumCtorInitializers,
4082                              RecordDataImpl &Record) {
4083   Record.push_back(NumCtorInitializers);
4084   for (unsigned i=0; i != NumCtorInitializers; ++i) {
4085     const CXXCtorInitializer *Init = CtorInitializers[i];
4086 
4087     if (Init->isBaseInitializer()) {
4088       Record.push_back(CTOR_INITIALIZER_BASE);
4089       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4090       Record.push_back(Init->isBaseVirtual());
4091     } else if (Init->isDelegatingInitializer()) {
4092       Record.push_back(CTOR_INITIALIZER_DELEGATING);
4093       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
4094     } else if (Init->isMemberInitializer()){
4095       Record.push_back(CTOR_INITIALIZER_MEMBER);
4096       AddDeclRef(Init->getMember(), Record);
4097     } else {
4098       Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
4099       AddDeclRef(Init->getIndirectMember(), Record);
4100     }
4101 
4102     AddSourceLocation(Init->getMemberLocation(), Record);
4103     AddStmt(Init->getInit());
4104     AddSourceLocation(Init->getLParenLoc(), Record);
4105     AddSourceLocation(Init->getRParenLoc(), Record);
4106     Record.push_back(Init->isWritten());
4107     if (Init->isWritten()) {
4108       Record.push_back(Init->getSourceOrder());
4109     } else {
4110       Record.push_back(Init->getNumArrayIndices());
4111       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
4112         AddDeclRef(Init->getArrayIndex(i), Record);
4113     }
4114   }
4115 }
4116 
4117 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
4118   assert(D->DefinitionData);
4119   struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
4120   Record.push_back(Data.UserDeclaredConstructor);
4121   Record.push_back(Data.UserDeclaredCopyConstructor);
4122   Record.push_back(Data.UserDeclaredMoveConstructor);
4123   Record.push_back(Data.UserDeclaredCopyAssignment);
4124   Record.push_back(Data.UserDeclaredMoveAssignment);
4125   Record.push_back(Data.UserDeclaredDestructor);
4126   Record.push_back(Data.Aggregate);
4127   Record.push_back(Data.PlainOldData);
4128   Record.push_back(Data.Empty);
4129   Record.push_back(Data.Polymorphic);
4130   Record.push_back(Data.Abstract);
4131   Record.push_back(Data.IsStandardLayout);
4132   Record.push_back(Data.HasNoNonEmptyBases);
4133   Record.push_back(Data.HasPrivateFields);
4134   Record.push_back(Data.HasProtectedFields);
4135   Record.push_back(Data.HasPublicFields);
4136   Record.push_back(Data.HasMutableFields);
4137   Record.push_back(Data.HasTrivialDefaultConstructor);
4138   Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
4139   Record.push_back(Data.HasTrivialCopyConstructor);
4140   Record.push_back(Data.HasTrivialMoveConstructor);
4141   Record.push_back(Data.HasTrivialCopyAssignment);
4142   Record.push_back(Data.HasTrivialMoveAssignment);
4143   Record.push_back(Data.HasTrivialDestructor);
4144   Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
4145   Record.push_back(Data.ComputedVisibleConversions);
4146   Record.push_back(Data.UserProvidedDefaultConstructor);
4147   Record.push_back(Data.DeclaredDefaultConstructor);
4148   Record.push_back(Data.DeclaredCopyConstructor);
4149   Record.push_back(Data.DeclaredMoveConstructor);
4150   Record.push_back(Data.DeclaredCopyAssignment);
4151   Record.push_back(Data.DeclaredMoveAssignment);
4152   Record.push_back(Data.DeclaredDestructor);
4153   Record.push_back(Data.FailedImplicitMoveConstructor);
4154   Record.push_back(Data.FailedImplicitMoveAssignment);
4155 
4156   Record.push_back(Data.NumBases);
4157   if (Data.NumBases > 0)
4158     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
4159                             Record);
4160 
4161   // FIXME: Make VBases lazily computed when needed to avoid storing them.
4162   Record.push_back(Data.NumVBases);
4163   if (Data.NumVBases > 0)
4164     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
4165                             Record);
4166 
4167   AddUnresolvedSet(Data.Conversions, Record);
4168   AddUnresolvedSet(Data.VisibleConversions, Record);
4169   // Data.Definition is the owning decl, no need to write it.
4170   AddDeclRef(Data.FirstFriend, Record);
4171 }
4172 
4173 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
4174   assert(Reader && "Cannot remove chain");
4175   assert((!Chain || Chain == Reader) && "Cannot replace chain");
4176   assert(FirstDeclID == NextDeclID &&
4177          FirstTypeID == NextTypeID &&
4178          FirstIdentID == NextIdentID &&
4179          FirstSubmoduleID == NextSubmoduleID &&
4180          FirstSelectorID == NextSelectorID &&
4181          "Setting chain after writing has started.");
4182 
4183   Chain = Reader;
4184 
4185   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
4186   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
4187   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
4188   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
4189   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
4190   NextDeclID = FirstDeclID;
4191   NextTypeID = FirstTypeID;
4192   NextIdentID = FirstIdentID;
4193   NextSelectorID = FirstSelectorID;
4194   NextSubmoduleID = FirstSubmoduleID;
4195 }
4196 
4197 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
4198   IdentifierIDs[II] = ID;
4199   if (II->hasMacroDefinition())
4200     DeserializedMacroNames.push_back(II);
4201 }
4202 
4203 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
4204   // Always take the highest-numbered type index. This copes with an interesting
4205   // case for chained AST writing where we schedule writing the type and then,
4206   // later, deserialize the type from another AST. In this case, we want to
4207   // keep the higher-numbered entry so that we can properly write it out to
4208   // the AST file.
4209   TypeIdx &StoredIdx = TypeIdxs[T];
4210   if (Idx.getIndex() >= StoredIdx.getIndex())
4211     StoredIdx = Idx;
4212 }
4213 
4214 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
4215   DeclIDs[D] = ID;
4216 }
4217 
4218 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
4219   SelectorIDs[S] = ID;
4220 }
4221 
4222 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
4223                                     MacroDefinition *MD) {
4224   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
4225   MacroDefinitions[MD] = ID;
4226 }
4227 
4228 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
4229   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
4230   SubmoduleIDs[Mod] = ID;
4231 }
4232 
4233 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
4234   assert(D->isCompleteDefinition());
4235   assert(!WritingAST && "Already writing the AST!");
4236   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
4237     // We are interested when a PCH decl is modified.
4238     if (RD->isFromASTFile()) {
4239       // A forward reference was mutated into a definition. Rewrite it.
4240       // FIXME: This happens during template instantiation, should we
4241       // have created a new definition decl instead ?
4242       RewriteDecl(RD);
4243     }
4244 
4245     for (CXXRecordDecl::redecl_iterator
4246            I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
4247       CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
4248       if (Redecl == RD)
4249         continue;
4250 
4251       // We are interested when a PCH decl is modified.
4252       if (Redecl->isFromASTFile()) {
4253         UpdateRecord &Record = DeclUpdates[Redecl];
4254         Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
4255         assert(Redecl->DefinitionData);
4256         assert(Redecl->DefinitionData->Definition == D);
4257         Record.push_back(reinterpret_cast<uint64_t>(D)); // the DefinitionDecl
4258       }
4259     }
4260   }
4261 }
4262 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
4263   assert(!WritingAST && "Already writing the AST!");
4264 
4265   // TU and namespaces are handled elsewhere.
4266   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
4267     return;
4268 
4269   if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
4270     return; // Not a source decl added to a DeclContext from PCH.
4271 
4272   AddUpdatedDeclContext(DC);
4273 }
4274 
4275 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
4276   assert(!WritingAST && "Already writing the AST!");
4277   assert(D->isImplicit());
4278   if (!(!D->isFromASTFile() && RD->isFromASTFile()))
4279     return; // Not a source member added to a class from PCH.
4280   if (!isa<CXXMethodDecl>(D))
4281     return; // We are interested in lazily declared implicit methods.
4282 
4283   // A decl coming from PCH was modified.
4284   assert(RD->isCompleteDefinition());
4285   UpdateRecord &Record = DeclUpdates[RD];
4286   Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
4287   Record.push_back(reinterpret_cast<uint64_t>(D));
4288 }
4289 
4290 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
4291                                      const ClassTemplateSpecializationDecl *D) {
4292   // The specializations set is kept in the canonical template.
4293   assert(!WritingAST && "Already writing the AST!");
4294   TD = TD->getCanonicalDecl();
4295   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4296     return; // Not a source specialization added to a template from PCH.
4297 
4298   UpdateRecord &Record = DeclUpdates[TD];
4299   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4300   Record.push_back(reinterpret_cast<uint64_t>(D));
4301 }
4302 
4303 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
4304                                                const FunctionDecl *D) {
4305   // The specializations set is kept in the canonical template.
4306   assert(!WritingAST && "Already writing the AST!");
4307   TD = TD->getCanonicalDecl();
4308   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
4309     return; // Not a source specialization added to a template from PCH.
4310 
4311   UpdateRecord &Record = DeclUpdates[TD];
4312   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
4313   Record.push_back(reinterpret_cast<uint64_t>(D));
4314 }
4315 
4316 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
4317   assert(!WritingAST && "Already writing the AST!");
4318   if (!D->isFromASTFile())
4319     return; // Declaration not imported from PCH.
4320 
4321   // Implicit decl from a PCH was defined.
4322   // FIXME: Should implicit definition be a separate FunctionDecl?
4323   RewriteDecl(D);
4324 }
4325 
4326 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
4327   assert(!WritingAST && "Already writing the AST!");
4328   if (!D->isFromASTFile())
4329     return;
4330 
4331   // Since the actual instantiation is delayed, this really means that we need
4332   // to update the instantiation location.
4333   UpdateRecord &Record = DeclUpdates[D];
4334   Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
4335   AddSourceLocation(
4336       D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
4337 }
4338 
4339 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
4340                                              const ObjCInterfaceDecl *IFD) {
4341   assert(!WritingAST && "Already writing the AST!");
4342   if (!IFD->isFromASTFile())
4343     return; // Declaration not imported from PCH.
4344   if (CatD->getNextClassCategory() &&
4345       !CatD->getNextClassCategory()->isFromASTFile())
4346     return; // We already recorded that the tail of a category chain should be
4347             // attached to an interface.
4348 
4349   ChainedObjCCategoriesData Data =  { IFD, CatD };
4350   LocalChainedObjCCategories.push_back(Data);
4351 }
4352 
4353 void ASTWriter::CompletedObjCForwardRef(const ObjCContainerDecl *D) {
4354   assert(!WritingAST && "Already writing the AST!");
4355   if (!D->isFromASTFile())
4356     return; // Declaration not imported from PCH.
4357 
4358   RewriteDecl(D);
4359 }
4360 
4361 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
4362                                           const ObjCPropertyDecl *OrigProp,
4363                                           const ObjCCategoryDecl *ClassExt) {
4364   const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
4365   if (!D)
4366     return;
4367 
4368   assert(!WritingAST && "Already writing the AST!");
4369   if (!D->isFromASTFile())
4370     return; // Declaration not imported from PCH.
4371 
4372   RewriteDecl(D);
4373 }
4374 
4375 void ASTWriter::UpdatedAttributeList(const Decl *D) {
4376   assert(!WritingAST && "Already writing the AST!");
4377   if (!D->isFromASTFile())
4378     return; // Declaration not imported from PCH.
4379 
4380   RewriteDecl(D);
4381 }
4382