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