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 "clang/Serialization/ASTSerializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Sema/Sema.h"
18 #include "clang/Sema/IdentifierResolver.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemStatCache.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.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 <cstdio>
48 using namespace clang;
49 using namespace clang::serialization;
50 
51 template <typename T, typename Allocator>
52 T *data(std::vector<T, Allocator> &v) {
53   return v.empty() ? 0 : &v.front();
54 }
55 template <typename T, typename Allocator>
56 const T *data(const std::vector<T, Allocator> &v) {
57   return v.empty() ? 0 : &v.front();
58 }
59 
60 //===----------------------------------------------------------------------===//
61 // Type serialization
62 //===----------------------------------------------------------------------===//
63 
64 namespace {
65   class ASTTypeWriter {
66     ASTWriter &Writer;
67     ASTWriter::RecordDataImpl &Record;
68 
69   public:
70     /// \brief Type code that corresponds to the record generated.
71     TypeCode Code;
72 
73     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
74       : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
75 
76     void VisitArrayType(const ArrayType *T);
77     void VisitFunctionType(const FunctionType *T);
78     void VisitTagType(const TagType *T);
79 
80 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
81 #define ABSTRACT_TYPE(Class, Base)
82 #include "clang/AST/TypeNodes.def"
83   };
84 }
85 
86 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
87   assert(false && "Built-in types are never serialized");
88 }
89 
90 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
91   Writer.AddTypeRef(T->getElementType(), Record);
92   Code = TYPE_COMPLEX;
93 }
94 
95 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
96   Writer.AddTypeRef(T->getPointeeType(), Record);
97   Code = TYPE_POINTER;
98 }
99 
100 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
101   Writer.AddTypeRef(T->getPointeeType(), Record);
102   Code = TYPE_BLOCK_POINTER;
103 }
104 
105 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
106   Writer.AddTypeRef(T->getPointeeType(), Record);
107   Code = TYPE_LVALUE_REFERENCE;
108 }
109 
110 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
111   Writer.AddTypeRef(T->getPointeeType(), Record);
112   Code = TYPE_RVALUE_REFERENCE;
113 }
114 
115 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
116   Writer.AddTypeRef(T->getPointeeType(), Record);
117   Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
118   Code = TYPE_MEMBER_POINTER;
119 }
120 
121 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
122   Writer.AddTypeRef(T->getElementType(), Record);
123   Record.push_back(T->getSizeModifier()); // FIXME: stable values
124   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
125 }
126 
127 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
128   VisitArrayType(T);
129   Writer.AddAPInt(T->getSize(), Record);
130   Code = TYPE_CONSTANT_ARRAY;
131 }
132 
133 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
134   VisitArrayType(T);
135   Code = TYPE_INCOMPLETE_ARRAY;
136 }
137 
138 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
139   VisitArrayType(T);
140   Writer.AddSourceLocation(T->getLBracketLoc(), Record);
141   Writer.AddSourceLocation(T->getRBracketLoc(), Record);
142   Writer.AddStmt(T->getSizeExpr());
143   Code = TYPE_VARIABLE_ARRAY;
144 }
145 
146 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
147   Writer.AddTypeRef(T->getElementType(), Record);
148   Record.push_back(T->getNumElements());
149   Record.push_back(T->getVectorKind());
150   Code = TYPE_VECTOR;
151 }
152 
153 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
154   VisitVectorType(T);
155   Code = TYPE_EXT_VECTOR;
156 }
157 
158 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
159   Writer.AddTypeRef(T->getResultType(), Record);
160   FunctionType::ExtInfo C = T->getExtInfo();
161   Record.push_back(C.getNoReturn());
162   Record.push_back(C.getRegParm());
163   // FIXME: need to stabilize encoding of calling convention...
164   Record.push_back(C.getCC());
165 }
166 
167 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
168   VisitFunctionType(T);
169   Code = TYPE_FUNCTION_NO_PROTO;
170 }
171 
172 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
173   VisitFunctionType(T);
174   Record.push_back(T->getNumArgs());
175   for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
176     Writer.AddTypeRef(T->getArgType(I), Record);
177   Record.push_back(T->isVariadic());
178   Record.push_back(T->getTypeQuals());
179   Record.push_back(T->hasExceptionSpec());
180   Record.push_back(T->hasAnyExceptionSpec());
181   Record.push_back(T->getNumExceptions());
182   for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
183     Writer.AddTypeRef(T->getExceptionType(I), Record);
184   Code = TYPE_FUNCTION_PROTO;
185 }
186 
187 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
188   Writer.AddDeclRef(T->getDecl(), Record);
189   Code = TYPE_UNRESOLVED_USING;
190 }
191 
192 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
193   Writer.AddDeclRef(T->getDecl(), Record);
194   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
195   Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
196   Code = TYPE_TYPEDEF;
197 }
198 
199 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
200   Writer.AddStmt(T->getUnderlyingExpr());
201   Code = TYPE_TYPEOF_EXPR;
202 }
203 
204 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
205   Writer.AddTypeRef(T->getUnderlyingType(), Record);
206   Code = TYPE_TYPEOF;
207 }
208 
209 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
210   Writer.AddStmt(T->getUnderlyingExpr());
211   Code = TYPE_DECLTYPE;
212 }
213 
214 void ASTTypeWriter::VisitTagType(const TagType *T) {
215   Record.push_back(T->isDependentType());
216   Writer.AddDeclRef(T->getDecl(), Record);
217   assert(!T->isBeingDefined() &&
218          "Cannot serialize in the middle of a type definition");
219 }
220 
221 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
222   VisitTagType(T);
223   Code = TYPE_RECORD;
224 }
225 
226 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
227   VisitTagType(T);
228   Code = TYPE_ENUM;
229 }
230 
231 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
232   Writer.AddTypeRef(T->getModifiedType(), Record);
233   Writer.AddTypeRef(T->getEquivalentType(), Record);
234   Record.push_back(T->getAttrKind());
235   Code = TYPE_ATTRIBUTED;
236 }
237 
238 void
239 ASTTypeWriter::VisitSubstTemplateTypeParmType(
240                                         const SubstTemplateTypeParmType *T) {
241   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
242   Writer.AddTypeRef(T->getReplacementType(), Record);
243   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
244 }
245 
246 void
247 ASTTypeWriter::VisitTemplateSpecializationType(
248                                        const TemplateSpecializationType *T) {
249   Record.push_back(T->isDependentType());
250   Writer.AddTemplateName(T->getTemplateName(), Record);
251   Record.push_back(T->getNumArgs());
252   for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
253          ArgI != ArgE; ++ArgI)
254     Writer.AddTemplateArgument(*ArgI, Record);
255   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
256                                                 : T->getCanonicalTypeInternal(),
257                     Record);
258   Code = TYPE_TEMPLATE_SPECIALIZATION;
259 }
260 
261 void
262 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
263   VisitArrayType(T);
264   Writer.AddStmt(T->getSizeExpr());
265   Writer.AddSourceRange(T->getBracketsRange(), Record);
266   Code = TYPE_DEPENDENT_SIZED_ARRAY;
267 }
268 
269 void
270 ASTTypeWriter::VisitDependentSizedExtVectorType(
271                                         const DependentSizedExtVectorType *T) {
272   // FIXME: Serialize this type (C++ only)
273   assert(false && "Cannot serialize dependent sized extended vector types");
274 }
275 
276 void
277 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
278   Record.push_back(T->getDepth());
279   Record.push_back(T->getIndex());
280   Record.push_back(T->isParameterPack());
281   Writer.AddIdentifierRef(T->getName(), Record);
282   Code = TYPE_TEMPLATE_TYPE_PARM;
283 }
284 
285 void
286 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
287   Record.push_back(T->getKeyword());
288   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
289   Writer.AddIdentifierRef(T->getIdentifier(), Record);
290   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
291                                                 : T->getCanonicalTypeInternal(),
292                     Record);
293   Code = TYPE_DEPENDENT_NAME;
294 }
295 
296 void
297 ASTTypeWriter::VisitDependentTemplateSpecializationType(
298                                 const DependentTemplateSpecializationType *T) {
299   Record.push_back(T->getKeyword());
300   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
301   Writer.AddIdentifierRef(T->getIdentifier(), Record);
302   Record.push_back(T->getNumArgs());
303   for (DependentTemplateSpecializationType::iterator
304          I = T->begin(), E = T->end(); I != E; ++I)
305     Writer.AddTemplateArgument(*I, Record);
306   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
307 }
308 
309 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
310   Writer.AddTypeRef(T->getPattern(), Record);
311   Code = TYPE_PACK_EXPANSION;
312 }
313 
314 void ASTTypeWriter::VisitParenType(const ParenType *T) {
315   Writer.AddTypeRef(T->getInnerType(), Record);
316   Code = TYPE_PAREN;
317 }
318 
319 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
320   Record.push_back(T->getKeyword());
321   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
322   Writer.AddTypeRef(T->getNamedType(), Record);
323   Code = TYPE_ELABORATED;
324 }
325 
326 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
327   Writer.AddDeclRef(T->getDecl(), Record);
328   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
329   Code = TYPE_INJECTED_CLASS_NAME;
330 }
331 
332 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
333   Writer.AddDeclRef(T->getDecl(), Record);
334   Code = TYPE_OBJC_INTERFACE;
335 }
336 
337 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
338   Writer.AddTypeRef(T->getBaseType(), Record);
339   Record.push_back(T->getNumProtocols());
340   for (ObjCObjectType::qual_iterator I = T->qual_begin(),
341        E = T->qual_end(); I != E; ++I)
342     Writer.AddDeclRef(*I, Record);
343   Code = TYPE_OBJC_OBJECT;
344 }
345 
346 void
347 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
348   Writer.AddTypeRef(T->getPointeeType(), Record);
349   Code = TYPE_OBJC_OBJECT_POINTER;
350 }
351 
352 namespace {
353 
354 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
355   ASTWriter &Writer;
356   ASTWriter::RecordDataImpl &Record;
357 
358 public:
359   TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
360     : Writer(Writer), Record(Record) { }
361 
362 #define ABSTRACT_TYPELOC(CLASS, PARENT)
363 #define TYPELOC(CLASS, PARENT) \
364     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
365 #include "clang/AST/TypeLocNodes.def"
366 
367   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
368   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
369 };
370 
371 }
372 
373 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
374   // nothing to do
375 }
376 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
377   Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
378   if (TL.needsExtraLocalData()) {
379     Record.push_back(TL.getWrittenTypeSpec());
380     Record.push_back(TL.getWrittenSignSpec());
381     Record.push_back(TL.getWrittenWidthSpec());
382     Record.push_back(TL.hasModeAttr());
383   }
384 }
385 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
386   Writer.AddSourceLocation(TL.getNameLoc(), Record);
387 }
388 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
389   Writer.AddSourceLocation(TL.getStarLoc(), Record);
390 }
391 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
392   Writer.AddSourceLocation(TL.getCaretLoc(), Record);
393 }
394 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
395   Writer.AddSourceLocation(TL.getAmpLoc(), Record);
396 }
397 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
398   Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
399 }
400 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
401   Writer.AddSourceLocation(TL.getStarLoc(), Record);
402 }
403 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
404   Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
405   Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
406   Record.push_back(TL.getSizeExpr() ? 1 : 0);
407   if (TL.getSizeExpr())
408     Writer.AddStmt(TL.getSizeExpr());
409 }
410 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
411   VisitArrayTypeLoc(TL);
412 }
413 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
414   VisitArrayTypeLoc(TL);
415 }
416 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
417   VisitArrayTypeLoc(TL);
418 }
419 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
420                                             DependentSizedArrayTypeLoc TL) {
421   VisitArrayTypeLoc(TL);
422 }
423 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
424                                         DependentSizedExtVectorTypeLoc TL) {
425   Writer.AddSourceLocation(TL.getNameLoc(), Record);
426 }
427 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
428   Writer.AddSourceLocation(TL.getNameLoc(), Record);
429 }
430 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
431   Writer.AddSourceLocation(TL.getNameLoc(), Record);
432 }
433 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
434   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
435   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
436   Record.push_back(TL.getTrailingReturn());
437   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
438     Writer.AddDeclRef(TL.getArg(i), Record);
439 }
440 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
441   VisitFunctionTypeLoc(TL);
442 }
443 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
444   VisitFunctionTypeLoc(TL);
445 }
446 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
447   Writer.AddSourceLocation(TL.getNameLoc(), Record);
448 }
449 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
450   Writer.AddSourceLocation(TL.getNameLoc(), Record);
451 }
452 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
453   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
454   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
455   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
456 }
457 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
458   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
459   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
460   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
461   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
462 }
463 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
464   Writer.AddSourceLocation(TL.getNameLoc(), Record);
465 }
466 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
467   Writer.AddSourceLocation(TL.getNameLoc(), Record);
468 }
469 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
470   Writer.AddSourceLocation(TL.getNameLoc(), Record);
471 }
472 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
473   Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
474   if (TL.hasAttrOperand()) {
475     SourceRange range = TL.getAttrOperandParensRange();
476     Writer.AddSourceLocation(range.getBegin(), Record);
477     Writer.AddSourceLocation(range.getEnd(), Record);
478   }
479   if (TL.hasAttrExprOperand()) {
480     Expr *operand = TL.getAttrExprOperand();
481     Record.push_back(operand ? 1 : 0);
482     if (operand) Writer.AddStmt(operand);
483   } else if (TL.hasAttrEnumOperand()) {
484     Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
485   }
486 }
487 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
488   Writer.AddSourceLocation(TL.getNameLoc(), Record);
489 }
490 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
491                                             SubstTemplateTypeParmTypeLoc TL) {
492   Writer.AddSourceLocation(TL.getNameLoc(), Record);
493 }
494 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
495                                            TemplateSpecializationTypeLoc TL) {
496   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
497   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
498   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
499   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
500     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
501                                       TL.getArgLoc(i).getLocInfo(), Record);
502 }
503 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
504   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
505   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
506 }
507 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
508   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
509   Writer.AddSourceRange(TL.getQualifierRange(), Record);
510 }
511 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
512   Writer.AddSourceLocation(TL.getNameLoc(), Record);
513 }
514 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
515   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
516   Writer.AddSourceRange(TL.getQualifierRange(), Record);
517   Writer.AddSourceLocation(TL.getNameLoc(), Record);
518 }
519 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
520        DependentTemplateSpecializationTypeLoc TL) {
521   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
522   Writer.AddSourceRange(TL.getQualifierRange(), Record);
523   Writer.AddSourceLocation(TL.getNameLoc(), Record);
524   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
525   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
526   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
527     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
528                                       TL.getArgLoc(I).getLocInfo(), Record);
529 }
530 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
531   Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
532 }
533 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
534   Writer.AddSourceLocation(TL.getNameLoc(), Record);
535 }
536 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
537   Record.push_back(TL.hasBaseTypeAsWritten());
538   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
539   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
540   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
541     Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
542 }
543 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
544   Writer.AddSourceLocation(TL.getStarLoc(), Record);
545 }
546 
547 //===----------------------------------------------------------------------===//
548 // ASTWriter Implementation
549 //===----------------------------------------------------------------------===//
550 
551 static void EmitBlockID(unsigned ID, const char *Name,
552                         llvm::BitstreamWriter &Stream,
553                         ASTWriter::RecordDataImpl &Record) {
554   Record.clear();
555   Record.push_back(ID);
556   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
557 
558   // Emit the block name if present.
559   if (Name == 0 || Name[0] == 0) return;
560   Record.clear();
561   while (*Name)
562     Record.push_back(*Name++);
563   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
564 }
565 
566 static void EmitRecordID(unsigned ID, const char *Name,
567                          llvm::BitstreamWriter &Stream,
568                          ASTWriter::RecordDataImpl &Record) {
569   Record.clear();
570   Record.push_back(ID);
571   while (*Name)
572     Record.push_back(*Name++);
573   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
574 }
575 
576 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
577                           ASTWriter::RecordDataImpl &Record) {
578 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
579   RECORD(STMT_STOP);
580   RECORD(STMT_NULL_PTR);
581   RECORD(STMT_NULL);
582   RECORD(STMT_COMPOUND);
583   RECORD(STMT_CASE);
584   RECORD(STMT_DEFAULT);
585   RECORD(STMT_LABEL);
586   RECORD(STMT_IF);
587   RECORD(STMT_SWITCH);
588   RECORD(STMT_WHILE);
589   RECORD(STMT_DO);
590   RECORD(STMT_FOR);
591   RECORD(STMT_GOTO);
592   RECORD(STMT_INDIRECT_GOTO);
593   RECORD(STMT_CONTINUE);
594   RECORD(STMT_BREAK);
595   RECORD(STMT_RETURN);
596   RECORD(STMT_DECL);
597   RECORD(STMT_ASM);
598   RECORD(EXPR_PREDEFINED);
599   RECORD(EXPR_DECL_REF);
600   RECORD(EXPR_INTEGER_LITERAL);
601   RECORD(EXPR_FLOATING_LITERAL);
602   RECORD(EXPR_IMAGINARY_LITERAL);
603   RECORD(EXPR_STRING_LITERAL);
604   RECORD(EXPR_CHARACTER_LITERAL);
605   RECORD(EXPR_PAREN);
606   RECORD(EXPR_UNARY_OPERATOR);
607   RECORD(EXPR_SIZEOF_ALIGN_OF);
608   RECORD(EXPR_ARRAY_SUBSCRIPT);
609   RECORD(EXPR_CALL);
610   RECORD(EXPR_MEMBER);
611   RECORD(EXPR_BINARY_OPERATOR);
612   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
613   RECORD(EXPR_CONDITIONAL_OPERATOR);
614   RECORD(EXPR_IMPLICIT_CAST);
615   RECORD(EXPR_CSTYLE_CAST);
616   RECORD(EXPR_COMPOUND_LITERAL);
617   RECORD(EXPR_EXT_VECTOR_ELEMENT);
618   RECORD(EXPR_INIT_LIST);
619   RECORD(EXPR_DESIGNATED_INIT);
620   RECORD(EXPR_IMPLICIT_VALUE_INIT);
621   RECORD(EXPR_VA_ARG);
622   RECORD(EXPR_ADDR_LABEL);
623   RECORD(EXPR_STMT);
624   RECORD(EXPR_CHOOSE);
625   RECORD(EXPR_GNU_NULL);
626   RECORD(EXPR_SHUFFLE_VECTOR);
627   RECORD(EXPR_BLOCK);
628   RECORD(EXPR_BLOCK_DECL_REF);
629   RECORD(EXPR_OBJC_STRING_LITERAL);
630   RECORD(EXPR_OBJC_ENCODE);
631   RECORD(EXPR_OBJC_SELECTOR_EXPR);
632   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
633   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
634   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
635   RECORD(EXPR_OBJC_KVC_REF_EXPR);
636   RECORD(EXPR_OBJC_MESSAGE_EXPR);
637   RECORD(STMT_OBJC_FOR_COLLECTION);
638   RECORD(STMT_OBJC_CATCH);
639   RECORD(STMT_OBJC_FINALLY);
640   RECORD(STMT_OBJC_AT_TRY);
641   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
642   RECORD(STMT_OBJC_AT_THROW);
643   RECORD(EXPR_CXX_OPERATOR_CALL);
644   RECORD(EXPR_CXX_CONSTRUCT);
645   RECORD(EXPR_CXX_STATIC_CAST);
646   RECORD(EXPR_CXX_DYNAMIC_CAST);
647   RECORD(EXPR_CXX_REINTERPRET_CAST);
648   RECORD(EXPR_CXX_CONST_CAST);
649   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
650   RECORD(EXPR_CXX_BOOL_LITERAL);
651   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
652 #undef RECORD
653 }
654 
655 void ASTWriter::WriteBlockInfoBlock() {
656   RecordData Record;
657   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
658 
659 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
660 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
661 
662   // AST Top-Level Block.
663   BLOCK(AST_BLOCK);
664   RECORD(ORIGINAL_FILE_NAME);
665   RECORD(TYPE_OFFSET);
666   RECORD(DECL_OFFSET);
667   RECORD(LANGUAGE_OPTIONS);
668   RECORD(METADATA);
669   RECORD(IDENTIFIER_OFFSET);
670   RECORD(IDENTIFIER_TABLE);
671   RECORD(EXTERNAL_DEFINITIONS);
672   RECORD(SPECIAL_TYPES);
673   RECORD(STATISTICS);
674   RECORD(TENTATIVE_DEFINITIONS);
675   RECORD(UNUSED_FILESCOPED_DECLS);
676   RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
677   RECORD(SELECTOR_OFFSETS);
678   RECORD(METHOD_POOL);
679   RECORD(PP_COUNTER_VALUE);
680   RECORD(SOURCE_LOCATION_OFFSETS);
681   RECORD(SOURCE_LOCATION_PRELOADS);
682   RECORD(STAT_CACHE);
683   RECORD(EXT_VECTOR_DECLS);
684   RECORD(VERSION_CONTROL_BRANCH_REVISION);
685   RECORD(MACRO_DEFINITION_OFFSETS);
686   RECORD(CHAINED_METADATA);
687   RECORD(REFERENCED_SELECTOR_POOL);
688 
689   // SourceManager Block.
690   BLOCK(SOURCE_MANAGER_BLOCK);
691   RECORD(SM_SLOC_FILE_ENTRY);
692   RECORD(SM_SLOC_BUFFER_ENTRY);
693   RECORD(SM_SLOC_BUFFER_BLOB);
694   RECORD(SM_SLOC_INSTANTIATION_ENTRY);
695   RECORD(SM_LINE_TABLE);
696 
697   // Preprocessor Block.
698   BLOCK(PREPROCESSOR_BLOCK);
699   RECORD(PP_MACRO_OBJECT_LIKE);
700   RECORD(PP_MACRO_FUNCTION_LIKE);
701   RECORD(PP_TOKEN);
702   RECORD(PP_MACRO_INSTANTIATION);
703   RECORD(PP_MACRO_DEFINITION);
704 
705   // Decls and Types block.
706   BLOCK(DECLTYPES_BLOCK);
707   RECORD(TYPE_EXT_QUAL);
708   RECORD(TYPE_COMPLEX);
709   RECORD(TYPE_POINTER);
710   RECORD(TYPE_BLOCK_POINTER);
711   RECORD(TYPE_LVALUE_REFERENCE);
712   RECORD(TYPE_RVALUE_REFERENCE);
713   RECORD(TYPE_MEMBER_POINTER);
714   RECORD(TYPE_CONSTANT_ARRAY);
715   RECORD(TYPE_INCOMPLETE_ARRAY);
716   RECORD(TYPE_VARIABLE_ARRAY);
717   RECORD(TYPE_VECTOR);
718   RECORD(TYPE_EXT_VECTOR);
719   RECORD(TYPE_FUNCTION_PROTO);
720   RECORD(TYPE_FUNCTION_NO_PROTO);
721   RECORD(TYPE_TYPEDEF);
722   RECORD(TYPE_TYPEOF_EXPR);
723   RECORD(TYPE_TYPEOF);
724   RECORD(TYPE_RECORD);
725   RECORD(TYPE_ENUM);
726   RECORD(TYPE_OBJC_INTERFACE);
727   RECORD(TYPE_OBJC_OBJECT);
728   RECORD(TYPE_OBJC_OBJECT_POINTER);
729   RECORD(DECL_TRANSLATION_UNIT);
730   RECORD(DECL_TYPEDEF);
731   RECORD(DECL_ENUM);
732   RECORD(DECL_RECORD);
733   RECORD(DECL_ENUM_CONSTANT);
734   RECORD(DECL_FUNCTION);
735   RECORD(DECL_OBJC_METHOD);
736   RECORD(DECL_OBJC_INTERFACE);
737   RECORD(DECL_OBJC_PROTOCOL);
738   RECORD(DECL_OBJC_IVAR);
739   RECORD(DECL_OBJC_AT_DEFS_FIELD);
740   RECORD(DECL_OBJC_CLASS);
741   RECORD(DECL_OBJC_FORWARD_PROTOCOL);
742   RECORD(DECL_OBJC_CATEGORY);
743   RECORD(DECL_OBJC_CATEGORY_IMPL);
744   RECORD(DECL_OBJC_IMPLEMENTATION);
745   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
746   RECORD(DECL_OBJC_PROPERTY);
747   RECORD(DECL_OBJC_PROPERTY_IMPL);
748   RECORD(DECL_FIELD);
749   RECORD(DECL_VAR);
750   RECORD(DECL_IMPLICIT_PARAM);
751   RECORD(DECL_PARM_VAR);
752   RECORD(DECL_FILE_SCOPE_ASM);
753   RECORD(DECL_BLOCK);
754   RECORD(DECL_CONTEXT_LEXICAL);
755   RECORD(DECL_CONTEXT_VISIBLE);
756   // Statements and Exprs can occur in the Decls and Types block.
757   AddStmtsExprs(Stream, Record);
758 #undef RECORD
759 #undef BLOCK
760   Stream.ExitBlock();
761 }
762 
763 /// \brief Adjusts the given filename to only write out the portion of the
764 /// filename that is not part of the system root directory.
765 ///
766 /// \param Filename the file name to adjust.
767 ///
768 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
769 /// the returned filename will be adjusted by this system root.
770 ///
771 /// \returns either the original filename (if it needs no adjustment) or the
772 /// adjusted filename (which points into the @p Filename parameter).
773 static const char *
774 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
775   assert(Filename && "No file name to adjust?");
776 
777   if (!isysroot)
778     return Filename;
779 
780   // Verify that the filename and the system root have the same prefix.
781   unsigned Pos = 0;
782   for (; Filename[Pos] && isysroot[Pos]; ++Pos)
783     if (Filename[Pos] != isysroot[Pos])
784       return Filename; // Prefixes don't match.
785 
786   // We hit the end of the filename before we hit the end of the system root.
787   if (!Filename[Pos])
788     return Filename;
789 
790   // If the file name has a '/' at the current position, skip over the '/'.
791   // We distinguish sysroot-based includes from absolute includes by the
792   // absence of '/' at the beginning of sysroot-based includes.
793   if (Filename[Pos] == '/')
794     ++Pos;
795 
796   return Filename + Pos;
797 }
798 
799 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
800 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
801   using namespace llvm;
802 
803   // Metadata
804   const TargetInfo &Target = Context.Target;
805   BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
806   MetaAbbrev->Add(BitCodeAbbrevOp(
807                     Chain ? CHAINED_METADATA : METADATA));
808   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
809   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
810   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
811   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
812   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
813   // Target triple or chained PCH name
814   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
815   unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
816 
817   RecordData Record;
818   Record.push_back(Chain ? CHAINED_METADATA : METADATA);
819   Record.push_back(VERSION_MAJOR);
820   Record.push_back(VERSION_MINOR);
821   Record.push_back(CLANG_VERSION_MAJOR);
822   Record.push_back(CLANG_VERSION_MINOR);
823   Record.push_back(isysroot != 0);
824   // FIXME: This writes the absolute path for chained headers.
825   const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
826   Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
827 
828   // Original file name
829   SourceManager &SM = Context.getSourceManager();
830   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
831     BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
832     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
833     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
834     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
835 
836     llvm::SmallString<128> MainFilePath(MainFile->getName());
837 
838     llvm::sys::fs::make_absolute(MainFilePath);
839 
840     const char *MainFileNameStr = MainFilePath.c_str();
841     MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
842                                                       isysroot);
843     RecordData Record;
844     Record.push_back(ORIGINAL_FILE_NAME);
845     Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
846   }
847 
848   // Repository branch/version information.
849   BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
850   RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
851   RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
852   unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
853   Record.clear();
854   Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
855   Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
856                             getClangFullRepositoryVersion());
857 }
858 
859 /// \brief Write the LangOptions structure.
860 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
861   RecordData Record;
862   Record.push_back(LangOpts.Trigraphs);
863   Record.push_back(LangOpts.BCPLComment);  // BCPL-style '//' comments.
864   Record.push_back(LangOpts.DollarIdents);  // '$' allowed in identifiers.
865   Record.push_back(LangOpts.AsmPreprocessor);  // Preprocessor in asm mode.
866   Record.push_back(LangOpts.GNUMode);  // True in gnu99 mode false in c99 mode (etc)
867   Record.push_back(LangOpts.GNUKeywords);  // Allow GNU-extension keywords
868   Record.push_back(LangOpts.ImplicitInt);  // C89 implicit 'int'.
869   Record.push_back(LangOpts.Digraphs);  // C94, C99 and C++
870   Record.push_back(LangOpts.HexFloats);  // C99 Hexadecimal float constants.
871   Record.push_back(LangOpts.C99);  // C99 Support
872   Record.push_back(LangOpts.Microsoft);  // Microsoft extensions.
873   // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
874   // already saved elsewhere.
875   Record.push_back(LangOpts.CPlusPlus);  // C++ Support
876   Record.push_back(LangOpts.CPlusPlus0x);  // C++0x Support
877   Record.push_back(LangOpts.CXXOperatorNames);  // Treat C++ operator names as keywords.
878 
879   Record.push_back(LangOpts.ObjC1);  // Objective-C 1 support enabled.
880   Record.push_back(LangOpts.ObjC2);  // Objective-C 2 support enabled.
881   Record.push_back(LangOpts.ObjCNonFragileABI);  // Objective-C
882                                                  // modern abi enabled.
883   Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
884                                                  // modern abi enabled.
885   Record.push_back(LangOpts.AppleKext);          // Apple's kernel extensions ABI
886   Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
887                                                       // properties enabled.
888   Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
889 
890   Record.push_back(LangOpts.PascalStrings);  // Allow Pascal strings
891   Record.push_back(LangOpts.WritableStrings);  // Allow writable strings
892   Record.push_back(LangOpts.LaxVectorConversions);
893   Record.push_back(LangOpts.AltiVec);
894   Record.push_back(LangOpts.Exceptions);  // Support exception handling.
895   Record.push_back(LangOpts.SjLjExceptions);
896 
897   Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
898   Record.push_back(LangOpts.Freestanding); // Freestanding implementation
899   Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
900 
901   // Whether static initializers are protected by locks.
902   Record.push_back(LangOpts.ThreadsafeStatics);
903   Record.push_back(LangOpts.POSIXThreads);
904   Record.push_back(LangOpts.Blocks); // block extension to C
905   Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
906                                   // they are unused.
907   Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
908                                   // (modulo the platform support).
909 
910   Record.push_back(LangOpts.getSignedOverflowBehavior());
911   Record.push_back(LangOpts.HeinousExtensions);
912 
913   Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
914   Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
915                                   // defined.
916   Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
917                                   // opposed to __DYNAMIC__).
918   Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
919 
920   Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
921                                   // used (instead of C99 semantics).
922   Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
923   Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
924                                             // be enabled.
925   Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
926                                            // unsigned type
927   Record.push_back(LangOpts.ShortWChar);  // force wchar_t to be unsigned short
928   Record.push_back(LangOpts.getGCMode());
929   Record.push_back(LangOpts.getVisibilityMode());
930   Record.push_back(LangOpts.getStackProtectorMode());
931   Record.push_back(LangOpts.InstantiationDepth);
932   Record.push_back(LangOpts.OpenCL);
933   Record.push_back(LangOpts.CUDA);
934   Record.push_back(LangOpts.CatchUndefined);
935   Record.push_back(LangOpts.ElideConstructors);
936   Record.push_back(LangOpts.SpellChecking);
937   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
938 }
939 
940 //===----------------------------------------------------------------------===//
941 // stat cache Serialization
942 //===----------------------------------------------------------------------===//
943 
944 namespace {
945 // Trait used for the on-disk hash table of stat cache results.
946 class ASTStatCacheTrait {
947 public:
948   typedef const char * key_type;
949   typedef key_type key_type_ref;
950 
951   typedef struct stat data_type;
952   typedef const data_type &data_type_ref;
953 
954   static unsigned ComputeHash(const char *path) {
955     return llvm::HashString(path);
956   }
957 
958   std::pair<unsigned,unsigned>
959     EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
960                       data_type_ref Data) {
961     unsigned StrLen = strlen(path);
962     clang::io::Emit16(Out, StrLen);
963     unsigned DataLen = 4 + 4 + 2 + 8 + 8;
964     clang::io::Emit8(Out, DataLen);
965     return std::make_pair(StrLen + 1, DataLen);
966   }
967 
968   void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
969     Out.write(path, KeyLen);
970   }
971 
972   void EmitData(llvm::raw_ostream &Out, key_type_ref,
973                 data_type_ref Data, unsigned DataLen) {
974     using namespace clang::io;
975     uint64_t Start = Out.tell(); (void)Start;
976 
977     Emit32(Out, (uint32_t) Data.st_ino);
978     Emit32(Out, (uint32_t) Data.st_dev);
979     Emit16(Out, (uint16_t) Data.st_mode);
980     Emit64(Out, (uint64_t) Data.st_mtime);
981     Emit64(Out, (uint64_t) Data.st_size);
982 
983     assert(Out.tell() - Start == DataLen && "Wrong data length");
984   }
985 };
986 } // end anonymous namespace
987 
988 /// \brief Write the stat() system call cache to the AST file.
989 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
990   // Build the on-disk hash table containing information about every
991   // stat() call.
992   OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
993   unsigned NumStatEntries = 0;
994   for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
995                                 StatEnd = StatCalls.end();
996        Stat != StatEnd; ++Stat, ++NumStatEntries) {
997     const char *Filename = Stat->first();
998     Generator.insert(Filename, Stat->second);
999   }
1000 
1001   // Create the on-disk hash table in a buffer.
1002   llvm::SmallString<4096> StatCacheData;
1003   uint32_t BucketOffset;
1004   {
1005     llvm::raw_svector_ostream Out(StatCacheData);
1006     // Make sure that no bucket is at offset 0
1007     clang::io::Emit32(Out, 0);
1008     BucketOffset = Generator.Emit(Out);
1009   }
1010 
1011   // Create a blob abbreviation
1012   using namespace llvm;
1013   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1014   Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1015   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1016   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1017   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1018   unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1019 
1020   // Write the stat cache
1021   RecordData Record;
1022   Record.push_back(STAT_CACHE);
1023   Record.push_back(BucketOffset);
1024   Record.push_back(NumStatEntries);
1025   Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1026 }
1027 
1028 //===----------------------------------------------------------------------===//
1029 // Source Manager Serialization
1030 //===----------------------------------------------------------------------===//
1031 
1032 /// \brief Create an abbreviation for the SLocEntry that refers to a
1033 /// file.
1034 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1035   using namespace llvm;
1036   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1037   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1038   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1039   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1040   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1041   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1042   // FileEntry fields.
1043   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1044   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1045   // HeaderFileInfo fields.
1046   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImport
1047   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // DirInfo
1048   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumIncludes
1049   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // ControllingMacro
1050   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1051   return Stream.EmitAbbrev(Abbrev);
1052 }
1053 
1054 /// \brief Create an abbreviation for the SLocEntry that refers to a
1055 /// buffer.
1056 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1057   using namespace llvm;
1058   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1059   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1060   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1061   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1062   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1063   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1064   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1065   return Stream.EmitAbbrev(Abbrev);
1066 }
1067 
1068 /// \brief Create an abbreviation for the SLocEntry that refers to a
1069 /// buffer's blob.
1070 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1071   using namespace llvm;
1072   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1073   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1074   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1075   return Stream.EmitAbbrev(Abbrev);
1076 }
1077 
1078 /// \brief Create an abbreviation for the SLocEntry that refers to an
1079 /// buffer.
1080 static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
1081   using namespace llvm;
1082   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1083   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY));
1084   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1085   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1086   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1087   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1088   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1089   return Stream.EmitAbbrev(Abbrev);
1090 }
1091 
1092 /// \brief Writes the block containing the serialized form of the
1093 /// source manager.
1094 ///
1095 /// TODO: We should probably use an on-disk hash table (stored in a
1096 /// blob), indexed based on the file name, so that we only create
1097 /// entries for files that we actually need. In the common case (no
1098 /// errors), we probably won't have to create file entries for any of
1099 /// the files in the AST.
1100 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1101                                         const Preprocessor &PP,
1102                                         const char *isysroot) {
1103   RecordData Record;
1104 
1105   // Enter the source manager block.
1106   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1107 
1108   // Abbreviations for the various kinds of source-location entries.
1109   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1110   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1111   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1112   unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
1113 
1114   // Write the line table.
1115   if (SourceMgr.hasLineTable()) {
1116     LineTableInfo &LineTable = SourceMgr.getLineTable();
1117 
1118     // Emit the file names
1119     Record.push_back(LineTable.getNumFilenames());
1120     for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1121       // Emit the file name
1122       const char *Filename = LineTable.getFilename(I);
1123       Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1124       unsigned FilenameLen = Filename? strlen(Filename) : 0;
1125       Record.push_back(FilenameLen);
1126       if (FilenameLen)
1127         Record.insert(Record.end(), Filename, Filename + FilenameLen);
1128     }
1129 
1130     // Emit the line entries
1131     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1132          L != LEnd; ++L) {
1133       // Emit the file ID
1134       Record.push_back(L->first);
1135 
1136       // Emit the line entries
1137       Record.push_back(L->second.size());
1138       for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1139                                          LEEnd = L->second.end();
1140            LE != LEEnd; ++LE) {
1141         Record.push_back(LE->FileOffset);
1142         Record.push_back(LE->LineNo);
1143         Record.push_back(LE->FilenameID);
1144         Record.push_back((unsigned)LE->FileKind);
1145         Record.push_back(LE->IncludeOffset);
1146       }
1147     }
1148     Stream.EmitRecord(SM_LINE_TABLE, Record);
1149   }
1150 
1151   // Write out the source location entry table. We skip the first
1152   // entry, which is always the same dummy entry.
1153   std::vector<uint32_t> SLocEntryOffsets;
1154   RecordData PreloadSLocs;
1155   unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1156   SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1157   for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1158        I != N; ++I) {
1159     // Get this source location entry.
1160     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1161 
1162     // Record the offset of this source-location entry.
1163     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1164 
1165     // Figure out which record code to use.
1166     unsigned Code;
1167     if (SLoc->isFile()) {
1168       if (SLoc->getFile().getContentCache()->Entry)
1169         Code = SM_SLOC_FILE_ENTRY;
1170       else
1171         Code = SM_SLOC_BUFFER_ENTRY;
1172     } else
1173       Code = SM_SLOC_INSTANTIATION_ENTRY;
1174     Record.clear();
1175     Record.push_back(Code);
1176 
1177     Record.push_back(SLoc->getOffset());
1178     if (SLoc->isFile()) {
1179       const SrcMgr::FileInfo &File = SLoc->getFile();
1180       Record.push_back(File.getIncludeLoc().getRawEncoding());
1181       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1182       Record.push_back(File.hasLineDirectives());
1183 
1184       const SrcMgr::ContentCache *Content = File.getContentCache();
1185       if (Content->Entry) {
1186         // The source location entry is a file. The blob associated
1187         // with this entry is the file name.
1188 
1189         // Emit size/modification time for this file.
1190         Record.push_back(Content->Entry->getSize());
1191         Record.push_back(Content->Entry->getModificationTime());
1192 
1193         // Emit header-search information associated with this file.
1194         HeaderFileInfo HFI;
1195         HeaderSearch &HS = PP.getHeaderSearchInfo();
1196         if (Content->Entry->getUID() < HS.header_file_size())
1197           HFI = HS.header_file_begin()[Content->Entry->getUID()];
1198         Record.push_back(HFI.isImport);
1199         Record.push_back(HFI.DirInfo);
1200         Record.push_back(HFI.NumIncludes);
1201         AddIdentifierRef(HFI.ControllingMacro, Record);
1202 
1203         // Turn the file name into an absolute path, if it isn't already.
1204         const char *Filename = Content->Entry->getName();
1205         llvm::SmallString<128> FilePath(Filename);
1206         llvm::sys::fs::make_absolute(FilePath);
1207         Filename = FilePath.c_str();
1208 
1209         Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1210         Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1211 
1212         // FIXME: For now, preload all file source locations, so that
1213         // we get the appropriate File entries in the reader. This is
1214         // a temporary measure.
1215         PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1216       } else {
1217         // The source location entry is a buffer. The blob associated
1218         // with this entry contains the contents of the buffer.
1219 
1220         // We add one to the size so that we capture the trailing NULL
1221         // that is required by llvm::MemoryBuffer::getMemBuffer (on
1222         // the reader side).
1223         const llvm::MemoryBuffer *Buffer
1224           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1225         const char *Name = Buffer->getBufferIdentifier();
1226         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1227                                   llvm::StringRef(Name, strlen(Name) + 1));
1228         Record.clear();
1229         Record.push_back(SM_SLOC_BUFFER_BLOB);
1230         Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1231                                   llvm::StringRef(Buffer->getBufferStart(),
1232                                                   Buffer->getBufferSize() + 1));
1233 
1234         if (strcmp(Name, "<built-in>") == 0)
1235           PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1236       }
1237     } else {
1238       // The source location entry is an instantiation.
1239       const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1240       Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1241       Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1242       Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1243 
1244       // Compute the token length for this macro expansion.
1245       unsigned NextOffset = SourceMgr.getNextOffset();
1246       if (I + 1 != N)
1247         NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1248       Record.push_back(NextOffset - SLoc->getOffset() - 1);
1249       Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1250     }
1251   }
1252 
1253   Stream.ExitBlock();
1254 
1255   if (SLocEntryOffsets.empty())
1256     return;
1257 
1258   // Write the source-location offsets table into the AST block. This
1259   // table is used for lazily loading source-location information.
1260   using namespace llvm;
1261   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1262   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1263   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1264   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1265   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1266   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1267 
1268   Record.clear();
1269   Record.push_back(SOURCE_LOCATION_OFFSETS);
1270   Record.push_back(SLocEntryOffsets.size());
1271   unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1272   Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1273   Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1274                             (const char *)data(SLocEntryOffsets),
1275                            SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
1276 
1277   // Write the source location entry preloads array, telling the AST
1278   // reader which source locations entries it should load eagerly.
1279   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1280 }
1281 
1282 //===----------------------------------------------------------------------===//
1283 // Preprocessor Serialization
1284 //===----------------------------------------------------------------------===//
1285 
1286 /// \brief Writes the block containing the serialized form of the
1287 /// preprocessor.
1288 ///
1289 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1290   RecordData Record;
1291 
1292   // If the preprocessor __COUNTER__ value has been bumped, remember it.
1293   if (PP.getCounterValue() != 0) {
1294     Record.push_back(PP.getCounterValue());
1295     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1296     Record.clear();
1297   }
1298 
1299   // Enter the preprocessor block.
1300   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1301 
1302   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1303   // FIXME: use diagnostics subsystem for localization etc.
1304   if (PP.SawDateOrTime())
1305     fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1306 
1307 
1308   // Loop over all the macro definitions that are live at the end of the file,
1309   // emitting each to the PP section.
1310   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1311   unsigned InclusionAbbrev = 0;
1312   if (PPRec) {
1313     using namespace llvm;
1314     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1315     Abbrev->Add(BitCodeAbbrevOp(PP_INCLUSION_DIRECTIVE));
1316     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1317     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1318     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1319     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1320     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1321     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1322     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1323     InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1324   }
1325 
1326   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1327        I != E; ++I) {
1328     // FIXME: This emits macros in hash table order, we should do it in a stable
1329     // order so that output is reproducible.
1330     MacroInfo *MI = I->second;
1331 
1332     // Don't emit builtin macros like __LINE__ to the AST file unless they have
1333     // been redefined by the header (in which case they are not isBuiltinMacro).
1334     // Also skip macros from a AST file if we're chaining.
1335 
1336     // FIXME: There is a (probably minor) optimization we could do here, if
1337     // the macro comes from the original PCH but the identifier comes from a
1338     // chained PCH, by storing the offset into the original PCH rather than
1339     // writing the macro definition a second time.
1340     if (MI->isBuiltinMacro() ||
1341         (Chain && I->first->isFromAST() && MI->isFromAST()))
1342       continue;
1343 
1344     AddIdentifierRef(I->first, Record);
1345     MacroOffsets[I->first] = Stream.GetCurrentBitNo();
1346     Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1347     Record.push_back(MI->isUsed());
1348 
1349     unsigned Code;
1350     if (MI->isObjectLike()) {
1351       Code = PP_MACRO_OBJECT_LIKE;
1352     } else {
1353       Code = PP_MACRO_FUNCTION_LIKE;
1354 
1355       Record.push_back(MI->isC99Varargs());
1356       Record.push_back(MI->isGNUVarargs());
1357       Record.push_back(MI->getNumArgs());
1358       for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1359            I != E; ++I)
1360         AddIdentifierRef(*I, Record);
1361     }
1362 
1363     // If we have a detailed preprocessing record, record the macro definition
1364     // ID that corresponds to this macro.
1365     if (PPRec)
1366       Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1367 
1368     Stream.EmitRecord(Code, Record);
1369     Record.clear();
1370 
1371     // Emit the tokens array.
1372     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1373       // Note that we know that the preprocessor does not have any annotation
1374       // tokens in it because they are created by the parser, and thus can't be
1375       // in a macro definition.
1376       const Token &Tok = MI->getReplacementToken(TokNo);
1377 
1378       Record.push_back(Tok.getLocation().getRawEncoding());
1379       Record.push_back(Tok.getLength());
1380 
1381       // FIXME: When reading literal tokens, reconstruct the literal pointer if
1382       // it is needed.
1383       AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1384 
1385       // FIXME: Should translate token kind to a stable encoding.
1386       Record.push_back(Tok.getKind());
1387       // FIXME: Should translate token flags to a stable encoding.
1388       Record.push_back(Tok.getFlags());
1389 
1390       Stream.EmitRecord(PP_TOKEN, Record);
1391       Record.clear();
1392     }
1393     ++NumMacros;
1394   }
1395 
1396   // If the preprocessor has a preprocessing record, emit it.
1397   unsigned NumPreprocessingRecords = 0;
1398   if (PPRec) {
1399     unsigned IndexBase = Chain ? PPRec->getNumPreallocatedEntities() : 0;
1400     for (PreprocessingRecord::iterator E = PPRec->begin(Chain),
1401                                        EEnd = PPRec->end(Chain);
1402          E != EEnd; ++E) {
1403       Record.clear();
1404 
1405       if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1406         // Record this macro definition's location.
1407         MacroID ID = getMacroDefinitionID(MD);
1408 
1409         // Don't write the macro definition if it is from another AST file.
1410         if (ID < FirstMacroID)
1411           continue;
1412 
1413         // Notify the serialization listener that we're serializing this entity.
1414         if (SerializationListener)
1415           SerializationListener->SerializedPreprocessedEntity(*E,
1416                                                       Stream.GetCurrentBitNo());
1417 
1418         unsigned Position = ID - FirstMacroID;
1419         if (Position != MacroDefinitionOffsets.size()) {
1420           if (Position > MacroDefinitionOffsets.size())
1421             MacroDefinitionOffsets.resize(Position + 1);
1422 
1423           MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1424         } else
1425           MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1426 
1427         Record.push_back(IndexBase + NumPreprocessingRecords++);
1428         Record.push_back(ID);
1429         AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1430         AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1431         AddIdentifierRef(MD->getName(), Record);
1432         AddSourceLocation(MD->getLocation(), Record);
1433         Stream.EmitRecord(PP_MACRO_DEFINITION, Record);
1434         continue;
1435       }
1436 
1437       // Notify the serialization listener that we're serializing this entity.
1438       if (SerializationListener)
1439         SerializationListener->SerializedPreprocessedEntity(*E,
1440                                                       Stream.GetCurrentBitNo());
1441 
1442       if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
1443         Record.push_back(IndexBase + NumPreprocessingRecords++);
1444         AddSourceLocation(MI->getSourceRange().getBegin(), Record);
1445         AddSourceLocation(MI->getSourceRange().getEnd(), Record);
1446         AddIdentifierRef(MI->getName(), Record);
1447         Record.push_back(getMacroDefinitionID(MI->getDefinition()));
1448         Stream.EmitRecord(PP_MACRO_INSTANTIATION, Record);
1449         continue;
1450       }
1451 
1452       if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1453         Record.push_back(PP_INCLUSION_DIRECTIVE);
1454         Record.push_back(IndexBase + NumPreprocessingRecords++);
1455         AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1456         AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1457         Record.push_back(ID->getFileName().size());
1458         Record.push_back(ID->wasInQuotes());
1459         Record.push_back(static_cast<unsigned>(ID->getKind()));
1460         llvm::SmallString<64> Buffer;
1461         Buffer += ID->getFileName();
1462         Buffer += ID->getFile()->getName();
1463         Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1464         continue;
1465       }
1466 
1467       llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1468     }
1469   }
1470 
1471   Stream.ExitBlock();
1472 
1473   // Write the offsets table for the preprocessing record.
1474   if (NumPreprocessingRecords > 0) {
1475     // Write the offsets table for identifier IDs.
1476     using namespace llvm;
1477     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1478     Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1479     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1480     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1481     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1482     unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1483 
1484     Record.clear();
1485     Record.push_back(MACRO_DEFINITION_OFFSETS);
1486     Record.push_back(NumPreprocessingRecords);
1487     Record.push_back(MacroDefinitionOffsets.size());
1488     Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1489                               (const char *)data(MacroDefinitionOffsets),
1490                               MacroDefinitionOffsets.size() * sizeof(uint32_t));
1491   }
1492 }
1493 
1494 void ASTWriter::WriteUserDiagnosticMappings(const Diagnostic &Diag) {
1495   RecordData Record;
1496   for (unsigned i = 0; i != diag::DIAG_UPPER_LIMIT; ++i) {
1497     diag::Mapping Map = Diag.getDiagnosticMappingInfo(i,Diag.GetCurDiagState());
1498     if (Map & 0x8) { // user mapping.
1499       Record.push_back(i);
1500       Record.push_back(Map & 0x7);
1501     }
1502   }
1503 
1504   if (!Record.empty())
1505     Stream.EmitRecord(DIAG_USER_MAPPINGS, Record);
1506 }
1507 
1508 //===----------------------------------------------------------------------===//
1509 // Type Serialization
1510 //===----------------------------------------------------------------------===//
1511 
1512 /// \brief Write the representation of a type to the AST stream.
1513 void ASTWriter::WriteType(QualType T) {
1514   TypeIdx &Idx = TypeIdxs[T];
1515   if (Idx.getIndex() == 0) // we haven't seen this type before.
1516     Idx = TypeIdx(NextTypeID++);
1517 
1518   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1519 
1520   // Record the offset for this type.
1521   unsigned Index = Idx.getIndex() - FirstTypeID;
1522   if (TypeOffsets.size() == Index)
1523     TypeOffsets.push_back(Stream.GetCurrentBitNo());
1524   else if (TypeOffsets.size() < Index) {
1525     TypeOffsets.resize(Index + 1);
1526     TypeOffsets[Index] = Stream.GetCurrentBitNo();
1527   }
1528 
1529   RecordData Record;
1530 
1531   // Emit the type's representation.
1532   ASTTypeWriter W(*this, Record);
1533 
1534   if (T.hasLocalNonFastQualifiers()) {
1535     Qualifiers Qs = T.getLocalQualifiers();
1536     AddTypeRef(T.getLocalUnqualifiedType(), Record);
1537     Record.push_back(Qs.getAsOpaqueValue());
1538     W.Code = TYPE_EXT_QUAL;
1539   } else {
1540     switch (T->getTypeClass()) {
1541       // For all of the concrete, non-dependent types, call the
1542       // appropriate visitor function.
1543 #define TYPE(Class, Base) \
1544     case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1545 #define ABSTRACT_TYPE(Class, Base)
1546 #include "clang/AST/TypeNodes.def"
1547     }
1548   }
1549 
1550   // Emit the serialized record.
1551   Stream.EmitRecord(W.Code, Record);
1552 
1553   // Flush any expressions that were written as part of this type.
1554   FlushStmts();
1555 }
1556 
1557 //===----------------------------------------------------------------------===//
1558 // Declaration Serialization
1559 //===----------------------------------------------------------------------===//
1560 
1561 /// \brief Write the block containing all of the declaration IDs
1562 /// lexically declared within the given DeclContext.
1563 ///
1564 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1565 /// bistream, or 0 if no block was written.
1566 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1567                                                  DeclContext *DC) {
1568   if (DC->decls_empty())
1569     return 0;
1570 
1571   uint64_t Offset = Stream.GetCurrentBitNo();
1572   RecordData Record;
1573   Record.push_back(DECL_CONTEXT_LEXICAL);
1574   llvm::SmallVector<KindDeclIDPair, 64> Decls;
1575   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1576          D != DEnd; ++D)
1577     Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1578 
1579   ++NumLexicalDeclContexts;
1580   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
1581                             reinterpret_cast<char*>(Decls.data()),
1582                             Decls.size() * sizeof(KindDeclIDPair));
1583   return Offset;
1584 }
1585 
1586 void ASTWriter::WriteTypeDeclOffsets() {
1587   using namespace llvm;
1588   RecordData Record;
1589 
1590   // Write the type offsets array
1591   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1592   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1593   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1594   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1595   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1596   Record.clear();
1597   Record.push_back(TYPE_OFFSET);
1598   Record.push_back(TypeOffsets.size());
1599   Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1600                             (const char *)data(TypeOffsets),
1601                             TypeOffsets.size() * sizeof(TypeOffsets[0]));
1602 
1603   // Write the declaration offsets array
1604   Abbrev = new BitCodeAbbrev();
1605   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1606   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1607   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1608   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1609   Record.clear();
1610   Record.push_back(DECL_OFFSET);
1611   Record.push_back(DeclOffsets.size());
1612   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1613                             (const char *)data(DeclOffsets),
1614                             DeclOffsets.size() * sizeof(DeclOffsets[0]));
1615 }
1616 
1617 //===----------------------------------------------------------------------===//
1618 // Global Method Pool and Selector Serialization
1619 //===----------------------------------------------------------------------===//
1620 
1621 namespace {
1622 // Trait used for the on-disk hash table used in the method pool.
1623 class ASTMethodPoolTrait {
1624   ASTWriter &Writer;
1625 
1626 public:
1627   typedef Selector key_type;
1628   typedef key_type key_type_ref;
1629 
1630   struct data_type {
1631     SelectorID ID;
1632     ObjCMethodList Instance, Factory;
1633   };
1634   typedef const data_type& data_type_ref;
1635 
1636   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
1637 
1638   static unsigned ComputeHash(Selector Sel) {
1639     return serialization::ComputeHash(Sel);
1640   }
1641 
1642   std::pair<unsigned,unsigned>
1643     EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1644                       data_type_ref Methods) {
1645     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1646     clang::io::Emit16(Out, KeyLen);
1647     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
1648     for (const ObjCMethodList *Method = &Methods.Instance; Method;
1649          Method = Method->Next)
1650       if (Method->Method)
1651         DataLen += 4;
1652     for (const ObjCMethodList *Method = &Methods.Factory; Method;
1653          Method = Method->Next)
1654       if (Method->Method)
1655         DataLen += 4;
1656     clang::io::Emit16(Out, DataLen);
1657     return std::make_pair(KeyLen, DataLen);
1658   }
1659 
1660   void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1661     uint64_t Start = Out.tell();
1662     assert((Start >> 32) == 0 && "Selector key offset too large");
1663     Writer.SetSelectorOffset(Sel, Start);
1664     unsigned N = Sel.getNumArgs();
1665     clang::io::Emit16(Out, N);
1666     if (N == 0)
1667       N = 1;
1668     for (unsigned I = 0; I != N; ++I)
1669       clang::io::Emit32(Out,
1670                     Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1671   }
1672 
1673   void EmitData(llvm::raw_ostream& Out, key_type_ref,
1674                 data_type_ref Methods, unsigned DataLen) {
1675     uint64_t Start = Out.tell(); (void)Start;
1676     clang::io::Emit32(Out, Methods.ID);
1677     unsigned NumInstanceMethods = 0;
1678     for (const ObjCMethodList *Method = &Methods.Instance; Method;
1679          Method = Method->Next)
1680       if (Method->Method)
1681         ++NumInstanceMethods;
1682 
1683     unsigned NumFactoryMethods = 0;
1684     for (const ObjCMethodList *Method = &Methods.Factory; Method;
1685          Method = Method->Next)
1686       if (Method->Method)
1687         ++NumFactoryMethods;
1688 
1689     clang::io::Emit16(Out, NumInstanceMethods);
1690     clang::io::Emit16(Out, NumFactoryMethods);
1691     for (const ObjCMethodList *Method = &Methods.Instance; Method;
1692          Method = Method->Next)
1693       if (Method->Method)
1694         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1695     for (const ObjCMethodList *Method = &Methods.Factory; Method;
1696          Method = Method->Next)
1697       if (Method->Method)
1698         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1699 
1700     assert(Out.tell() - Start == DataLen && "Data length is wrong");
1701   }
1702 };
1703 } // end anonymous namespace
1704 
1705 /// \brief Write ObjC data: selectors and the method pool.
1706 ///
1707 /// The method pool contains both instance and factory methods, stored
1708 /// in an on-disk hash table indexed by the selector. The hash table also
1709 /// contains an empty entry for every other selector known to Sema.
1710 void ASTWriter::WriteSelectors(Sema &SemaRef) {
1711   using namespace llvm;
1712 
1713   // Do we have to do anything at all?
1714   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
1715     return;
1716   unsigned NumTableEntries = 0;
1717   // Create and write out the blob that contains selectors and the method pool.
1718   {
1719     OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
1720     ASTMethodPoolTrait Trait(*this);
1721 
1722     // Create the on-disk hash table representation. We walk through every
1723     // selector we've seen and look it up in the method pool.
1724     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
1725     for (llvm::DenseMap<Selector, SelectorID>::iterator
1726              I = SelectorIDs.begin(), E = SelectorIDs.end();
1727          I != E; ++I) {
1728       Selector S = I->first;
1729       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
1730       ASTMethodPoolTrait::data_type Data = {
1731         I->second,
1732         ObjCMethodList(),
1733         ObjCMethodList()
1734       };
1735       if (F != SemaRef.MethodPool.end()) {
1736         Data.Instance = F->second.first;
1737         Data.Factory = F->second.second;
1738       }
1739       // Only write this selector if it's not in an existing AST or something
1740       // changed.
1741       if (Chain && I->second < FirstSelectorID) {
1742         // Selector already exists. Did it change?
1743         bool changed = false;
1744         for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
1745              M = M->Next) {
1746           if (M->Method->getPCHLevel() == 0)
1747             changed = true;
1748         }
1749         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
1750              M = M->Next) {
1751           if (M->Method->getPCHLevel() == 0)
1752             changed = true;
1753         }
1754         if (!changed)
1755           continue;
1756       } else if (Data.Instance.Method || Data.Factory.Method) {
1757         // A new method pool entry.
1758         ++NumTableEntries;
1759       }
1760       Generator.insert(S, Data, Trait);
1761     }
1762 
1763     // Create the on-disk hash table in a buffer.
1764     llvm::SmallString<4096> MethodPool;
1765     uint32_t BucketOffset;
1766     {
1767       ASTMethodPoolTrait Trait(*this);
1768       llvm::raw_svector_ostream Out(MethodPool);
1769       // Make sure that no bucket is at offset 0
1770       clang::io::Emit32(Out, 0);
1771       BucketOffset = Generator.Emit(Out, Trait);
1772     }
1773 
1774     // Create a blob abbreviation
1775     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1776     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
1777     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1778     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1779     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1780     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1781 
1782     // Write the method pool
1783     RecordData Record;
1784     Record.push_back(METHOD_POOL);
1785     Record.push_back(BucketOffset);
1786     Record.push_back(NumTableEntries);
1787     Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
1788 
1789     // Create a blob abbreviation for the selector table offsets.
1790     Abbrev = new BitCodeAbbrev();
1791     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
1792     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1793     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1794     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1795 
1796     // Write the selector offsets table.
1797     Record.clear();
1798     Record.push_back(SELECTOR_OFFSETS);
1799     Record.push_back(SelectorOffsets.size());
1800     Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1801                               (const char *)data(SelectorOffsets),
1802                               SelectorOffsets.size() * 4);
1803   }
1804 }
1805 
1806 /// \brief Write the selectors referenced in @selector expression into AST file.
1807 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
1808   using namespace llvm;
1809   if (SemaRef.ReferencedSelectors.empty())
1810     return;
1811 
1812   RecordData Record;
1813 
1814   // Note: this writes out all references even for a dependent AST. But it is
1815   // very tricky to fix, and given that @selector shouldn't really appear in
1816   // headers, probably not worth it. It's not a correctness issue.
1817   for (DenseMap<Selector, SourceLocation>::iterator S =
1818        SemaRef.ReferencedSelectors.begin(),
1819        E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
1820     Selector Sel = (*S).first;
1821     SourceLocation Loc = (*S).second;
1822     AddSelectorRef(Sel, Record);
1823     AddSourceLocation(Loc, Record);
1824   }
1825   Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
1826 }
1827 
1828 //===----------------------------------------------------------------------===//
1829 // Identifier Table Serialization
1830 //===----------------------------------------------------------------------===//
1831 
1832 namespace {
1833 class ASTIdentifierTableTrait {
1834   ASTWriter &Writer;
1835   Preprocessor &PP;
1836 
1837   /// \brief Determines whether this is an "interesting" identifier
1838   /// that needs a full IdentifierInfo structure written into the hash
1839   /// table.
1840   static bool isInterestingIdentifier(const IdentifierInfo *II) {
1841     return II->isPoisoned() ||
1842       II->isExtensionToken() ||
1843       II->hasMacroDefinition() ||
1844       II->getObjCOrBuiltinID() ||
1845       II->getFETokenInfo<void>();
1846   }
1847 
1848 public:
1849   typedef const IdentifierInfo* key_type;
1850   typedef key_type  key_type_ref;
1851 
1852   typedef IdentID data_type;
1853   typedef data_type data_type_ref;
1854 
1855   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
1856     : Writer(Writer), PP(PP) { }
1857 
1858   static unsigned ComputeHash(const IdentifierInfo* II) {
1859     return llvm::HashString(II->getName());
1860   }
1861 
1862   std::pair<unsigned,unsigned>
1863     EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1864                       IdentID ID) {
1865     unsigned KeyLen = II->getLength() + 1;
1866     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1867     if (isInterestingIdentifier(II)) {
1868       DataLen += 2; // 2 bytes for builtin ID, flags
1869       if (II->hasMacroDefinition() &&
1870           !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1871         DataLen += 4;
1872       for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1873                                      DEnd = IdentifierResolver::end();
1874            D != DEnd; ++D)
1875         DataLen += sizeof(DeclID);
1876     }
1877     clang::io::Emit16(Out, DataLen);
1878     // We emit the key length after the data length so that every
1879     // string is preceded by a 16-bit length. This matches the PTH
1880     // format for storing identifiers.
1881     clang::io::Emit16(Out, KeyLen);
1882     return std::make_pair(KeyLen, DataLen);
1883   }
1884 
1885   void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1886                unsigned KeyLen) {
1887     // Record the location of the key data.  This is used when generating
1888     // the mapping from persistent IDs to strings.
1889     Writer.SetIdentifierOffset(II, Out.tell());
1890     Out.write(II->getNameStart(), KeyLen);
1891   }
1892 
1893   void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1894                 IdentID ID, unsigned) {
1895     if (!isInterestingIdentifier(II)) {
1896       clang::io::Emit32(Out, ID << 1);
1897       return;
1898     }
1899 
1900     clang::io::Emit32(Out, (ID << 1) | 0x01);
1901     uint32_t Bits = 0;
1902     bool hasMacroDefinition =
1903       II->hasMacroDefinition() &&
1904       !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
1905     Bits = (uint32_t)II->getObjCOrBuiltinID();
1906     Bits = (Bits << 1) | unsigned(hasMacroDefinition);
1907     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
1908     Bits = (Bits << 1) | unsigned(II->isPoisoned());
1909     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
1910     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
1911     clang::io::Emit16(Out, Bits);
1912 
1913     if (hasMacroDefinition)
1914       clang::io::Emit32(Out, Writer.getMacroOffset(II));
1915 
1916     // Emit the declaration IDs in reverse order, because the
1917     // IdentifierResolver provides the declarations as they would be
1918     // visible (e.g., the function "stat" would come before the struct
1919     // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1920     // adds declarations to the end of the list (so we need to see the
1921     // struct "status" before the function "status").
1922     // Only emit declarations that aren't from a chained PCH, though.
1923     llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1924                                         IdentifierResolver::end());
1925     for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1926                                                       DEnd = Decls.rend();
1927          D != DEnd; ++D)
1928       clang::io::Emit32(Out, Writer.getDeclID(*D));
1929   }
1930 };
1931 } // end anonymous namespace
1932 
1933 /// \brief Write the identifier table into the AST file.
1934 ///
1935 /// The identifier table consists of a blob containing string data
1936 /// (the actual identifiers themselves) and a separate "offsets" index
1937 /// that maps identifier IDs to locations within the blob.
1938 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
1939   using namespace llvm;
1940 
1941   // Create and write out the blob that contains the identifier
1942   // strings.
1943   {
1944     OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
1945     ASTIdentifierTableTrait Trait(*this, PP);
1946 
1947     // Look for any identifiers that were named while processing the
1948     // headers, but are otherwise not needed. We add these to the hash
1949     // table to enable checking of the predefines buffer in the case
1950     // where the user adds new macro definitions when building the AST
1951     // file.
1952     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1953                                 IDEnd = PP.getIdentifierTable().end();
1954          ID != IDEnd; ++ID)
1955       getIdentifierRef(ID->second);
1956 
1957     // Create the on-disk hash table representation. We only store offsets
1958     // for identifiers that appear here for the first time.
1959     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
1960     for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
1961            ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1962          ID != IDEnd; ++ID) {
1963       assert(ID->first && "NULL identifier in identifier table");
1964       if (!Chain || !ID->first->isFromAST())
1965         Generator.insert(ID->first, ID->second, Trait);
1966     }
1967 
1968     // Create the on-disk hash table in a buffer.
1969     llvm::SmallString<4096> IdentifierTable;
1970     uint32_t BucketOffset;
1971     {
1972       ASTIdentifierTableTrait Trait(*this, PP);
1973       llvm::raw_svector_ostream Out(IdentifierTable);
1974       // Make sure that no bucket is at offset 0
1975       clang::io::Emit32(Out, 0);
1976       BucketOffset = Generator.Emit(Out, Trait);
1977     }
1978 
1979     // Create a blob abbreviation
1980     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1981     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
1982     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1983     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1984     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
1985 
1986     // Write the identifier table
1987     RecordData Record;
1988     Record.push_back(IDENTIFIER_TABLE);
1989     Record.push_back(BucketOffset);
1990     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
1991   }
1992 
1993   // Write the offsets table for identifier IDs.
1994   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1995   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
1996   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1997   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1998   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1999 
2000   RecordData Record;
2001   Record.push_back(IDENTIFIER_OFFSET);
2002   Record.push_back(IdentifierOffsets.size());
2003   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2004                             (const char *)data(IdentifierOffsets),
2005                             IdentifierOffsets.size() * sizeof(uint32_t));
2006 }
2007 
2008 //===----------------------------------------------------------------------===//
2009 // DeclContext's Name Lookup Table Serialization
2010 //===----------------------------------------------------------------------===//
2011 
2012 namespace {
2013 // Trait used for the on-disk hash table used in the method pool.
2014 class ASTDeclContextNameLookupTrait {
2015   ASTWriter &Writer;
2016 
2017 public:
2018   typedef DeclarationName key_type;
2019   typedef key_type key_type_ref;
2020 
2021   typedef DeclContext::lookup_result data_type;
2022   typedef const data_type& data_type_ref;
2023 
2024   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2025 
2026   unsigned ComputeHash(DeclarationName Name) {
2027     llvm::FoldingSetNodeID ID;
2028     ID.AddInteger(Name.getNameKind());
2029 
2030     switch (Name.getNameKind()) {
2031     case DeclarationName::Identifier:
2032       ID.AddString(Name.getAsIdentifierInfo()->getName());
2033       break;
2034     case DeclarationName::ObjCZeroArgSelector:
2035     case DeclarationName::ObjCOneArgSelector:
2036     case DeclarationName::ObjCMultiArgSelector:
2037       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2038       break;
2039     case DeclarationName::CXXConstructorName:
2040     case DeclarationName::CXXDestructorName:
2041     case DeclarationName::CXXConversionFunctionName:
2042       ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2043       break;
2044     case DeclarationName::CXXOperatorName:
2045       ID.AddInteger(Name.getCXXOverloadedOperator());
2046       break;
2047     case DeclarationName::CXXLiteralOperatorName:
2048       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2049     case DeclarationName::CXXUsingDirective:
2050       break;
2051     }
2052 
2053     return ID.ComputeHash();
2054   }
2055 
2056   std::pair<unsigned,unsigned>
2057     EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2058                       data_type_ref Lookup) {
2059     unsigned KeyLen = 1;
2060     switch (Name.getNameKind()) {
2061     case DeclarationName::Identifier:
2062     case DeclarationName::ObjCZeroArgSelector:
2063     case DeclarationName::ObjCOneArgSelector:
2064     case DeclarationName::ObjCMultiArgSelector:
2065     case DeclarationName::CXXConstructorName:
2066     case DeclarationName::CXXDestructorName:
2067     case DeclarationName::CXXConversionFunctionName:
2068     case DeclarationName::CXXLiteralOperatorName:
2069       KeyLen += 4;
2070       break;
2071     case DeclarationName::CXXOperatorName:
2072       KeyLen += 1;
2073       break;
2074     case DeclarationName::CXXUsingDirective:
2075       break;
2076     }
2077     clang::io::Emit16(Out, KeyLen);
2078 
2079     // 2 bytes for num of decls and 4 for each DeclID.
2080     unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2081     clang::io::Emit16(Out, DataLen);
2082 
2083     return std::make_pair(KeyLen, DataLen);
2084   }
2085 
2086   void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2087     using namespace clang::io;
2088 
2089     assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2090     Emit8(Out, Name.getNameKind());
2091     switch (Name.getNameKind()) {
2092     case DeclarationName::Identifier:
2093       Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2094       break;
2095     case DeclarationName::ObjCZeroArgSelector:
2096     case DeclarationName::ObjCOneArgSelector:
2097     case DeclarationName::ObjCMultiArgSelector:
2098       Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2099       break;
2100     case DeclarationName::CXXConstructorName:
2101     case DeclarationName::CXXDestructorName:
2102     case DeclarationName::CXXConversionFunctionName:
2103       Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2104       break;
2105     case DeclarationName::CXXOperatorName:
2106       assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2107       Emit8(Out, Name.getCXXOverloadedOperator());
2108       break;
2109     case DeclarationName::CXXLiteralOperatorName:
2110       Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2111       break;
2112     case DeclarationName::CXXUsingDirective:
2113       break;
2114     }
2115   }
2116 
2117   void EmitData(llvm::raw_ostream& Out, key_type_ref,
2118                 data_type Lookup, unsigned DataLen) {
2119     uint64_t Start = Out.tell(); (void)Start;
2120     clang::io::Emit16(Out, Lookup.second - Lookup.first);
2121     for (; Lookup.first != Lookup.second; ++Lookup.first)
2122       clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2123 
2124     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2125   }
2126 };
2127 } // end anonymous namespace
2128 
2129 /// \brief Write the block containing all of the declaration IDs
2130 /// visible from the given DeclContext.
2131 ///
2132 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2133 /// bitstream, or 0 if no block was written.
2134 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2135                                                  DeclContext *DC) {
2136   if (DC->getPrimaryContext() != DC)
2137     return 0;
2138 
2139   // Since there is no name lookup into functions or methods, don't bother to
2140   // build a visible-declarations table for these entities.
2141   if (DC->isFunctionOrMethod())
2142     return 0;
2143 
2144   // If not in C++, we perform name lookup for the translation unit via the
2145   // IdentifierInfo chains, don't bother to build a visible-declarations table.
2146   // FIXME: In C++ we need the visible declarations in order to "see" the
2147   // friend declarations, is there a way to do this without writing the table ?
2148   if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2149     return 0;
2150 
2151   // Force the DeclContext to build a its name-lookup table.
2152   if (DC->hasExternalVisibleStorage())
2153     DC->MaterializeVisibleDeclsFromExternalStorage();
2154   else
2155     DC->lookup(DeclarationName());
2156 
2157   // Serialize the contents of the mapping used for lookup. Note that,
2158   // although we have two very different code paths, the serialized
2159   // representation is the same for both cases: a declaration name,
2160   // followed by a size, followed by references to the visible
2161   // declarations that have that name.
2162   uint64_t Offset = Stream.GetCurrentBitNo();
2163   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2164   if (!Map || Map->empty())
2165     return 0;
2166 
2167   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2168   ASTDeclContextNameLookupTrait Trait(*this);
2169 
2170   // Create the on-disk hash table representation.
2171   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2172        D != DEnd; ++D) {
2173     DeclarationName Name = D->first;
2174     DeclContext::lookup_result Result = D->second.getLookupResult();
2175     Generator.insert(Name, Result, Trait);
2176   }
2177 
2178   // Create the on-disk hash table in a buffer.
2179   llvm::SmallString<4096> LookupTable;
2180   uint32_t BucketOffset;
2181   {
2182     llvm::raw_svector_ostream Out(LookupTable);
2183     // Make sure that no bucket is at offset 0
2184     clang::io::Emit32(Out, 0);
2185     BucketOffset = Generator.Emit(Out, Trait);
2186   }
2187 
2188   // Write the lookup table
2189   RecordData Record;
2190   Record.push_back(DECL_CONTEXT_VISIBLE);
2191   Record.push_back(BucketOffset);
2192   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2193                             LookupTable.str());
2194 
2195   Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2196   ++NumVisibleDeclContexts;
2197   return Offset;
2198 }
2199 
2200 /// \brief Write an UPDATE_VISIBLE block for the given context.
2201 ///
2202 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2203 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2204 /// (in C++) and for namespaces.
2205 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2206   // Make the context build its lookup table, but don't make it load external
2207   // decls.
2208   DC->lookup(DeclarationName());
2209 
2210   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2211   if (!Map || Map->empty())
2212     return;
2213 
2214   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2215   ASTDeclContextNameLookupTrait Trait(*this);
2216 
2217   // Create the hash table.
2218   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2219        D != DEnd; ++D) {
2220     DeclarationName Name = D->first;
2221     DeclContext::lookup_result Result = D->second.getLookupResult();
2222     // For any name that appears in this table, the results are complete, i.e.
2223     // they overwrite results from previous PCHs. Merging is always a mess.
2224     Generator.insert(Name, Result, Trait);
2225   }
2226 
2227   // Create the on-disk hash table in a buffer.
2228   llvm::SmallString<4096> LookupTable;
2229   uint32_t BucketOffset;
2230   {
2231     llvm::raw_svector_ostream Out(LookupTable);
2232     // Make sure that no bucket is at offset 0
2233     clang::io::Emit32(Out, 0);
2234     BucketOffset = Generator.Emit(Out, Trait);
2235   }
2236 
2237   // Write the lookup table
2238   RecordData Record;
2239   Record.push_back(UPDATE_VISIBLE);
2240   Record.push_back(getDeclID(cast<Decl>(DC)));
2241   Record.push_back(BucketOffset);
2242   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2243 }
2244 
2245 //===----------------------------------------------------------------------===//
2246 // General Serialization Routines
2247 //===----------------------------------------------------------------------===//
2248 
2249 /// \brief Write a record containing the given attributes.
2250 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2251   Record.push_back(Attrs.size());
2252   for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2253     const Attr * A = *i;
2254     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2255     AddSourceLocation(A->getLocation(), Record);
2256     Record.push_back(A->isInherited());
2257 
2258 #include "clang/Serialization/AttrPCHWrite.inc"
2259 
2260   }
2261 }
2262 
2263 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2264   Record.push_back(Str.size());
2265   Record.insert(Record.end(), Str.begin(), Str.end());
2266 }
2267 
2268 /// \brief Note that the identifier II occurs at the given offset
2269 /// within the identifier table.
2270 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2271   IdentID ID = IdentifierIDs[II];
2272   // Only store offsets new to this AST file. Other identifier names are looked
2273   // up earlier in the chain and thus don't need an offset.
2274   if (ID >= FirstIdentID)
2275     IdentifierOffsets[ID - FirstIdentID] = Offset;
2276 }
2277 
2278 /// \brief Note that the selector Sel occurs at the given offset
2279 /// within the method pool/selector table.
2280 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2281   unsigned ID = SelectorIDs[Sel];
2282   assert(ID && "Unknown selector");
2283   // Don't record offsets for selectors that are also available in a different
2284   // file.
2285   if (ID < FirstSelectorID)
2286     return;
2287   SelectorOffsets[ID - FirstSelectorID] = Offset;
2288 }
2289 
2290 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2291   : Stream(Stream), Chain(0), SerializationListener(0),
2292     FirstDeclID(1), NextDeclID(FirstDeclID),
2293     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2294     FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2295     NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2296     CollectedStmts(&StmtsToEmit),
2297     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2298     NumVisibleDeclContexts(0), FirstCXXBaseSpecifiersID(1),
2299     NextCXXBaseSpecifiersID(1)
2300 {
2301 }
2302 
2303 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2304                          const char *isysroot) {
2305   // Emit the file header.
2306   Stream.Emit((unsigned)'C', 8);
2307   Stream.Emit((unsigned)'P', 8);
2308   Stream.Emit((unsigned)'C', 8);
2309   Stream.Emit((unsigned)'H', 8);
2310 
2311   WriteBlockInfoBlock();
2312 
2313   if (Chain)
2314     WriteASTChain(SemaRef, StatCalls, isysroot);
2315   else
2316     WriteASTCore(SemaRef, StatCalls, isysroot);
2317 }
2318 
2319 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2320                              const char *isysroot) {
2321   using namespace llvm;
2322 
2323   ASTContext &Context = SemaRef.Context;
2324   Preprocessor &PP = SemaRef.PP;
2325 
2326   // The translation unit is the first declaration we'll emit.
2327   DeclIDs[Context.getTranslationUnitDecl()] = 1;
2328   ++NextDeclID;
2329   DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2330 
2331   // Make sure that we emit IdentifierInfos (and any attached
2332   // declarations) for builtins.
2333   {
2334     IdentifierTable &Table = PP.getIdentifierTable();
2335     llvm::SmallVector<const char *, 32> BuiltinNames;
2336     Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2337                                         Context.getLangOptions().NoBuiltin);
2338     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2339       getIdentifierRef(&Table.get(BuiltinNames[I]));
2340   }
2341 
2342   // Build a record containing all of the tentative definitions in this file, in
2343   // TentativeDefinitions order.  Generally, this record will be empty for
2344   // headers.
2345   RecordData TentativeDefinitions;
2346   for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2347     AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2348   }
2349 
2350   // Build a record containing all of the file scoped decls in this file.
2351   RecordData UnusedFileScopedDecls;
2352   for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2353     AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2354 
2355   RecordData WeakUndeclaredIdentifiers;
2356   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2357     WeakUndeclaredIdentifiers.push_back(
2358                                       SemaRef.WeakUndeclaredIdentifiers.size());
2359     for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2360          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2361          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2362       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2363       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2364       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2365       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2366     }
2367   }
2368 
2369   // Build a record containing all of the locally-scoped external
2370   // declarations in this header file. Generally, this record will be
2371   // empty.
2372   RecordData LocallyScopedExternalDecls;
2373   // FIXME: This is filling in the AST file in densemap order which is
2374   // nondeterminstic!
2375   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2376          TD = SemaRef.LocallyScopedExternalDecls.begin(),
2377          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2378        TD != TDEnd; ++TD)
2379     AddDeclRef(TD->second, LocallyScopedExternalDecls);
2380 
2381   // Build a record containing all of the ext_vector declarations.
2382   RecordData ExtVectorDecls;
2383   for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2384     AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2385 
2386   // Build a record containing all of the VTable uses information.
2387   RecordData VTableUses;
2388   if (!SemaRef.VTableUses.empty()) {
2389     VTableUses.push_back(SemaRef.VTableUses.size());
2390     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2391       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2392       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2393       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2394     }
2395   }
2396 
2397   // Build a record containing all of dynamic classes declarations.
2398   RecordData DynamicClasses;
2399   for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2400     AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2401 
2402   // Build a record containing all of pending implicit instantiations.
2403   RecordData PendingInstantiations;
2404   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2405          I = SemaRef.PendingInstantiations.begin(),
2406          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2407     AddDeclRef(I->first, PendingInstantiations);
2408     AddSourceLocation(I->second, PendingInstantiations);
2409   }
2410   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2411          "There are local ones at end of translation unit!");
2412 
2413   // Build a record containing some declaration references.
2414   RecordData SemaDeclRefs;
2415   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2416     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2417     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2418   }
2419 
2420   // Write the remaining AST contents.
2421   RecordData Record;
2422   Stream.EnterSubblock(AST_BLOCK_ID, 5);
2423   WriteMetadata(Context, isysroot);
2424   WriteLanguageOptions(Context.getLangOptions());
2425   if (StatCalls && !isysroot)
2426     WriteStatCache(*StatCalls);
2427   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2428   // Write the record of special types.
2429   Record.clear();
2430 
2431   AddTypeRef(Context.getBuiltinVaListType(), Record);
2432   AddTypeRef(Context.getObjCIdType(), Record);
2433   AddTypeRef(Context.getObjCSelType(), Record);
2434   AddTypeRef(Context.getObjCProtoType(), Record);
2435   AddTypeRef(Context.getObjCClassType(), Record);
2436   AddTypeRef(Context.getRawCFConstantStringType(), Record);
2437   AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2438   AddTypeRef(Context.getFILEType(), Record);
2439   AddTypeRef(Context.getjmp_bufType(), Record);
2440   AddTypeRef(Context.getsigjmp_bufType(), Record);
2441   AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2442   AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2443   AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2444   AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2445   AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2446   AddTypeRef(Context.getRawNSConstantStringType(), Record);
2447   Record.push_back(Context.isInt128Installed());
2448   Stream.EmitRecord(SPECIAL_TYPES, Record);
2449 
2450   // Keep writing types and declarations until all types and
2451   // declarations have been written.
2452   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2453   WriteDeclsBlockAbbrevs();
2454   while (!DeclTypesToEmit.empty()) {
2455     DeclOrType DOT = DeclTypesToEmit.front();
2456     DeclTypesToEmit.pop();
2457     if (DOT.isType())
2458       WriteType(DOT.getType());
2459     else
2460       WriteDecl(Context, DOT.getDecl());
2461   }
2462   Stream.ExitBlock();
2463 
2464   WritePreprocessor(PP);
2465   WriteSelectors(SemaRef);
2466   WriteReferencedSelectorsPool(SemaRef);
2467   WriteIdentifierTable(PP);
2468 
2469   WriteTypeDeclOffsets();
2470   WriteUserDiagnosticMappings(Context.getDiagnostics());
2471 
2472   // Write the C++ base-specifier set offsets.
2473   if (!CXXBaseSpecifiersOffsets.empty()) {
2474     // Create a blob abbreviation for the C++ base specifiers offsets.
2475     using namespace llvm;
2476 
2477     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2478     Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2479     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2480     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2481     unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2482 
2483     // Write the selector offsets table.
2484     Record.clear();
2485     Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2486     Record.push_back(CXXBaseSpecifiersOffsets.size());
2487     Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2488                               (const char *)CXXBaseSpecifiersOffsets.data(),
2489                             CXXBaseSpecifiersOffsets.size() * sizeof(uint32_t));
2490   }
2491 
2492   // Write the record containing external, unnamed definitions.
2493   if (!ExternalDefinitions.empty())
2494     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2495 
2496   // Write the record containing tentative definitions.
2497   if (!TentativeDefinitions.empty())
2498     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2499 
2500   // Write the record containing unused file scoped decls.
2501   if (!UnusedFileScopedDecls.empty())
2502     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2503 
2504   // Write the record containing weak undeclared identifiers.
2505   if (!WeakUndeclaredIdentifiers.empty())
2506     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2507                       WeakUndeclaredIdentifiers);
2508 
2509   // Write the record containing locally-scoped external definitions.
2510   if (!LocallyScopedExternalDecls.empty())
2511     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2512                       LocallyScopedExternalDecls);
2513 
2514   // Write the record containing ext_vector type names.
2515   if (!ExtVectorDecls.empty())
2516     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2517 
2518   // Write the record containing VTable uses information.
2519   if (!VTableUses.empty())
2520     Stream.EmitRecord(VTABLE_USES, VTableUses);
2521 
2522   // Write the record containing dynamic classes declarations.
2523   if (!DynamicClasses.empty())
2524     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2525 
2526   // Write the record containing pending implicit instantiations.
2527   if (!PendingInstantiations.empty())
2528     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2529 
2530   // Write the record containing declaration references of Sema.
2531   if (!SemaDeclRefs.empty())
2532     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2533 
2534   // Some simple statistics
2535   Record.clear();
2536   Record.push_back(NumStatements);
2537   Record.push_back(NumMacros);
2538   Record.push_back(NumLexicalDeclContexts);
2539   Record.push_back(NumVisibleDeclContexts);
2540   Stream.EmitRecord(STATISTICS, Record);
2541   Stream.ExitBlock();
2542 }
2543 
2544 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2545                               const char *isysroot) {
2546   using namespace llvm;
2547 
2548   ASTContext &Context = SemaRef.Context;
2549   Preprocessor &PP = SemaRef.PP;
2550 
2551   RecordData Record;
2552   Stream.EnterSubblock(AST_BLOCK_ID, 5);
2553   WriteMetadata(Context, isysroot);
2554   if (StatCalls && !isysroot)
2555     WriteStatCache(*StatCalls);
2556   // FIXME: Source manager block should only write new stuff, which could be
2557   // done by tracking the largest ID in the chain
2558   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2559 
2560   // The special types are in the chained PCH.
2561 
2562   // We don't start with the translation unit, but with its decls that
2563   // don't come from the chained PCH.
2564   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2565   llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
2566   for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
2567                                   E = TU->noload_decls_end();
2568        I != E; ++I) {
2569     if ((*I)->getPCHLevel() == 0)
2570       NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
2571     else if ((*I)->isChangedSinceDeserialization())
2572       (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
2573   }
2574   // We also need to write a lexical updates block for the TU.
2575   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
2576   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
2577   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2578   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
2579   Record.clear();
2580   Record.push_back(TU_UPDATE_LEXICAL);
2581   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
2582                           reinterpret_cast<const char*>(NewGlobalDecls.data()),
2583                           NewGlobalDecls.size() * sizeof(KindDeclIDPair));
2584   // And a visible updates block for the DeclContexts.
2585   Abv = new llvm::BitCodeAbbrev();
2586   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
2587   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
2588   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
2589   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2590   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
2591   WriteDeclContextVisibleUpdate(TU);
2592 
2593   // Build a record containing all of the new tentative definitions in this
2594   // file, in TentativeDefinitions order.
2595   RecordData TentativeDefinitions;
2596   for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2597     if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
2598       AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2599   }
2600 
2601   // Build a record containing all of the file scoped decls in this file.
2602   RecordData UnusedFileScopedDecls;
2603   for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
2604     if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
2605       AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2606   }
2607 
2608   // We write the entire table, overwriting the tables from the chain.
2609   RecordData WeakUndeclaredIdentifiers;
2610   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2611     WeakUndeclaredIdentifiers.push_back(
2612                                       SemaRef.WeakUndeclaredIdentifiers.size());
2613     for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2614          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2615          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2616       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2617       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2618       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2619       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2620     }
2621   }
2622 
2623   // Build a record containing all of the locally-scoped external
2624   // declarations in this header file. Generally, this record will be
2625   // empty.
2626   RecordData LocallyScopedExternalDecls;
2627   // FIXME: This is filling in the AST file in densemap order which is
2628   // nondeterminstic!
2629   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2630          TD = SemaRef.LocallyScopedExternalDecls.begin(),
2631          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2632        TD != TDEnd; ++TD) {
2633     if (TD->second->getPCHLevel() == 0)
2634       AddDeclRef(TD->second, LocallyScopedExternalDecls);
2635   }
2636 
2637   // Build a record containing all of the ext_vector declarations.
2638   RecordData ExtVectorDecls;
2639   for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
2640     if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
2641       AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2642   }
2643 
2644   // Build a record containing all of the VTable uses information.
2645   // We write everything here, because it's too hard to determine whether
2646   // a use is new to this part.
2647   RecordData VTableUses;
2648   if (!SemaRef.VTableUses.empty()) {
2649     VTableUses.push_back(SemaRef.VTableUses.size());
2650     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2651       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2652       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2653       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2654     }
2655   }
2656 
2657   // Build a record containing all of dynamic classes declarations.
2658   RecordData DynamicClasses;
2659   for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2660     if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
2661       AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2662 
2663   // Build a record containing all of pending implicit instantiations.
2664   RecordData PendingInstantiations;
2665   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2666          I = SemaRef.PendingInstantiations.begin(),
2667          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2668     if (I->first->getPCHLevel() == 0) {
2669       AddDeclRef(I->first, PendingInstantiations);
2670       AddSourceLocation(I->second, PendingInstantiations);
2671     }
2672   }
2673   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2674          "There are local ones at end of translation unit!");
2675 
2676   // Build a record containing some declaration references.
2677   // It's not worth the effort to avoid duplication here.
2678   RecordData SemaDeclRefs;
2679   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2680     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2681     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2682   }
2683 
2684   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2685   WriteDeclsBlockAbbrevs();
2686   for (DeclsToRewriteTy::iterator
2687          I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
2688     DeclTypesToEmit.push(const_cast<Decl*>(*I));
2689   while (!DeclTypesToEmit.empty()) {
2690     DeclOrType DOT = DeclTypesToEmit.front();
2691     DeclTypesToEmit.pop();
2692     if (DOT.isType())
2693       WriteType(DOT.getType());
2694     else
2695       WriteDecl(Context, DOT.getDecl());
2696   }
2697   Stream.ExitBlock();
2698 
2699   WritePreprocessor(PP);
2700   WriteSelectors(SemaRef);
2701   WriteReferencedSelectorsPool(SemaRef);
2702   WriteIdentifierTable(PP);
2703   WriteTypeDeclOffsets();
2704   // FIXME: For chained PCH only write the new mappings (we currently
2705   // write all of them again).
2706   WriteUserDiagnosticMappings(Context.getDiagnostics());
2707 
2708   /// Build a record containing first declarations from a chained PCH and the
2709   /// most recent declarations in this AST that they point to.
2710   RecordData FirstLatestDeclIDs;
2711   for (FirstLatestDeclMap::iterator
2712         I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
2713     assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
2714            "Expected first & second to be in different PCHs");
2715     AddDeclRef(I->first, FirstLatestDeclIDs);
2716     AddDeclRef(I->second, FirstLatestDeclIDs);
2717   }
2718   if (!FirstLatestDeclIDs.empty())
2719     Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
2720 
2721   // Write the record containing external, unnamed definitions.
2722   if (!ExternalDefinitions.empty())
2723     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2724 
2725   // Write the record containing tentative definitions.
2726   if (!TentativeDefinitions.empty())
2727     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2728 
2729   // Write the record containing unused file scoped decls.
2730   if (!UnusedFileScopedDecls.empty())
2731     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2732 
2733   // Write the record containing weak undeclared identifiers.
2734   if (!WeakUndeclaredIdentifiers.empty())
2735     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2736                       WeakUndeclaredIdentifiers);
2737 
2738   // Write the record containing locally-scoped external definitions.
2739   if (!LocallyScopedExternalDecls.empty())
2740     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2741                       LocallyScopedExternalDecls);
2742 
2743   // Write the record containing ext_vector type names.
2744   if (!ExtVectorDecls.empty())
2745     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2746 
2747   // Write the record containing VTable uses information.
2748   if (!VTableUses.empty())
2749     Stream.EmitRecord(VTABLE_USES, VTableUses);
2750 
2751   // Write the record containing dynamic classes declarations.
2752   if (!DynamicClasses.empty())
2753     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2754 
2755   // Write the record containing pending implicit instantiations.
2756   if (!PendingInstantiations.empty())
2757     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2758 
2759   // Write the record containing declaration references of Sema.
2760   if (!SemaDeclRefs.empty())
2761     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2762 
2763   // Write the updates to DeclContexts.
2764   for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
2765            I = UpdatedDeclContexts.begin(),
2766            E = UpdatedDeclContexts.end();
2767          I != E; ++I)
2768     WriteDeclContextVisibleUpdate(*I);
2769 
2770   WriteDeclUpdatesBlocks();
2771 
2772   Record.clear();
2773   Record.push_back(NumStatements);
2774   Record.push_back(NumMacros);
2775   Record.push_back(NumLexicalDeclContexts);
2776   Record.push_back(NumVisibleDeclContexts);
2777   WriteDeclReplacementsBlock();
2778   Stream.EmitRecord(STATISTICS, Record);
2779   Stream.ExitBlock();
2780 }
2781 
2782 void ASTWriter::WriteDeclUpdatesBlocks() {
2783   if (DeclUpdates.empty())
2784     return;
2785 
2786   RecordData OffsetsRecord;
2787   Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, 3);
2788   for (DeclUpdateMap::iterator
2789          I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
2790     const Decl *D = I->first;
2791     UpdateRecord &URec = I->second;
2792 
2793     if (DeclsToRewrite.count(D))
2794       continue; // The decl will be written completely,no need to store updates.
2795 
2796     uint64_t Offset = Stream.GetCurrentBitNo();
2797     Stream.EmitRecord(DECL_UPDATES, URec);
2798 
2799     OffsetsRecord.push_back(GetDeclRef(D));
2800     OffsetsRecord.push_back(Offset);
2801   }
2802   Stream.ExitBlock();
2803   Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
2804 }
2805 
2806 void ASTWriter::WriteDeclReplacementsBlock() {
2807   if (ReplacedDecls.empty())
2808     return;
2809 
2810   RecordData Record;
2811   for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
2812            I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
2813     Record.push_back(I->first);
2814     Record.push_back(I->second);
2815   }
2816   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
2817 }
2818 
2819 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
2820   Record.push_back(Loc.getRawEncoding());
2821 }
2822 
2823 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
2824   AddSourceLocation(Range.getBegin(), Record);
2825   AddSourceLocation(Range.getEnd(), Record);
2826 }
2827 
2828 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
2829   Record.push_back(Value.getBitWidth());
2830   const uint64_t *Words = Value.getRawData();
2831   Record.append(Words, Words + Value.getNumWords());
2832 }
2833 
2834 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
2835   Record.push_back(Value.isUnsigned());
2836   AddAPInt(Value, Record);
2837 }
2838 
2839 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
2840   AddAPInt(Value.bitcastToAPInt(), Record);
2841 }
2842 
2843 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
2844   Record.push_back(getIdentifierRef(II));
2845 }
2846 
2847 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
2848   if (II == 0)
2849     return 0;
2850 
2851   IdentID &ID = IdentifierIDs[II];
2852   if (ID == 0)
2853     ID = NextIdentID++;
2854   return ID;
2855 }
2856 
2857 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
2858   if (MD == 0)
2859     return 0;
2860 
2861   MacroID &ID = MacroDefinitions[MD];
2862   if (ID == 0)
2863     ID = NextMacroID++;
2864   return ID;
2865 }
2866 
2867 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
2868   Record.push_back(getSelectorRef(SelRef));
2869 }
2870 
2871 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
2872   if (Sel.getAsOpaquePtr() == 0) {
2873     return 0;
2874   }
2875 
2876   SelectorID &SID = SelectorIDs[Sel];
2877   if (SID == 0 && Chain) {
2878     // This might trigger a ReadSelector callback, which will set the ID for
2879     // this selector.
2880     Chain->LoadSelector(Sel);
2881   }
2882   if (SID == 0) {
2883     SID = NextSelectorID++;
2884   }
2885   return SID;
2886 }
2887 
2888 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
2889   AddDeclRef(Temp->getDestructor(), Record);
2890 }
2891 
2892 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
2893                                       CXXBaseSpecifier const *BasesEnd,
2894                                         RecordDataImpl &Record) {
2895   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
2896   CXXBaseSpecifiersToWrite.push_back(
2897                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
2898                                                         Bases, BasesEnd));
2899   Record.push_back(NextCXXBaseSpecifiersID++);
2900 }
2901 
2902 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2903                                            const TemplateArgumentLocInfo &Arg,
2904                                            RecordDataImpl &Record) {
2905   switch (Kind) {
2906   case TemplateArgument::Expression:
2907     AddStmt(Arg.getAsExpr());
2908     break;
2909   case TemplateArgument::Type:
2910     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
2911     break;
2912   case TemplateArgument::Template:
2913     AddSourceRange(Arg.getTemplateQualifierRange(), Record);
2914     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
2915     break;
2916   case TemplateArgument::TemplateExpansion:
2917     AddSourceRange(Arg.getTemplateQualifierRange(), Record);
2918     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
2919     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
2920     break;
2921   case TemplateArgument::Null:
2922   case TemplateArgument::Integral:
2923   case TemplateArgument::Declaration:
2924   case TemplateArgument::Pack:
2925     break;
2926   }
2927 }
2928 
2929 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
2930                                        RecordDataImpl &Record) {
2931   AddTemplateArgument(Arg.getArgument(), Record);
2932 
2933   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
2934     bool InfoHasSameExpr
2935       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
2936     Record.push_back(InfoHasSameExpr);
2937     if (InfoHasSameExpr)
2938       return; // Avoid storing the same expr twice.
2939   }
2940   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
2941                              Record);
2942 }
2943 
2944 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record) {
2945   if (TInfo == 0) {
2946     AddTypeRef(QualType(), Record);
2947     return;
2948   }
2949 
2950   AddTypeRef(TInfo->getType(), Record);
2951   TypeLocWriter TLW(*this, Record);
2952   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2953     TLW.Visit(TL);
2954 }
2955 
2956 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
2957   Record.push_back(GetOrCreateTypeID(T));
2958 }
2959 
2960 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
2961   return MakeTypeID(T,
2962               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
2963 }
2964 
2965 TypeID ASTWriter::getTypeID(QualType T) const {
2966   return MakeTypeID(T,
2967               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
2968 }
2969 
2970 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
2971   if (T.isNull())
2972     return TypeIdx();
2973   assert(!T.getLocalFastQualifiers());
2974 
2975   TypeIdx &Idx = TypeIdxs[T];
2976   if (Idx.getIndex() == 0) {
2977     // We haven't seen this type before. Assign it a new ID and put it
2978     // into the queue of types to emit.
2979     Idx = TypeIdx(NextTypeID++);
2980     DeclTypesToEmit.push(T);
2981   }
2982   return Idx;
2983 }
2984 
2985 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
2986   if (T.isNull())
2987     return TypeIdx();
2988   assert(!T.getLocalFastQualifiers());
2989 
2990   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
2991   assert(I != TypeIdxs.end() && "Type not emitted!");
2992   return I->second;
2993 }
2994 
2995 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
2996   Record.push_back(GetDeclRef(D));
2997 }
2998 
2999 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3000   if (D == 0) {
3001     return 0;
3002   }
3003   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3004   DeclID &ID = DeclIDs[D];
3005   if (ID == 0) {
3006     // We haven't seen this declaration before. Give it a new ID and
3007     // enqueue it in the list of declarations to emit.
3008     ID = NextDeclID++;
3009     DeclTypesToEmit.push(const_cast<Decl *>(D));
3010   } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3011     // We don't add it to the replacement collection here, because we don't
3012     // have the offset yet.
3013     DeclTypesToEmit.push(const_cast<Decl *>(D));
3014     // Reset the flag, so that we don't add this decl multiple times.
3015     const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3016   }
3017 
3018   return ID;
3019 }
3020 
3021 DeclID ASTWriter::getDeclID(const Decl *D) {
3022   if (D == 0)
3023     return 0;
3024 
3025   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3026   return DeclIDs[D];
3027 }
3028 
3029 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3030   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
3031   Record.push_back(Name.getNameKind());
3032   switch (Name.getNameKind()) {
3033   case DeclarationName::Identifier:
3034     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3035     break;
3036 
3037   case DeclarationName::ObjCZeroArgSelector:
3038   case DeclarationName::ObjCOneArgSelector:
3039   case DeclarationName::ObjCMultiArgSelector:
3040     AddSelectorRef(Name.getObjCSelector(), Record);
3041     break;
3042 
3043   case DeclarationName::CXXConstructorName:
3044   case DeclarationName::CXXDestructorName:
3045   case DeclarationName::CXXConversionFunctionName:
3046     AddTypeRef(Name.getCXXNameType(), Record);
3047     break;
3048 
3049   case DeclarationName::CXXOperatorName:
3050     Record.push_back(Name.getCXXOverloadedOperator());
3051     break;
3052 
3053   case DeclarationName::CXXLiteralOperatorName:
3054     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3055     break;
3056 
3057   case DeclarationName::CXXUsingDirective:
3058     // No extra data to emit
3059     break;
3060   }
3061 }
3062 
3063 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3064                                      DeclarationName Name, RecordDataImpl &Record) {
3065   switch (Name.getNameKind()) {
3066   case DeclarationName::CXXConstructorName:
3067   case DeclarationName::CXXDestructorName:
3068   case DeclarationName::CXXConversionFunctionName:
3069     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3070     break;
3071 
3072   case DeclarationName::CXXOperatorName:
3073     AddSourceLocation(
3074        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3075        Record);
3076     AddSourceLocation(
3077         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3078         Record);
3079     break;
3080 
3081   case DeclarationName::CXXLiteralOperatorName:
3082     AddSourceLocation(
3083      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3084      Record);
3085     break;
3086 
3087   case DeclarationName::Identifier:
3088   case DeclarationName::ObjCZeroArgSelector:
3089   case DeclarationName::ObjCOneArgSelector:
3090   case DeclarationName::ObjCMultiArgSelector:
3091   case DeclarationName::CXXUsingDirective:
3092     break;
3093   }
3094 }
3095 
3096 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3097                                        RecordDataImpl &Record) {
3098   AddDeclarationName(NameInfo.getName(), Record);
3099   AddSourceLocation(NameInfo.getLoc(), Record);
3100   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3101 }
3102 
3103 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3104                                  RecordDataImpl &Record) {
3105   AddNestedNameSpecifier(Info.NNS, Record);
3106   AddSourceRange(Info.NNSRange, Record);
3107   Record.push_back(Info.NumTemplParamLists);
3108   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3109     AddTemplateParameterList(Info.TemplParamLists[i], Record);
3110 }
3111 
3112 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3113                                        RecordDataImpl &Record) {
3114   // Nested name specifiers usually aren't too long. I think that 8 would
3115   // typically accomodate the vast majority.
3116   llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3117 
3118   // Push each of the NNS's onto a stack for serialization in reverse order.
3119   while (NNS) {
3120     NestedNames.push_back(NNS);
3121     NNS = NNS->getPrefix();
3122   }
3123 
3124   Record.push_back(NestedNames.size());
3125   while(!NestedNames.empty()) {
3126     NNS = NestedNames.pop_back_val();
3127     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3128     Record.push_back(Kind);
3129     switch (Kind) {
3130     case NestedNameSpecifier::Identifier:
3131       AddIdentifierRef(NNS->getAsIdentifier(), Record);
3132       break;
3133 
3134     case NestedNameSpecifier::Namespace:
3135       AddDeclRef(NNS->getAsNamespace(), Record);
3136       break;
3137 
3138     case NestedNameSpecifier::TypeSpec:
3139     case NestedNameSpecifier::TypeSpecWithTemplate:
3140       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3141       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3142       break;
3143 
3144     case NestedNameSpecifier::Global:
3145       // Don't need to write an associated value.
3146       break;
3147     }
3148   }
3149 }
3150 
3151 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3152   TemplateName::NameKind Kind = Name.getKind();
3153   Record.push_back(Kind);
3154   switch (Kind) {
3155   case TemplateName::Template:
3156     AddDeclRef(Name.getAsTemplateDecl(), Record);
3157     break;
3158 
3159   case TemplateName::OverloadedTemplate: {
3160     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3161     Record.push_back(OvT->size());
3162     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3163            I != E; ++I)
3164       AddDeclRef(*I, Record);
3165     break;
3166   }
3167 
3168   case TemplateName::QualifiedTemplate: {
3169     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3170     AddNestedNameSpecifier(QualT->getQualifier(), Record);
3171     Record.push_back(QualT->hasTemplateKeyword());
3172     AddDeclRef(QualT->getTemplateDecl(), Record);
3173     break;
3174   }
3175 
3176   case TemplateName::DependentTemplate: {
3177     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3178     AddNestedNameSpecifier(DepT->getQualifier(), Record);
3179     Record.push_back(DepT->isIdentifier());
3180     if (DepT->isIdentifier())
3181       AddIdentifierRef(DepT->getIdentifier(), Record);
3182     else
3183       Record.push_back(DepT->getOperator());
3184     break;
3185   }
3186   }
3187 }
3188 
3189 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3190                                     RecordDataImpl &Record) {
3191   Record.push_back(Arg.getKind());
3192   switch (Arg.getKind()) {
3193   case TemplateArgument::Null:
3194     break;
3195   case TemplateArgument::Type:
3196     AddTypeRef(Arg.getAsType(), Record);
3197     break;
3198   case TemplateArgument::Declaration:
3199     AddDeclRef(Arg.getAsDecl(), Record);
3200     break;
3201   case TemplateArgument::Integral:
3202     AddAPSInt(*Arg.getAsIntegral(), Record);
3203     AddTypeRef(Arg.getIntegralType(), Record);
3204     break;
3205   case TemplateArgument::Template:
3206   case TemplateArgument::TemplateExpansion:
3207     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3208     break;
3209   case TemplateArgument::Expression:
3210     AddStmt(Arg.getAsExpr());
3211     break;
3212   case TemplateArgument::Pack:
3213     Record.push_back(Arg.pack_size());
3214     for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3215            I != E; ++I)
3216       AddTemplateArgument(*I, Record);
3217     break;
3218   }
3219 }
3220 
3221 void
3222 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3223                                     RecordDataImpl &Record) {
3224   assert(TemplateParams && "No TemplateParams!");
3225   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3226   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3227   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3228   Record.push_back(TemplateParams->size());
3229   for (TemplateParameterList::const_iterator
3230          P = TemplateParams->begin(), PEnd = TemplateParams->end();
3231          P != PEnd; ++P)
3232     AddDeclRef(*P, Record);
3233 }
3234 
3235 /// \brief Emit a template argument list.
3236 void
3237 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3238                                    RecordDataImpl &Record) {
3239   assert(TemplateArgs && "No TemplateArgs!");
3240   Record.push_back(TemplateArgs->size());
3241   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3242     AddTemplateArgument(TemplateArgs->get(i), Record);
3243 }
3244 
3245 
3246 void
3247 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3248   Record.push_back(Set.size());
3249   for (UnresolvedSetImpl::const_iterator
3250          I = Set.begin(), E = Set.end(); I != E; ++I) {
3251     AddDeclRef(I.getDecl(), Record);
3252     Record.push_back(I.getAccess());
3253   }
3254 }
3255 
3256 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3257                                     RecordDataImpl &Record) {
3258   Record.push_back(Base.isVirtual());
3259   Record.push_back(Base.isBaseOfClass());
3260   Record.push_back(Base.getAccessSpecifierAsWritten());
3261   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3262   AddSourceRange(Base.getSourceRange(), Record);
3263   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3264                                           : SourceLocation(),
3265                     Record);
3266 }
3267 
3268 void ASTWriter::FlushCXXBaseSpecifiers() {
3269   RecordData Record;
3270   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3271     Record.clear();
3272 
3273     // Record the offset of this base-specifier set.
3274     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3275     if (Index == CXXBaseSpecifiersOffsets.size())
3276       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3277     else {
3278       if (Index > CXXBaseSpecifiersOffsets.size())
3279         CXXBaseSpecifiersOffsets.resize(Index + 1);
3280       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3281     }
3282 
3283     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3284                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3285     Record.push_back(BEnd - B);
3286     for (; B != BEnd; ++B)
3287       AddCXXBaseSpecifier(*B, Record);
3288     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3289 
3290     // Flush any expressions that were written as part of the base specifiers.
3291     FlushStmts();
3292   }
3293 
3294   CXXBaseSpecifiersToWrite.clear();
3295 }
3296 
3297 void ASTWriter::AddCXXCtorInitializers(
3298                              const CXXCtorInitializer * const *CtorInitializers,
3299                              unsigned NumCtorInitializers,
3300                              RecordDataImpl &Record) {
3301   Record.push_back(NumCtorInitializers);
3302   for (unsigned i=0; i != NumCtorInitializers; ++i) {
3303     const CXXCtorInitializer *Init = CtorInitializers[i];
3304 
3305     Record.push_back(Init->isBaseInitializer());
3306     if (Init->isBaseInitializer()) {
3307       AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3308       Record.push_back(Init->isBaseVirtual());
3309     } else {
3310       Record.push_back(Init->isIndirectMemberInitializer());
3311       if (Init->isIndirectMemberInitializer())
3312         AddDeclRef(Init->getIndirectMember(), Record);
3313       else
3314         AddDeclRef(Init->getMember(), Record);
3315     }
3316 
3317     AddSourceLocation(Init->getMemberLocation(), Record);
3318     AddStmt(Init->getInit());
3319     AddSourceLocation(Init->getLParenLoc(), Record);
3320     AddSourceLocation(Init->getRParenLoc(), Record);
3321     Record.push_back(Init->isWritten());
3322     if (Init->isWritten()) {
3323       Record.push_back(Init->getSourceOrder());
3324     } else {
3325       Record.push_back(Init->getNumArrayIndices());
3326       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3327         AddDeclRef(Init->getArrayIndex(i), Record);
3328     }
3329   }
3330 }
3331 
3332 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3333   assert(D->DefinitionData);
3334   struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3335   Record.push_back(Data.UserDeclaredConstructor);
3336   Record.push_back(Data.UserDeclaredCopyConstructor);
3337   Record.push_back(Data.UserDeclaredCopyAssignment);
3338   Record.push_back(Data.UserDeclaredDestructor);
3339   Record.push_back(Data.Aggregate);
3340   Record.push_back(Data.PlainOldData);
3341   Record.push_back(Data.Empty);
3342   Record.push_back(Data.Polymorphic);
3343   Record.push_back(Data.Abstract);
3344   Record.push_back(Data.HasTrivialConstructor);
3345   Record.push_back(Data.HasTrivialCopyConstructor);
3346   Record.push_back(Data.HasTrivialCopyAssignment);
3347   Record.push_back(Data.HasTrivialDestructor);
3348   Record.push_back(Data.ComputedVisibleConversions);
3349   Record.push_back(Data.DeclaredDefaultConstructor);
3350   Record.push_back(Data.DeclaredCopyConstructor);
3351   Record.push_back(Data.DeclaredCopyAssignment);
3352   Record.push_back(Data.DeclaredDestructor);
3353 
3354   Record.push_back(Data.NumBases);
3355   if (Data.NumBases > 0)
3356     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3357                             Record);
3358 
3359   // FIXME: Make VBases lazily computed when needed to avoid storing them.
3360   Record.push_back(Data.NumVBases);
3361   if (Data.NumVBases > 0)
3362     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3363                             Record);
3364 
3365   AddUnresolvedSet(Data.Conversions, Record);
3366   AddUnresolvedSet(Data.VisibleConversions, Record);
3367   // Data.Definition is the owning decl, no need to write it.
3368   AddDeclRef(Data.FirstFriend, Record);
3369 }
3370 
3371 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3372   assert(Reader && "Cannot remove chain");
3373   assert(!Chain && "Cannot replace chain");
3374   assert(FirstDeclID == NextDeclID &&
3375          FirstTypeID == NextTypeID &&
3376          FirstIdentID == NextIdentID &&
3377          FirstSelectorID == NextSelectorID &&
3378          FirstMacroID == NextMacroID &&
3379          FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3380          "Setting chain after writing has started.");
3381   Chain = Reader;
3382 
3383   FirstDeclID += Chain->getTotalNumDecls();
3384   FirstTypeID += Chain->getTotalNumTypes();
3385   FirstIdentID += Chain->getTotalNumIdentifiers();
3386   FirstSelectorID += Chain->getTotalNumSelectors();
3387   FirstMacroID += Chain->getTotalNumMacroDefinitions();
3388   FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3389   NextDeclID = FirstDeclID;
3390   NextTypeID = FirstTypeID;
3391   NextIdentID = FirstIdentID;
3392   NextSelectorID = FirstSelectorID;
3393   NextMacroID = FirstMacroID;
3394   NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3395 }
3396 
3397 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3398   IdentifierIDs[II] = ID;
3399 }
3400 
3401 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3402   // Always take the highest-numbered type index. This copes with an interesting
3403   // case for chained AST writing where we schedule writing the type and then,
3404   // later, deserialize the type from another AST. In this case, we want to
3405   // keep the higher-numbered entry so that we can properly write it out to
3406   // the AST file.
3407   TypeIdx &StoredIdx = TypeIdxs[T];
3408   if (Idx.getIndex() >= StoredIdx.getIndex())
3409     StoredIdx = Idx;
3410 }
3411 
3412 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3413   DeclIDs[D] = ID;
3414 }
3415 
3416 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3417   SelectorIDs[S] = ID;
3418 }
3419 
3420 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3421                                     MacroDefinition *MD) {
3422   MacroDefinitions[MD] = ID;
3423 }
3424 
3425 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3426   assert(D->isDefinition());
3427   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3428     // We are interested when a PCH decl is modified.
3429     if (RD->getPCHLevel() > 0) {
3430       // A forward reference was mutated into a definition. Rewrite it.
3431       // FIXME: This happens during template instantiation, should we
3432       // have created a new definition decl instead ?
3433       RewriteDecl(RD);
3434     }
3435 
3436     for (CXXRecordDecl::redecl_iterator
3437            I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3438       CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3439       if (Redecl == RD)
3440         continue;
3441 
3442       // We are interested when a PCH decl is modified.
3443       if (Redecl->getPCHLevel() > 0) {
3444         UpdateRecord &Record = DeclUpdates[Redecl];
3445         Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3446         assert(Redecl->DefinitionData);
3447         assert(Redecl->DefinitionData->Definition == D);
3448         AddDeclRef(D, Record); // the DefinitionDecl
3449       }
3450     }
3451   }
3452 }
3453 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
3454   // TU and namespaces are handled elsewhere.
3455   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
3456     return;
3457 
3458   if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
3459     return; // Not a source decl added to a DeclContext from PCH.
3460 
3461   AddUpdatedDeclContext(DC);
3462 }
3463 
3464 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
3465   assert(D->isImplicit());
3466   if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
3467     return; // Not a source member added to a class from PCH.
3468   if (!isa<CXXMethodDecl>(D))
3469     return; // We are interested in lazily declared implicit methods.
3470 
3471   // A decl coming from PCH was modified.
3472   assert(RD->isDefinition());
3473   UpdateRecord &Record = DeclUpdates[RD];
3474   Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
3475   AddDeclRef(D, Record);
3476 }
3477 
3478 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
3479                                      const ClassTemplateSpecializationDecl *D) {
3480   // The specializations set is kept in the canonical template.
3481   TD = TD->getCanonicalDecl();
3482   if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
3483     return; // Not a source specialization added to a template from PCH.
3484 
3485   UpdateRecord &Record = DeclUpdates[TD];
3486   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
3487   AddDeclRef(D, Record);
3488 }
3489 
3490 ASTSerializationListener::~ASTSerializationListener() { }
3491