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