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