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