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