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