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