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