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