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