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