ASTWriter.cpp revision f90b27ad077c3339b62befc892382845339f9490
1a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
2a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
3a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
4a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
5a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
6a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// License. See LICENSE.TXT for details.
7a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
8a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
9a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
10a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//  This file defines the ASTWriter class, which writes AST files.
11a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
12a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
13a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
14a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Serialization/ASTWriter.h"
15a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Serialization/ASTSerializationListener.h"
16a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "ASTCommon.h"
17a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Sema/Sema.h"
18cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "clang/Sema/IdentifierResolver.h"
191320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/ASTContext.h"
20a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/Decl.h"
21a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclContextInternals.h"
22a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclTemplate.h"
23a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclFriend.h"
24a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/Expr.h"
251320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/ExprCXX.h"
26a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/Type.h"
271320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/TypeLocVisitor.h"
281320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Serialization/ASTReader.h"
29a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Lex/MacroInfo.h"
301320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Lex/PreprocessingRecord.h"
311320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Lex/Preprocessor.h"
321320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Lex/HeaderSearch.h"
33a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/FileManager.h"
34a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/FileSystemStatCache.h"
35a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/OnDiskHashTable.h"
36a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/SourceManager.h"
37a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/SourceManagerInternals.h"
38a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/TargetInfo.h"
39a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/Version.h"
40a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/ADT/APFloat.h"
411320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/APInt.h"
421320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/StringExtras.h"
431320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/Bitcode/BitstreamWriter.h"
441320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/Support/FileSystem.h"
451320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/Support/MemoryBuffer.h"
461320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/Support/Path.h"
47a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include <cstdio>
481320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucciusing namespace clang;
49a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)using namespace clang::serialization;
501320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
51a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)template <typename T, typename Allocator>
52a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)T *data(std::vector<T, Allocator> &v) {
53a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return v.empty() ? 0 : &v.front();
54a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
55a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)template <typename T, typename Allocator>
56a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)const T *data(const std::vector<T, Allocator> &v) {
57a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return v.empty() ? 0 : &v.front();
581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
591320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
601320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===//
611320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci// Type serialization
621320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===//
631320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
641320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccinamespace {
651320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  class ASTTypeWriter {
661320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    ASTWriter &Writer;
671320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    ASTWriter::RecordDataImpl &Record;
68a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
69a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  public:
7046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    /// \brief Type code that corresponds to the record generated.
7146d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    TypeCode Code;
721320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
741320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci      : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
751320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
761320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    void VisitArrayType(const ArrayType *T);
771320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    void VisitFunctionType(const FunctionType *T);
781320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    void VisitTagType(const TagType *T);
79a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
80a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
81a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define ABSTRACT_TYPE(Class, Base)
821320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/TypeNodes.def"
83a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  };
84a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
85a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
86a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
87a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  assert(false && "Built-in types are never serialized");
88a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
89a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
90a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
915f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  Writer.AddTypeRef(T->getElementType(), Record);
925f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  Code = TYPE_COMPLEX;
931320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
941320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
951320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitPointerType(const PointerType *T) {
961320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getPointeeType(), Record);
975f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  Code = TYPE_POINTER;
985f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)}
991320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1001320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
1015f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  Writer.AddTypeRef(T->getPointeeType(), Record);
1021320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_BLOCK_POINTER;
1031320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1041320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1051320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
1061320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getPointeeType(), Record);
1071320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_LVALUE_REFERENCE;
1081320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1091320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1101320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
1111320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getPointeeType(), Record);
1121320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_RVALUE_REFERENCE;
1131320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1141320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1151320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
1161320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getPointeeType(), Record);
1171320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
1185f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  Code = TYPE_MEMBER_POINTER;
1191320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1205f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)
1211320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitArrayType(const ArrayType *T) {
122a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getElementType(), Record);
123a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getSizeModifier()); // FIXME: stable values
12446d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
1251320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1261320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
127a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
128a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  VisitArrayType(T);
1291320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddAPInt(T->getSize(), Record);
1301320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_CONSTANT_ARRAY;
131cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
132a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
133a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1341320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  VisitArrayType(T);
1351320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_INCOMPLETE_ARRAY;
136a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
137a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
138a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
1391320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  VisitArrayType(T);
1401320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceLocation(T->getLBracketLoc(), Record);
1411320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceLocation(T->getRBracketLoc(), Record);
1421320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddStmt(T->getSizeExpr());
1431320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_VARIABLE_ARRAY;
1441320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1451320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1461320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitVectorType(const VectorType *T) {
1471320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getElementType(), Record);
1481320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getNumElements());
1491320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getVectorKind());
1501320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_VECTOR;
1511320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1521320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1531320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
1541320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  VisitVectorType(T);
1551320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_EXT_VECTOR;
1561320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1571320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
159a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getResultType(), Record);
160a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  FunctionType::ExtInfo C = T->getExtInfo();
161a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(C.getNoReturn());
162a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(C.getRegParm());
163a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // FIXME: need to stabilize encoding of calling convention...
1641320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(C.getCC());
1651320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1661320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1671320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
168a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  VisitFunctionType(T);
169a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_FUNCTION_NO_PROTO;
170a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
171a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
1721320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
1731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  VisitFunctionType(T);
1741320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getNumArgs());
1751320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
1761320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    Writer.AddTypeRef(T->getArgType(I), Record);
177a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->isVariadic());
178a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getTypeQuals());
179cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Record.push_back(T->hasExceptionSpec());
180a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->hasAnyExceptionSpec());
1811320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getNumExceptions());
1821320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
1831320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    Writer.AddTypeRef(T->getExceptionType(I), Record);
1841320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_FUNCTION_PROTO;
1851320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
1861320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
187a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
188a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddDeclRef(T->getDecl(), Record);
189cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Code = TYPE_UNRESOLVED_USING;
190cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
1911320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1921320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
1931320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddDeclRef(T->getDecl(), Record);
1941320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
195cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
1961320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_TYPEDEF;
197cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
1981320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1991320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
200cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Writer.AddStmt(T->getUnderlyingExpr());
2011320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_TYPEOF_EXPR;
2021320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2031320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2041320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
2051320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getUnderlyingType(), Record);
2061320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_TYPEOF;
2071320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2081320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2091320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
2101320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddStmt(T->getUnderlyingExpr());
2111320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_DECLTYPE;
2121320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2131320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2141320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitTagType(const TagType *T) {
215cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Record.push_back(T->isDependentType());
216cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Writer.AddDeclRef(T->getDecl(), Record);
217cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  assert(!T->isBeingDefined() &&
218cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)         "Cannot serialize in the middle of a type definition");
219cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
220a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
2215c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liuvoid ASTTypeWriter::VisitRecordType(const RecordType *T) {
2225c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  VisitTagType(T);
2235c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  Code = TYPE_RECORD;
2245c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu}
225a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
226a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitEnumType(const EnumType *T) {
227a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  VisitTagType(T);
228cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Code = TYPE_ENUM;
229cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
230cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
231cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)void
23203b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)ASTTypeWriter::VisitSubstTemplateTypeParmType(
233cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)                                        const SubstTemplateTypeParmType *T) {
234a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
235a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getReplacementType(), Record);
236cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
2371320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2381320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2391320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid
2401320f92c476a1ad9d19dba2a48c72b75566198e9Primiano TucciASTTypeWriter::VisitTemplateSpecializationType(
2411320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci                                       const TemplateSpecializationType *T) {
2421320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->isDependentType());
2431320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTemplateName(T->getTemplateName(), Record);
2441320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getNumArgs());
2451320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
2461320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci         ArgI != ArgE; ++ArgI)
2471320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    Writer.AddTemplateArgument(*ArgI, Record);
2481320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
2491320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci                                                : T->getCanonicalTypeInternal(),
2501320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci                    Record);
2511320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_TEMPLATE_SPECIALIZATION;
2521320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2531320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
254e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdochvoid
255e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen MurdochASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
256a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  VisitArrayType(T);
257a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddStmt(T->getSizeExpr());
2581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceRange(T->getBracketsRange(), Record);
2591320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_DEPENDENT_SIZED_ARRAY;
2601320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
2611320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2621320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid
2631320f92c476a1ad9d19dba2a48c72b75566198e9Primiano TucciASTTypeWriter::VisitDependentSizedExtVectorType(
264a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                        const DependentSizedExtVectorType *T) {
265a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // FIXME: Serialize this type (C++ only)
266cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  assert(false && "Cannot serialize dependent sized extended vector types");
267a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
2681320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
2691320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid
2701320f92c476a1ad9d19dba2a48c72b75566198e9Primiano TucciASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2711320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getDepth());
2721320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getIndex());
2731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->isParameterPack());
2741320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddIdentifierRef(T->getName(), Record);
275a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_TEMPLATE_TYPE_PARM;
276a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
277a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
278a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void
279a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
280a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getKeyword());
281a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
282cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Writer.AddIdentifierRef(T->getIdentifier(), Record);
283cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
284a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                                : T->getCanonicalTypeInternal(),
285a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                    Record);
286010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  Code = TYPE_DEPENDENT_NAME;
287010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)}
2881320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
289a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void
290a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTTypeWriter::VisitDependentTemplateSpecializationType(
291a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                const DependentTemplateSpecializationType *T) {
292a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getKeyword());
293c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
2941320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddIdentifierRef(T->getIdentifier(), Record);
2951320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Record.push_back(T->getNumArgs());
296cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  for (DependentTemplateSpecializationType::iterator
2971320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci         I = T->begin(), E = T->end(); I != E; ++I)
298c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    Writer.AddTemplateArgument(*I, Record);
299a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
300a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
301cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
302c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdochvoid ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
303a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getPattern(), Record);
304a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_PACK_EXPANSION;
305cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
306a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
3071320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitParenType(const ParenType *T) {
308a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getInnerType(), Record);
309a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_PAREN;
310a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
311cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
312a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
313a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getKeyword());
3141320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
315a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getNamedType(), Record);
316a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_ELABORATED;
3171320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3181320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
3191320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
3201320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddDeclRef(T->getDecl(), Record);
3211320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
3221320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Code = TYPE_INJECTED_CLASS_NAME;
3231320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3241320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
3251320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
3261320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddDeclRef(T->getDecl(), Record);
327a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_OBJC_INTERFACE;
328a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
329cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
330cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
331a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getBaseType(), Record);
332a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Record.push_back(T->getNumProtocols());
3331320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  for (ObjCObjectType::qual_iterator I = T->qual_begin(),
334cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)       E = T->qual_end(); I != E; ++I)
335a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    Writer.AddDeclRef(*I, Record);
336cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Code = TYPE_OBJC_OBJECT;
337a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
338a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
339a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void
340a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
341a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddTypeRef(T->getPointeeType(), Record);
342a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Code = TYPE_OBJC_OBJECT_POINTER;
343a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
344a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
345a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)namespace {
346a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
347a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
348a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  ASTWriter &Writer;
349a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  ASTWriter::RecordDataImpl &Record;
3501320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
351a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)public:
352a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
353a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    : Writer(Writer), Record(Record) { }
354a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
355a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define ABSTRACT_TYPELOC(CLASS, PARENT)
356a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define TYPELOC(CLASS, PARENT) \
357a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/AST/TypeLocNodes.def"
3591320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
360a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
361a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
362e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch};
363e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch
364e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch}
365cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
3661320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3671320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  // nothing to do
3681320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3691320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
370a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
3711320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  if (TL.needsExtraLocalData()) {
372a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    Record.push_back(TL.getWrittenTypeSpec());
3731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci    Record.push_back(TL.getWrittenSignSpec());
374cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    Record.push_back(TL.getWrittenWidthSpec());
375e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch    Record.push_back(TL.hasModeAttr());
3761320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  }
3771320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
378e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdochvoid TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
379a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddSourceLocation(TL.getNameLoc(), Record);
380a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
381116680a4aac90f2aa7413d9095a592090648e557Ben Murdochvoid TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
382116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  Writer.AddSourceLocation(TL.getStarLoc(), Record);
3831320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3841320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3851320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceLocation(TL.getCaretLoc(), Record);
3861320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3871320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3881320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceLocation(TL.getAmpLoc(), Record);
3891320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci}
3901320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3911320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
392116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch}
393116680a4aac90f2aa7413d9095a592090648e557Ben Murdochvoid TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
394a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Writer.AddSourceLocation(TL.getStarLoc(), Record);
395}
396void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
397  Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
398  Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
399  Record.push_back(TL.getSizeExpr() ? 1 : 0);
400  if (TL.getSizeExpr())
401    Writer.AddStmt(TL.getSizeExpr());
402}
403void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
404  VisitArrayTypeLoc(TL);
405}
406void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
407  VisitArrayTypeLoc(TL);
408}
409void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
410  VisitArrayTypeLoc(TL);
411}
412void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
413                                            DependentSizedArrayTypeLoc TL) {
414  VisitArrayTypeLoc(TL);
415}
416void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
417                                        DependentSizedExtVectorTypeLoc TL) {
418  Writer.AddSourceLocation(TL.getNameLoc(), Record);
419}
420void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
421  Writer.AddSourceLocation(TL.getNameLoc(), Record);
422}
423void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
424  Writer.AddSourceLocation(TL.getNameLoc(), Record);
425}
426void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
427  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
428  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
429  Record.push_back(TL.getTrailingReturn());
430  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
431    Writer.AddDeclRef(TL.getArg(i), Record);
432}
433void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
434  VisitFunctionTypeLoc(TL);
435}
436void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
437  VisitFunctionTypeLoc(TL);
438}
439void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
440  Writer.AddSourceLocation(TL.getNameLoc(), Record);
441}
442void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
443  Writer.AddSourceLocation(TL.getNameLoc(), Record);
444}
445void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
446  Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
447  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
448  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
449}
450void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
451  Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
452  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
453  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
454  Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
455}
456void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
457  Writer.AddSourceLocation(TL.getNameLoc(), Record);
458}
459void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
460  Writer.AddSourceLocation(TL.getNameLoc(), Record);
461}
462void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
463  Writer.AddSourceLocation(TL.getNameLoc(), Record);
464}
465void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
466  Writer.AddSourceLocation(TL.getNameLoc(), Record);
467}
468void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
469                                            SubstTemplateTypeParmTypeLoc TL) {
470  Writer.AddSourceLocation(TL.getNameLoc(), Record);
471}
472void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
473                                           TemplateSpecializationTypeLoc TL) {
474  Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
475  Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
476  Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
477  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
478    Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
479                                      TL.getArgLoc(i).getLocInfo(), Record);
480}
481void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
482  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
483  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
484}
485void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
486  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
487  Writer.AddSourceRange(TL.getQualifierRange(), Record);
488}
489void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
490  Writer.AddSourceLocation(TL.getNameLoc(), Record);
491}
492void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
493  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
494  Writer.AddSourceRange(TL.getQualifierRange(), Record);
495  Writer.AddSourceLocation(TL.getNameLoc(), Record);
496}
497void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
498       DependentTemplateSpecializationTypeLoc TL) {
499  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
500  Writer.AddSourceRange(TL.getQualifierRange(), Record);
501  Writer.AddSourceLocation(TL.getNameLoc(), Record);
502  Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
503  Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
504  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
505    Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
506                                      TL.getArgLoc(I).getLocInfo(), Record);
507}
508void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
509  Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
510}
511void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
512  Writer.AddSourceLocation(TL.getNameLoc(), Record);
513}
514void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
515  Record.push_back(TL.hasBaseTypeAsWritten());
516  Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
517  Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
518  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
519    Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
520}
521void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
522  Writer.AddSourceLocation(TL.getStarLoc(), Record);
523}
524
525//===----------------------------------------------------------------------===//
526// ASTWriter Implementation
527//===----------------------------------------------------------------------===//
528
529static void EmitBlockID(unsigned ID, const char *Name,
530                        llvm::BitstreamWriter &Stream,
531                        ASTWriter::RecordDataImpl &Record) {
532  Record.clear();
533  Record.push_back(ID);
534  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
535
536  // Emit the block name if present.
537  if (Name == 0 || Name[0] == 0) return;
538  Record.clear();
539  while (*Name)
540    Record.push_back(*Name++);
541  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
542}
543
544static void EmitRecordID(unsigned ID, const char *Name,
545                         llvm::BitstreamWriter &Stream,
546                         ASTWriter::RecordDataImpl &Record) {
547  Record.clear();
548  Record.push_back(ID);
549  while (*Name)
550    Record.push_back(*Name++);
551  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
552}
553
554static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
555                          ASTWriter::RecordDataImpl &Record) {
556#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
557  RECORD(STMT_STOP);
558  RECORD(STMT_NULL_PTR);
559  RECORD(STMT_NULL);
560  RECORD(STMT_COMPOUND);
561  RECORD(STMT_CASE);
562  RECORD(STMT_DEFAULT);
563  RECORD(STMT_LABEL);
564  RECORD(STMT_IF);
565  RECORD(STMT_SWITCH);
566  RECORD(STMT_WHILE);
567  RECORD(STMT_DO);
568  RECORD(STMT_FOR);
569  RECORD(STMT_GOTO);
570  RECORD(STMT_INDIRECT_GOTO);
571  RECORD(STMT_CONTINUE);
572  RECORD(STMT_BREAK);
573  RECORD(STMT_RETURN);
574  RECORD(STMT_DECL);
575  RECORD(STMT_ASM);
576  RECORD(EXPR_PREDEFINED);
577  RECORD(EXPR_DECL_REF);
578  RECORD(EXPR_INTEGER_LITERAL);
579  RECORD(EXPR_FLOATING_LITERAL);
580  RECORD(EXPR_IMAGINARY_LITERAL);
581  RECORD(EXPR_STRING_LITERAL);
582  RECORD(EXPR_CHARACTER_LITERAL);
583  RECORD(EXPR_PAREN);
584  RECORD(EXPR_UNARY_OPERATOR);
585  RECORD(EXPR_SIZEOF_ALIGN_OF);
586  RECORD(EXPR_ARRAY_SUBSCRIPT);
587  RECORD(EXPR_CALL);
588  RECORD(EXPR_MEMBER);
589  RECORD(EXPR_BINARY_OPERATOR);
590  RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
591  RECORD(EXPR_CONDITIONAL_OPERATOR);
592  RECORD(EXPR_IMPLICIT_CAST);
593  RECORD(EXPR_CSTYLE_CAST);
594  RECORD(EXPR_COMPOUND_LITERAL);
595  RECORD(EXPR_EXT_VECTOR_ELEMENT);
596  RECORD(EXPR_INIT_LIST);
597  RECORD(EXPR_DESIGNATED_INIT);
598  RECORD(EXPR_IMPLICIT_VALUE_INIT);
599  RECORD(EXPR_VA_ARG);
600  RECORD(EXPR_ADDR_LABEL);
601  RECORD(EXPR_STMT);
602  RECORD(EXPR_CHOOSE);
603  RECORD(EXPR_GNU_NULL);
604  RECORD(EXPR_SHUFFLE_VECTOR);
605  RECORD(EXPR_BLOCK);
606  RECORD(EXPR_BLOCK_DECL_REF);
607  RECORD(EXPR_OBJC_STRING_LITERAL);
608  RECORD(EXPR_OBJC_ENCODE);
609  RECORD(EXPR_OBJC_SELECTOR_EXPR);
610  RECORD(EXPR_OBJC_PROTOCOL_EXPR);
611  RECORD(EXPR_OBJC_IVAR_REF_EXPR);
612  RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
613  RECORD(EXPR_OBJC_KVC_REF_EXPR);
614  RECORD(EXPR_OBJC_MESSAGE_EXPR);
615  RECORD(STMT_OBJC_FOR_COLLECTION);
616  RECORD(STMT_OBJC_CATCH);
617  RECORD(STMT_OBJC_FINALLY);
618  RECORD(STMT_OBJC_AT_TRY);
619  RECORD(STMT_OBJC_AT_SYNCHRONIZED);
620  RECORD(STMT_OBJC_AT_THROW);
621  RECORD(EXPR_CXX_OPERATOR_CALL);
622  RECORD(EXPR_CXX_CONSTRUCT);
623  RECORD(EXPR_CXX_STATIC_CAST);
624  RECORD(EXPR_CXX_DYNAMIC_CAST);
625  RECORD(EXPR_CXX_REINTERPRET_CAST);
626  RECORD(EXPR_CXX_CONST_CAST);
627  RECORD(EXPR_CXX_FUNCTIONAL_CAST);
628  RECORD(EXPR_CXX_BOOL_LITERAL);
629  RECORD(EXPR_CXX_NULL_PTR_LITERAL);
630#undef RECORD
631}
632
633void ASTWriter::WriteBlockInfoBlock() {
634  RecordData Record;
635  Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
636
637#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
638#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
639
640  // AST Top-Level Block.
641  BLOCK(AST_BLOCK);
642  RECORD(ORIGINAL_FILE_NAME);
643  RECORD(TYPE_OFFSET);
644  RECORD(DECL_OFFSET);
645  RECORD(LANGUAGE_OPTIONS);
646  RECORD(METADATA);
647  RECORD(IDENTIFIER_OFFSET);
648  RECORD(IDENTIFIER_TABLE);
649  RECORD(EXTERNAL_DEFINITIONS);
650  RECORD(SPECIAL_TYPES);
651  RECORD(STATISTICS);
652  RECORD(TENTATIVE_DEFINITIONS);
653  RECORD(UNUSED_FILESCOPED_DECLS);
654  RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
655  RECORD(SELECTOR_OFFSETS);
656  RECORD(METHOD_POOL);
657  RECORD(PP_COUNTER_VALUE);
658  RECORD(SOURCE_LOCATION_OFFSETS);
659  RECORD(SOURCE_LOCATION_PRELOADS);
660  RECORD(STAT_CACHE);
661  RECORD(EXT_VECTOR_DECLS);
662  RECORD(VERSION_CONTROL_BRANCH_REVISION);
663  RECORD(MACRO_DEFINITION_OFFSETS);
664  RECORD(CHAINED_METADATA);
665  RECORD(REFERENCED_SELECTOR_POOL);
666
667  // SourceManager Block.
668  BLOCK(SOURCE_MANAGER_BLOCK);
669  RECORD(SM_SLOC_FILE_ENTRY);
670  RECORD(SM_SLOC_BUFFER_ENTRY);
671  RECORD(SM_SLOC_BUFFER_BLOB);
672  RECORD(SM_SLOC_INSTANTIATION_ENTRY);
673  RECORD(SM_LINE_TABLE);
674
675  // Preprocessor Block.
676  BLOCK(PREPROCESSOR_BLOCK);
677  RECORD(PP_MACRO_OBJECT_LIKE);
678  RECORD(PP_MACRO_FUNCTION_LIKE);
679  RECORD(PP_TOKEN);
680  RECORD(PP_MACRO_INSTANTIATION);
681  RECORD(PP_MACRO_DEFINITION);
682
683  // Decls and Types block.
684  BLOCK(DECLTYPES_BLOCK);
685  RECORD(TYPE_EXT_QUAL);
686  RECORD(TYPE_COMPLEX);
687  RECORD(TYPE_POINTER);
688  RECORD(TYPE_BLOCK_POINTER);
689  RECORD(TYPE_LVALUE_REFERENCE);
690  RECORD(TYPE_RVALUE_REFERENCE);
691  RECORD(TYPE_MEMBER_POINTER);
692  RECORD(TYPE_CONSTANT_ARRAY);
693  RECORD(TYPE_INCOMPLETE_ARRAY);
694  RECORD(TYPE_VARIABLE_ARRAY);
695  RECORD(TYPE_VECTOR);
696  RECORD(TYPE_EXT_VECTOR);
697  RECORD(TYPE_FUNCTION_PROTO);
698  RECORD(TYPE_FUNCTION_NO_PROTO);
699  RECORD(TYPE_TYPEDEF);
700  RECORD(TYPE_TYPEOF_EXPR);
701  RECORD(TYPE_TYPEOF);
702  RECORD(TYPE_RECORD);
703  RECORD(TYPE_ENUM);
704  RECORD(TYPE_OBJC_INTERFACE);
705  RECORD(TYPE_OBJC_OBJECT);
706  RECORD(TYPE_OBJC_OBJECT_POINTER);
707  RECORD(DECL_TRANSLATION_UNIT);
708  RECORD(DECL_TYPEDEF);
709  RECORD(DECL_ENUM);
710  RECORD(DECL_RECORD);
711  RECORD(DECL_ENUM_CONSTANT);
712  RECORD(DECL_FUNCTION);
713  RECORD(DECL_OBJC_METHOD);
714  RECORD(DECL_OBJC_INTERFACE);
715  RECORD(DECL_OBJC_PROTOCOL);
716  RECORD(DECL_OBJC_IVAR);
717  RECORD(DECL_OBJC_AT_DEFS_FIELD);
718  RECORD(DECL_OBJC_CLASS);
719  RECORD(DECL_OBJC_FORWARD_PROTOCOL);
720  RECORD(DECL_OBJC_CATEGORY);
721  RECORD(DECL_OBJC_CATEGORY_IMPL);
722  RECORD(DECL_OBJC_IMPLEMENTATION);
723  RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
724  RECORD(DECL_OBJC_PROPERTY);
725  RECORD(DECL_OBJC_PROPERTY_IMPL);
726  RECORD(DECL_FIELD);
727  RECORD(DECL_VAR);
728  RECORD(DECL_IMPLICIT_PARAM);
729  RECORD(DECL_PARM_VAR);
730  RECORD(DECL_FILE_SCOPE_ASM);
731  RECORD(DECL_BLOCK);
732  RECORD(DECL_CONTEXT_LEXICAL);
733  RECORD(DECL_CONTEXT_VISIBLE);
734  // Statements and Exprs can occur in the Decls and Types block.
735  AddStmtsExprs(Stream, Record);
736#undef RECORD
737#undef BLOCK
738  Stream.ExitBlock();
739}
740
741/// \brief Adjusts the given filename to only write out the portion of the
742/// filename that is not part of the system root directory.
743///
744/// \param Filename the file name to adjust.
745///
746/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
747/// the returned filename will be adjusted by this system root.
748///
749/// \returns either the original filename (if it needs no adjustment) or the
750/// adjusted filename (which points into the @p Filename parameter).
751static const char *
752adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
753  assert(Filename && "No file name to adjust?");
754
755  if (!isysroot)
756    return Filename;
757
758  // Verify that the filename and the system root have the same prefix.
759  unsigned Pos = 0;
760  for (; Filename[Pos] && isysroot[Pos]; ++Pos)
761    if (Filename[Pos] != isysroot[Pos])
762      return Filename; // Prefixes don't match.
763
764  // We hit the end of the filename before we hit the end of the system root.
765  if (!Filename[Pos])
766    return Filename;
767
768  // If the file name has a '/' at the current position, skip over the '/'.
769  // We distinguish sysroot-based includes from absolute includes by the
770  // absence of '/' at the beginning of sysroot-based includes.
771  if (Filename[Pos] == '/')
772    ++Pos;
773
774  return Filename + Pos;
775}
776
777/// \brief Write the AST metadata (e.g., i686-apple-darwin9).
778void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
779  using namespace llvm;
780
781  // Metadata
782  const TargetInfo &Target = Context.Target;
783  BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
784  MetaAbbrev->Add(BitCodeAbbrevOp(
785                    Chain ? CHAINED_METADATA : METADATA));
786  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
787  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
788  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
789  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
790  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
791  // Target triple or chained PCH name
792  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
793  unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
794
795  RecordData Record;
796  Record.push_back(Chain ? CHAINED_METADATA : METADATA);
797  Record.push_back(VERSION_MAJOR);
798  Record.push_back(VERSION_MINOR);
799  Record.push_back(CLANG_VERSION_MAJOR);
800  Record.push_back(CLANG_VERSION_MINOR);
801  Record.push_back(isysroot != 0);
802  // FIXME: This writes the absolute path for chained headers.
803  const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
804  Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
805
806  // Original file name
807  SourceManager &SM = Context.getSourceManager();
808  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
809    BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
810    FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
811    FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
812    unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
813
814    llvm::SmallString<128> MainFilePath(MainFile->getName());
815
816    llvm::sys::fs::make_absolute(MainFilePath);
817
818    const char *MainFileNameStr = MainFilePath.c_str();
819    MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
820                                                      isysroot);
821    RecordData Record;
822    Record.push_back(ORIGINAL_FILE_NAME);
823    Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
824  }
825
826  // Repository branch/version information.
827  BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
828  RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
829  RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
830  unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
831  Record.clear();
832  Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
833  Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
834                            getClangFullRepositoryVersion());
835}
836
837/// \brief Write the LangOptions structure.
838void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
839  RecordData Record;
840  Record.push_back(LangOpts.Trigraphs);
841  Record.push_back(LangOpts.BCPLComment);  // BCPL-style '//' comments.
842  Record.push_back(LangOpts.DollarIdents);  // '$' allowed in identifiers.
843  Record.push_back(LangOpts.AsmPreprocessor);  // Preprocessor in asm mode.
844  Record.push_back(LangOpts.GNUMode);  // True in gnu99 mode false in c99 mode (etc)
845  Record.push_back(LangOpts.GNUKeywords);  // Allow GNU-extension keywords
846  Record.push_back(LangOpts.ImplicitInt);  // C89 implicit 'int'.
847  Record.push_back(LangOpts.Digraphs);  // C94, C99 and C++
848  Record.push_back(LangOpts.HexFloats);  // C99 Hexadecimal float constants.
849  Record.push_back(LangOpts.C99);  // C99 Support
850  Record.push_back(LangOpts.Microsoft);  // Microsoft extensions.
851  // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
852  // already saved elsewhere.
853  Record.push_back(LangOpts.CPlusPlus);  // C++ Support
854  Record.push_back(LangOpts.CPlusPlus0x);  // C++0x Support
855  Record.push_back(LangOpts.CXXOperatorNames);  // Treat C++ operator names as keywords.
856
857  Record.push_back(LangOpts.ObjC1);  // Objective-C 1 support enabled.
858  Record.push_back(LangOpts.ObjC2);  // Objective-C 2 support enabled.
859  Record.push_back(LangOpts.ObjCNonFragileABI);  // Objective-C
860                                                 // modern abi enabled.
861  Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
862                                                 // modern abi enabled.
863  Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
864                                                      // properties enabled.
865  Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
866
867  Record.push_back(LangOpts.PascalStrings);  // Allow Pascal strings
868  Record.push_back(LangOpts.WritableStrings);  // Allow writable strings
869  Record.push_back(LangOpts.LaxVectorConversions);
870  Record.push_back(LangOpts.AltiVec);
871  Record.push_back(LangOpts.Exceptions);  // Support exception handling.
872  Record.push_back(LangOpts.SjLjExceptions);
873
874  Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
875  Record.push_back(LangOpts.Freestanding); // Freestanding implementation
876  Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
877
878  // Whether static initializers are protected by locks.
879  Record.push_back(LangOpts.ThreadsafeStatics);
880  Record.push_back(LangOpts.POSIXThreads);
881  Record.push_back(LangOpts.Blocks); // block extension to C
882  Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
883                                  // they are unused.
884  Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
885                                  // (modulo the platform support).
886
887  Record.push_back(LangOpts.getSignedOverflowBehavior());
888  Record.push_back(LangOpts.HeinousExtensions);
889
890  Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
891  Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
892                                  // defined.
893  Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
894                                  // opposed to __DYNAMIC__).
895  Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
896
897  Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
898                                  // used (instead of C99 semantics).
899  Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
900  Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
901                                            // be enabled.
902  Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
903                                           // unsigned type
904  Record.push_back(LangOpts.ShortWChar);  // force wchar_t to be unsigned short
905  Record.push_back(LangOpts.getGCMode());
906  Record.push_back(LangOpts.getVisibilityMode());
907  Record.push_back(LangOpts.getStackProtectorMode());
908  Record.push_back(LangOpts.InstantiationDepth);
909  Record.push_back(LangOpts.OpenCL);
910  Record.push_back(LangOpts.CUDA);
911  Record.push_back(LangOpts.CatchUndefined);
912  Record.push_back(LangOpts.ElideConstructors);
913  Record.push_back(LangOpts.SpellChecking);
914  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
915}
916
917//===----------------------------------------------------------------------===//
918// stat cache Serialization
919//===----------------------------------------------------------------------===//
920
921namespace {
922// Trait used for the on-disk hash table of stat cache results.
923class ASTStatCacheTrait {
924public:
925  typedef const char * key_type;
926  typedef key_type key_type_ref;
927
928  typedef struct stat data_type;
929  typedef const data_type &data_type_ref;
930
931  static unsigned ComputeHash(const char *path) {
932    return llvm::HashString(path);
933  }
934
935  std::pair<unsigned,unsigned>
936    EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
937                      data_type_ref Data) {
938    unsigned StrLen = strlen(path);
939    clang::io::Emit16(Out, StrLen);
940    unsigned DataLen = 4 + 4 + 2 + 8 + 8;
941    clang::io::Emit8(Out, DataLen);
942    return std::make_pair(StrLen + 1, DataLen);
943  }
944
945  void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
946    Out.write(path, KeyLen);
947  }
948
949  void EmitData(llvm::raw_ostream &Out, key_type_ref,
950                data_type_ref Data, unsigned DataLen) {
951    using namespace clang::io;
952    uint64_t Start = Out.tell(); (void)Start;
953
954    Emit32(Out, (uint32_t) Data.st_ino);
955    Emit32(Out, (uint32_t) Data.st_dev);
956    Emit16(Out, (uint16_t) Data.st_mode);
957    Emit64(Out, (uint64_t) Data.st_mtime);
958    Emit64(Out, (uint64_t) Data.st_size);
959
960    assert(Out.tell() - Start == DataLen && "Wrong data length");
961  }
962};
963} // end anonymous namespace
964
965/// \brief Write the stat() system call cache to the AST file.
966void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
967  // Build the on-disk hash table containing information about every
968  // stat() call.
969  OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
970  unsigned NumStatEntries = 0;
971  for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
972                                StatEnd = StatCalls.end();
973       Stat != StatEnd; ++Stat, ++NumStatEntries) {
974    const char *Filename = Stat->first();
975    Generator.insert(Filename, Stat->second);
976  }
977
978  // Create the on-disk hash table in a buffer.
979  llvm::SmallString<4096> StatCacheData;
980  uint32_t BucketOffset;
981  {
982    llvm::raw_svector_ostream Out(StatCacheData);
983    // Make sure that no bucket is at offset 0
984    clang::io::Emit32(Out, 0);
985    BucketOffset = Generator.Emit(Out);
986  }
987
988  // Create a blob abbreviation
989  using namespace llvm;
990  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
991  Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
992  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
993  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
994  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
995  unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
996
997  // Write the stat cache
998  RecordData Record;
999  Record.push_back(STAT_CACHE);
1000  Record.push_back(BucketOffset);
1001  Record.push_back(NumStatEntries);
1002  Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// Source Manager Serialization
1007//===----------------------------------------------------------------------===//
1008
1009/// \brief Create an abbreviation for the SLocEntry that refers to a
1010/// file.
1011static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1012  using namespace llvm;
1013  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1014  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1015  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1016  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1017  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1018  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1019  // FileEntry fields.
1020  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1021  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1022  // HeaderFileInfo fields.
1023  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImport
1024  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // DirInfo
1025  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumIncludes
1026  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // ControllingMacro
1027  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1028  return Stream.EmitAbbrev(Abbrev);
1029}
1030
1031/// \brief Create an abbreviation for the SLocEntry that refers to a
1032/// buffer.
1033static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1034  using namespace llvm;
1035  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1036  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1037  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1038  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1039  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1040  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1041  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1042  return Stream.EmitAbbrev(Abbrev);
1043}
1044
1045/// \brief Create an abbreviation for the SLocEntry that refers to a
1046/// buffer's blob.
1047static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1048  using namespace llvm;
1049  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1050  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1051  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1052  return Stream.EmitAbbrev(Abbrev);
1053}
1054
1055/// \brief Create an abbreviation for the SLocEntry that refers to an
1056/// buffer.
1057static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
1058  using namespace llvm;
1059  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1060  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY));
1061  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1062  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1063  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1064  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1065  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1066  return Stream.EmitAbbrev(Abbrev);
1067}
1068
1069/// \brief Writes the block containing the serialized form of the
1070/// source manager.
1071///
1072/// TODO: We should probably use an on-disk hash table (stored in a
1073/// blob), indexed based on the file name, so that we only create
1074/// entries for files that we actually need. In the common case (no
1075/// errors), we probably won't have to create file entries for any of
1076/// the files in the AST.
1077void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1078                                        const Preprocessor &PP,
1079                                        const char *isysroot) {
1080  RecordData Record;
1081
1082  // Enter the source manager block.
1083  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1084
1085  // Abbreviations for the various kinds of source-location entries.
1086  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1087  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1088  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1089  unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
1090
1091  // Write the line table.
1092  if (SourceMgr.hasLineTable()) {
1093    LineTableInfo &LineTable = SourceMgr.getLineTable();
1094
1095    // Emit the file names
1096    Record.push_back(LineTable.getNumFilenames());
1097    for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1098      // Emit the file name
1099      const char *Filename = LineTable.getFilename(I);
1100      Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1101      unsigned FilenameLen = Filename? strlen(Filename) : 0;
1102      Record.push_back(FilenameLen);
1103      if (FilenameLen)
1104        Record.insert(Record.end(), Filename, Filename + FilenameLen);
1105    }
1106
1107    // Emit the line entries
1108    for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1109         L != LEnd; ++L) {
1110      // Emit the file ID
1111      Record.push_back(L->first);
1112
1113      // Emit the line entries
1114      Record.push_back(L->second.size());
1115      for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1116                                         LEEnd = L->second.end();
1117           LE != LEEnd; ++LE) {
1118        Record.push_back(LE->FileOffset);
1119        Record.push_back(LE->LineNo);
1120        Record.push_back(LE->FilenameID);
1121        Record.push_back((unsigned)LE->FileKind);
1122        Record.push_back(LE->IncludeOffset);
1123      }
1124    }
1125    Stream.EmitRecord(SM_LINE_TABLE, Record);
1126  }
1127
1128  // Write out the source location entry table. We skip the first
1129  // entry, which is always the same dummy entry.
1130  std::vector<uint32_t> SLocEntryOffsets;
1131  RecordData PreloadSLocs;
1132  unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1133  SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1134  for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1135       I != N; ++I) {
1136    // Get this source location entry.
1137    const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1138
1139    // Record the offset of this source-location entry.
1140    SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1141
1142    // Figure out which record code to use.
1143    unsigned Code;
1144    if (SLoc->isFile()) {
1145      if (SLoc->getFile().getContentCache()->Entry)
1146        Code = SM_SLOC_FILE_ENTRY;
1147      else
1148        Code = SM_SLOC_BUFFER_ENTRY;
1149    } else
1150      Code = SM_SLOC_INSTANTIATION_ENTRY;
1151    Record.clear();
1152    Record.push_back(Code);
1153
1154    Record.push_back(SLoc->getOffset());
1155    if (SLoc->isFile()) {
1156      const SrcMgr::FileInfo &File = SLoc->getFile();
1157      Record.push_back(File.getIncludeLoc().getRawEncoding());
1158      Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1159      Record.push_back(File.hasLineDirectives());
1160
1161      const SrcMgr::ContentCache *Content = File.getContentCache();
1162      if (Content->Entry) {
1163        // The source location entry is a file. The blob associated
1164        // with this entry is the file name.
1165
1166        // Emit size/modification time for this file.
1167        Record.push_back(Content->Entry->getSize());
1168        Record.push_back(Content->Entry->getModificationTime());
1169
1170        // Emit header-search information associated with this file.
1171        HeaderFileInfo HFI;
1172        HeaderSearch &HS = PP.getHeaderSearchInfo();
1173        if (Content->Entry->getUID() < HS.header_file_size())
1174          HFI = HS.header_file_begin()[Content->Entry->getUID()];
1175        Record.push_back(HFI.isImport);
1176        Record.push_back(HFI.DirInfo);
1177        Record.push_back(HFI.NumIncludes);
1178        AddIdentifierRef(HFI.ControllingMacro, Record);
1179
1180        // Turn the file name into an absolute path, if it isn't already.
1181        const char *Filename = Content->Entry->getName();
1182        llvm::SmallString<128> FilePath(Filename);
1183        llvm::sys::fs::make_absolute(FilePath);
1184        Filename = FilePath.c_str();
1185
1186        Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1187        Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1188
1189        // FIXME: For now, preload all file source locations, so that
1190        // we get the appropriate File entries in the reader. This is
1191        // a temporary measure.
1192        PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1193      } else {
1194        // The source location entry is a buffer. The blob associated
1195        // with this entry contains the contents of the buffer.
1196
1197        // We add one to the size so that we capture the trailing NULL
1198        // that is required by llvm::MemoryBuffer::getMemBuffer (on
1199        // the reader side).
1200        const llvm::MemoryBuffer *Buffer
1201          = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1202        const char *Name = Buffer->getBufferIdentifier();
1203        Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1204                                  llvm::StringRef(Name, strlen(Name) + 1));
1205        Record.clear();
1206        Record.push_back(SM_SLOC_BUFFER_BLOB);
1207        Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1208                                  llvm::StringRef(Buffer->getBufferStart(),
1209                                                  Buffer->getBufferSize() + 1));
1210
1211        if (strcmp(Name, "<built-in>") == 0)
1212          PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1213      }
1214    } else {
1215      // The source location entry is an instantiation.
1216      const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1217      Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1218      Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1219      Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1220
1221      // Compute the token length for this macro expansion.
1222      unsigned NextOffset = SourceMgr.getNextOffset();
1223      if (I + 1 != N)
1224        NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1225      Record.push_back(NextOffset - SLoc->getOffset() - 1);
1226      Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1227    }
1228  }
1229
1230  Stream.ExitBlock();
1231
1232  if (SLocEntryOffsets.empty())
1233    return;
1234
1235  // Write the source-location offsets table into the AST block. This
1236  // table is used for lazily loading source-location information.
1237  using namespace llvm;
1238  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1239  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1240  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1241  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1242  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1243  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1244
1245  Record.clear();
1246  Record.push_back(SOURCE_LOCATION_OFFSETS);
1247  Record.push_back(SLocEntryOffsets.size());
1248  unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1249  Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1250  Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1251                            (const char *)data(SLocEntryOffsets),
1252                           SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
1253
1254  // Write the source location entry preloads array, telling the AST
1255  // reader which source locations entries it should load eagerly.
1256  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1257}
1258
1259//===----------------------------------------------------------------------===//
1260// Preprocessor Serialization
1261//===----------------------------------------------------------------------===//
1262
1263/// \brief Writes the block containing the serialized form of the
1264/// preprocessor.
1265///
1266void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1267  RecordData Record;
1268
1269  // If the preprocessor __COUNTER__ value has been bumped, remember it.
1270  if (PP.getCounterValue() != 0) {
1271    Record.push_back(PP.getCounterValue());
1272    Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1273    Record.clear();
1274  }
1275
1276  // Enter the preprocessor block.
1277  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1278
1279  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1280  // FIXME: use diagnostics subsystem for localization etc.
1281  if (PP.SawDateOrTime())
1282    fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1283
1284
1285  // Loop over all the macro definitions that are live at the end of the file,
1286  // emitting each to the PP section.
1287  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1288  unsigned InclusionAbbrev = 0;
1289  if (PPRec) {
1290    using namespace llvm;
1291    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1292    Abbrev->Add(BitCodeAbbrevOp(PP_INCLUSION_DIRECTIVE));
1293    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1294    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1295    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1296    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1297    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1298    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1299    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1300    InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1301  }
1302
1303  for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1304       I != E; ++I) {
1305    // FIXME: This emits macros in hash table order, we should do it in a stable
1306    // order so that output is reproducible.
1307    MacroInfo *MI = I->second;
1308
1309    // Don't emit builtin macros like __LINE__ to the AST file unless they have
1310    // been redefined by the header (in which case they are not isBuiltinMacro).
1311    // Also skip macros from a AST file if we're chaining.
1312
1313    // FIXME: There is a (probably minor) optimization we could do here, if
1314    // the macro comes from the original PCH but the identifier comes from a
1315    // chained PCH, by storing the offset into the original PCH rather than
1316    // writing the macro definition a second time.
1317    if (MI->isBuiltinMacro() ||
1318        (Chain && I->first->isFromAST() && MI->isFromAST()))
1319      continue;
1320
1321    AddIdentifierRef(I->first, Record);
1322    MacroOffsets[I->first] = Stream.GetCurrentBitNo();
1323    Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1324    Record.push_back(MI->isUsed());
1325
1326    unsigned Code;
1327    if (MI->isObjectLike()) {
1328      Code = PP_MACRO_OBJECT_LIKE;
1329    } else {
1330      Code = PP_MACRO_FUNCTION_LIKE;
1331
1332      Record.push_back(MI->isC99Varargs());
1333      Record.push_back(MI->isGNUVarargs());
1334      Record.push_back(MI->getNumArgs());
1335      for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1336           I != E; ++I)
1337        AddIdentifierRef(*I, Record);
1338    }
1339
1340    // If we have a detailed preprocessing record, record the macro definition
1341    // ID that corresponds to this macro.
1342    if (PPRec)
1343      Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1344
1345    Stream.EmitRecord(Code, Record);
1346    Record.clear();
1347
1348    // Emit the tokens array.
1349    for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1350      // Note that we know that the preprocessor does not have any annotation
1351      // tokens in it because they are created by the parser, and thus can't be
1352      // in a macro definition.
1353      const Token &Tok = MI->getReplacementToken(TokNo);
1354
1355      Record.push_back(Tok.getLocation().getRawEncoding());
1356      Record.push_back(Tok.getLength());
1357
1358      // FIXME: When reading literal tokens, reconstruct the literal pointer if
1359      // it is needed.
1360      AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1361
1362      // FIXME: Should translate token kind to a stable encoding.
1363      Record.push_back(Tok.getKind());
1364      // FIXME: Should translate token flags to a stable encoding.
1365      Record.push_back(Tok.getFlags());
1366
1367      Stream.EmitRecord(PP_TOKEN, Record);
1368      Record.clear();
1369    }
1370    ++NumMacros;
1371  }
1372
1373  // If the preprocessor has a preprocessing record, emit it.
1374  unsigned NumPreprocessingRecords = 0;
1375  if (PPRec) {
1376    unsigned IndexBase = Chain ? PPRec->getNumPreallocatedEntities() : 0;
1377    for (PreprocessingRecord::iterator E = PPRec->begin(Chain),
1378                                       EEnd = PPRec->end(Chain);
1379         E != EEnd; ++E) {
1380      Record.clear();
1381
1382      if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1383        // Record this macro definition's location.
1384        MacroID ID = getMacroDefinitionID(MD);
1385
1386        // Don't write the macro definition if it is from another AST file.
1387        if (ID < FirstMacroID)
1388          continue;
1389
1390        // Notify the serialization listener that we're serializing this entity.
1391        if (SerializationListener)
1392          SerializationListener->SerializedPreprocessedEntity(*E,
1393                                                      Stream.GetCurrentBitNo());
1394
1395        unsigned Position = ID - FirstMacroID;
1396        if (Position != MacroDefinitionOffsets.size()) {
1397          if (Position > MacroDefinitionOffsets.size())
1398            MacroDefinitionOffsets.resize(Position + 1);
1399
1400          MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1401        } else
1402          MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1403
1404        Record.push_back(IndexBase + NumPreprocessingRecords++);
1405        Record.push_back(ID);
1406        AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1407        AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1408        AddIdentifierRef(MD->getName(), Record);
1409        AddSourceLocation(MD->getLocation(), Record);
1410        Stream.EmitRecord(PP_MACRO_DEFINITION, Record);
1411        continue;
1412      }
1413
1414      // Notify the serialization listener that we're serializing this entity.
1415      if (SerializationListener)
1416        SerializationListener->SerializedPreprocessedEntity(*E,
1417                                                      Stream.GetCurrentBitNo());
1418
1419      if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
1420        Record.push_back(IndexBase + NumPreprocessingRecords++);
1421        AddSourceLocation(MI->getSourceRange().getBegin(), Record);
1422        AddSourceLocation(MI->getSourceRange().getEnd(), Record);
1423        AddIdentifierRef(MI->getName(), Record);
1424        Record.push_back(getMacroDefinitionID(MI->getDefinition()));
1425        Stream.EmitRecord(PP_MACRO_INSTANTIATION, Record);
1426        continue;
1427      }
1428
1429      if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1430        Record.push_back(PP_INCLUSION_DIRECTIVE);
1431        Record.push_back(IndexBase + NumPreprocessingRecords++);
1432        AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1433        AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1434        Record.push_back(ID->getFileName().size());
1435        Record.push_back(ID->wasInQuotes());
1436        Record.push_back(static_cast<unsigned>(ID->getKind()));
1437        llvm::SmallString<64> Buffer;
1438        Buffer += ID->getFileName();
1439        Buffer += ID->getFile()->getName();
1440        Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1441        continue;
1442      }
1443
1444      llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1445    }
1446  }
1447
1448  Stream.ExitBlock();
1449
1450  // Write the offsets table for the preprocessing record.
1451  if (NumPreprocessingRecords > 0) {
1452    // Write the offsets table for identifier IDs.
1453    using namespace llvm;
1454    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1455    Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1456    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1457    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1458    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1459    unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1460
1461    Record.clear();
1462    Record.push_back(MACRO_DEFINITION_OFFSETS);
1463    Record.push_back(NumPreprocessingRecords);
1464    Record.push_back(MacroDefinitionOffsets.size());
1465    Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1466                              (const char *)data(MacroDefinitionOffsets),
1467                              MacroDefinitionOffsets.size() * sizeof(uint32_t));
1468  }
1469}
1470
1471void ASTWriter::WriteUserDiagnosticMappings(const Diagnostic &Diag) {
1472  RecordData Record;
1473  for (unsigned i = 0; i != diag::DIAG_UPPER_LIMIT; ++i) {
1474    diag::Mapping Map = Diag.getDiagnosticMappingInfo(i,Diag.GetCurDiagState());
1475    if (Map & 0x8) { // user mapping.
1476      Record.push_back(i);
1477      Record.push_back(Map & 0x7);
1478    }
1479  }
1480
1481  if (!Record.empty())
1482    Stream.EmitRecord(DIAG_USER_MAPPINGS, Record);
1483}
1484
1485//===----------------------------------------------------------------------===//
1486// Type Serialization
1487//===----------------------------------------------------------------------===//
1488
1489/// \brief Write the representation of a type to the AST stream.
1490void ASTWriter::WriteType(QualType T) {
1491  TypeIdx &Idx = TypeIdxs[T];
1492  if (Idx.getIndex() == 0) // we haven't seen this type before.
1493    Idx = TypeIdx(NextTypeID++);
1494
1495  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1496
1497  // Record the offset for this type.
1498  unsigned Index = Idx.getIndex() - FirstTypeID;
1499  if (TypeOffsets.size() == Index)
1500    TypeOffsets.push_back(Stream.GetCurrentBitNo());
1501  else if (TypeOffsets.size() < Index) {
1502    TypeOffsets.resize(Index + 1);
1503    TypeOffsets[Index] = Stream.GetCurrentBitNo();
1504  }
1505
1506  RecordData Record;
1507
1508  // Emit the type's representation.
1509  ASTTypeWriter W(*this, Record);
1510
1511  if (T.hasLocalNonFastQualifiers()) {
1512    Qualifiers Qs = T.getLocalQualifiers();
1513    AddTypeRef(T.getLocalUnqualifiedType(), Record);
1514    Record.push_back(Qs.getAsOpaqueValue());
1515    W.Code = TYPE_EXT_QUAL;
1516  } else {
1517    switch (T->getTypeClass()) {
1518      // For all of the concrete, non-dependent types, call the
1519      // appropriate visitor function.
1520#define TYPE(Class, Base) \
1521    case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1522#define ABSTRACT_TYPE(Class, Base)
1523#include "clang/AST/TypeNodes.def"
1524    }
1525  }
1526
1527  // Emit the serialized record.
1528  Stream.EmitRecord(W.Code, Record);
1529
1530  // Flush any expressions that were written as part of this type.
1531  FlushStmts();
1532}
1533
1534//===----------------------------------------------------------------------===//
1535// Declaration Serialization
1536//===----------------------------------------------------------------------===//
1537
1538/// \brief Write the block containing all of the declaration IDs
1539/// lexically declared within the given DeclContext.
1540///
1541/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1542/// bistream, or 0 if no block was written.
1543uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1544                                                 DeclContext *DC) {
1545  if (DC->decls_empty())
1546    return 0;
1547
1548  uint64_t Offset = Stream.GetCurrentBitNo();
1549  RecordData Record;
1550  Record.push_back(DECL_CONTEXT_LEXICAL);
1551  llvm::SmallVector<KindDeclIDPair, 64> Decls;
1552  for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1553         D != DEnd; ++D)
1554    Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1555
1556  ++NumLexicalDeclContexts;
1557  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
1558                            reinterpret_cast<char*>(Decls.data()),
1559                            Decls.size() * sizeof(KindDeclIDPair));
1560  return Offset;
1561}
1562
1563void ASTWriter::WriteTypeDeclOffsets() {
1564  using namespace llvm;
1565  RecordData Record;
1566
1567  // Write the type offsets array
1568  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1569  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1570  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1571  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1572  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1573  Record.clear();
1574  Record.push_back(TYPE_OFFSET);
1575  Record.push_back(TypeOffsets.size());
1576  Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1577                            (const char *)data(TypeOffsets),
1578                            TypeOffsets.size() * sizeof(TypeOffsets[0]));
1579
1580  // Write the declaration offsets array
1581  Abbrev = new BitCodeAbbrev();
1582  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1583  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1584  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1585  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1586  Record.clear();
1587  Record.push_back(DECL_OFFSET);
1588  Record.push_back(DeclOffsets.size());
1589  Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1590                            (const char *)data(DeclOffsets),
1591                            DeclOffsets.size() * sizeof(DeclOffsets[0]));
1592}
1593
1594//===----------------------------------------------------------------------===//
1595// Global Method Pool and Selector Serialization
1596//===----------------------------------------------------------------------===//
1597
1598namespace {
1599// Trait used for the on-disk hash table used in the method pool.
1600class ASTMethodPoolTrait {
1601  ASTWriter &Writer;
1602
1603public:
1604  typedef Selector key_type;
1605  typedef key_type key_type_ref;
1606
1607  struct data_type {
1608    SelectorID ID;
1609    ObjCMethodList Instance, Factory;
1610  };
1611  typedef const data_type& data_type_ref;
1612
1613  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
1614
1615  static unsigned ComputeHash(Selector Sel) {
1616    return serialization::ComputeHash(Sel);
1617  }
1618
1619  std::pair<unsigned,unsigned>
1620    EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1621                      data_type_ref Methods) {
1622    unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1623    clang::io::Emit16(Out, KeyLen);
1624    unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
1625    for (const ObjCMethodList *Method = &Methods.Instance; Method;
1626         Method = Method->Next)
1627      if (Method->Method)
1628        DataLen += 4;
1629    for (const ObjCMethodList *Method = &Methods.Factory; Method;
1630         Method = Method->Next)
1631      if (Method->Method)
1632        DataLen += 4;
1633    clang::io::Emit16(Out, DataLen);
1634    return std::make_pair(KeyLen, DataLen);
1635  }
1636
1637  void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1638    uint64_t Start = Out.tell();
1639    assert((Start >> 32) == 0 && "Selector key offset too large");
1640    Writer.SetSelectorOffset(Sel, Start);
1641    unsigned N = Sel.getNumArgs();
1642    clang::io::Emit16(Out, N);
1643    if (N == 0)
1644      N = 1;
1645    for (unsigned I = 0; I != N; ++I)
1646      clang::io::Emit32(Out,
1647                    Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1648  }
1649
1650  void EmitData(llvm::raw_ostream& Out, key_type_ref,
1651                data_type_ref Methods, unsigned DataLen) {
1652    uint64_t Start = Out.tell(); (void)Start;
1653    clang::io::Emit32(Out, Methods.ID);
1654    unsigned NumInstanceMethods = 0;
1655    for (const ObjCMethodList *Method = &Methods.Instance; Method;
1656         Method = Method->Next)
1657      if (Method->Method)
1658        ++NumInstanceMethods;
1659
1660    unsigned NumFactoryMethods = 0;
1661    for (const ObjCMethodList *Method = &Methods.Factory; Method;
1662         Method = Method->Next)
1663      if (Method->Method)
1664        ++NumFactoryMethods;
1665
1666    clang::io::Emit16(Out, NumInstanceMethods);
1667    clang::io::Emit16(Out, NumFactoryMethods);
1668    for (const ObjCMethodList *Method = &Methods.Instance; Method;
1669         Method = Method->Next)
1670      if (Method->Method)
1671        clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1672    for (const ObjCMethodList *Method = &Methods.Factory; Method;
1673         Method = Method->Next)
1674      if (Method->Method)
1675        clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1676
1677    assert(Out.tell() - Start == DataLen && "Data length is wrong");
1678  }
1679};
1680} // end anonymous namespace
1681
1682/// \brief Write ObjC data: selectors and the method pool.
1683///
1684/// The method pool contains both instance and factory methods, stored
1685/// in an on-disk hash table indexed by the selector. The hash table also
1686/// contains an empty entry for every other selector known to Sema.
1687void ASTWriter::WriteSelectors(Sema &SemaRef) {
1688  using namespace llvm;
1689
1690  // Do we have to do anything at all?
1691  if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
1692    return;
1693  unsigned NumTableEntries = 0;
1694  // Create and write out the blob that contains selectors and the method pool.
1695  {
1696    OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
1697    ASTMethodPoolTrait Trait(*this);
1698
1699    // Create the on-disk hash table representation. We walk through every
1700    // selector we've seen and look it up in the method pool.
1701    SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
1702    for (llvm::DenseMap<Selector, SelectorID>::iterator
1703             I = SelectorIDs.begin(), E = SelectorIDs.end();
1704         I != E; ++I) {
1705      Selector S = I->first;
1706      Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
1707      ASTMethodPoolTrait::data_type Data = {
1708        I->second,
1709        ObjCMethodList(),
1710        ObjCMethodList()
1711      };
1712      if (F != SemaRef.MethodPool.end()) {
1713        Data.Instance = F->second.first;
1714        Data.Factory = F->second.second;
1715      }
1716      // Only write this selector if it's not in an existing AST or something
1717      // changed.
1718      if (Chain && I->second < FirstSelectorID) {
1719        // Selector already exists. Did it change?
1720        bool changed = false;
1721        for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
1722             M = M->Next) {
1723          if (M->Method->getPCHLevel() == 0)
1724            changed = true;
1725        }
1726        for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
1727             M = M->Next) {
1728          if (M->Method->getPCHLevel() == 0)
1729            changed = true;
1730        }
1731        if (!changed)
1732          continue;
1733      } else if (Data.Instance.Method || Data.Factory.Method) {
1734        // A new method pool entry.
1735        ++NumTableEntries;
1736      }
1737      Generator.insert(S, Data, Trait);
1738    }
1739
1740    // Create the on-disk hash table in a buffer.
1741    llvm::SmallString<4096> MethodPool;
1742    uint32_t BucketOffset;
1743    {
1744      ASTMethodPoolTrait Trait(*this);
1745      llvm::raw_svector_ostream Out(MethodPool);
1746      // Make sure that no bucket is at offset 0
1747      clang::io::Emit32(Out, 0);
1748      BucketOffset = Generator.Emit(Out, Trait);
1749    }
1750
1751    // Create a blob abbreviation
1752    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1753    Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
1754    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1755    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1756    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1757    unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1758
1759    // Write the method pool
1760    RecordData Record;
1761    Record.push_back(METHOD_POOL);
1762    Record.push_back(BucketOffset);
1763    Record.push_back(NumTableEntries);
1764    Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
1765
1766    // Create a blob abbreviation for the selector table offsets.
1767    Abbrev = new BitCodeAbbrev();
1768    Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
1769    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1770    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1771    unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1772
1773    // Write the selector offsets table.
1774    Record.clear();
1775    Record.push_back(SELECTOR_OFFSETS);
1776    Record.push_back(SelectorOffsets.size());
1777    Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1778                              (const char *)data(SelectorOffsets),
1779                              SelectorOffsets.size() * 4);
1780  }
1781}
1782
1783/// \brief Write the selectors referenced in @selector expression into AST file.
1784void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
1785  using namespace llvm;
1786  if (SemaRef.ReferencedSelectors.empty())
1787    return;
1788
1789  RecordData Record;
1790
1791  // Note: this writes out all references even for a dependent AST. But it is
1792  // very tricky to fix, and given that @selector shouldn't really appear in
1793  // headers, probably not worth it. It's not a correctness issue.
1794  for (DenseMap<Selector, SourceLocation>::iterator S =
1795       SemaRef.ReferencedSelectors.begin(),
1796       E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
1797    Selector Sel = (*S).first;
1798    SourceLocation Loc = (*S).second;
1799    AddSelectorRef(Sel, Record);
1800    AddSourceLocation(Loc, Record);
1801  }
1802  Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
1803}
1804
1805//===----------------------------------------------------------------------===//
1806// Identifier Table Serialization
1807//===----------------------------------------------------------------------===//
1808
1809namespace {
1810class ASTIdentifierTableTrait {
1811  ASTWriter &Writer;
1812  Preprocessor &PP;
1813
1814  /// \brief Determines whether this is an "interesting" identifier
1815  /// that needs a full IdentifierInfo structure written into the hash
1816  /// table.
1817  static bool isInterestingIdentifier(const IdentifierInfo *II) {
1818    return II->isPoisoned() ||
1819      II->isExtensionToken() ||
1820      II->hasMacroDefinition() ||
1821      II->getObjCOrBuiltinID() ||
1822      II->getFETokenInfo<void>();
1823  }
1824
1825public:
1826  typedef const IdentifierInfo* key_type;
1827  typedef key_type  key_type_ref;
1828
1829  typedef IdentID data_type;
1830  typedef data_type data_type_ref;
1831
1832  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
1833    : Writer(Writer), PP(PP) { }
1834
1835  static unsigned ComputeHash(const IdentifierInfo* II) {
1836    return llvm::HashString(II->getName());
1837  }
1838
1839  std::pair<unsigned,unsigned>
1840    EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1841                      IdentID ID) {
1842    unsigned KeyLen = II->getLength() + 1;
1843    unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1844    if (isInterestingIdentifier(II)) {
1845      DataLen += 2; // 2 bytes for builtin ID, flags
1846      if (II->hasMacroDefinition() &&
1847          !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1848        DataLen += 4;
1849      for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1850                                     DEnd = IdentifierResolver::end();
1851           D != DEnd; ++D)
1852        DataLen += sizeof(DeclID);
1853    }
1854    clang::io::Emit16(Out, DataLen);
1855    // We emit the key length after the data length so that every
1856    // string is preceded by a 16-bit length. This matches the PTH
1857    // format for storing identifiers.
1858    clang::io::Emit16(Out, KeyLen);
1859    return std::make_pair(KeyLen, DataLen);
1860  }
1861
1862  void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1863               unsigned KeyLen) {
1864    // Record the location of the key data.  This is used when generating
1865    // the mapping from persistent IDs to strings.
1866    Writer.SetIdentifierOffset(II, Out.tell());
1867    Out.write(II->getNameStart(), KeyLen);
1868  }
1869
1870  void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1871                IdentID ID, unsigned) {
1872    if (!isInterestingIdentifier(II)) {
1873      clang::io::Emit32(Out, ID << 1);
1874      return;
1875    }
1876
1877    clang::io::Emit32(Out, (ID << 1) | 0x01);
1878    uint32_t Bits = 0;
1879    bool hasMacroDefinition =
1880      II->hasMacroDefinition() &&
1881      !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
1882    Bits = (uint32_t)II->getObjCOrBuiltinID();
1883    Bits = (Bits << 1) | unsigned(hasMacroDefinition);
1884    Bits = (Bits << 1) | unsigned(II->isExtensionToken());
1885    Bits = (Bits << 1) | unsigned(II->isPoisoned());
1886    Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
1887    Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
1888    clang::io::Emit16(Out, Bits);
1889
1890    if (hasMacroDefinition)
1891      clang::io::Emit32(Out, Writer.getMacroOffset(II));
1892
1893    // Emit the declaration IDs in reverse order, because the
1894    // IdentifierResolver provides the declarations as they would be
1895    // visible (e.g., the function "stat" would come before the struct
1896    // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1897    // adds declarations to the end of the list (so we need to see the
1898    // struct "status" before the function "status").
1899    // Only emit declarations that aren't from a chained PCH, though.
1900    llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1901                                        IdentifierResolver::end());
1902    for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1903                                                      DEnd = Decls.rend();
1904         D != DEnd; ++D)
1905      clang::io::Emit32(Out, Writer.getDeclID(*D));
1906  }
1907};
1908} // end anonymous namespace
1909
1910/// \brief Write the identifier table into the AST file.
1911///
1912/// The identifier table consists of a blob containing string data
1913/// (the actual identifiers themselves) and a separate "offsets" index
1914/// that maps identifier IDs to locations within the blob.
1915void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
1916  using namespace llvm;
1917
1918  // Create and write out the blob that contains the identifier
1919  // strings.
1920  {
1921    OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
1922    ASTIdentifierTableTrait Trait(*this, PP);
1923
1924    // Look for any identifiers that were named while processing the
1925    // headers, but are otherwise not needed. We add these to the hash
1926    // table to enable checking of the predefines buffer in the case
1927    // where the user adds new macro definitions when building the AST
1928    // file.
1929    for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1930                                IDEnd = PP.getIdentifierTable().end();
1931         ID != IDEnd; ++ID)
1932      getIdentifierRef(ID->second);
1933
1934    // Create the on-disk hash table representation. We only store offsets
1935    // for identifiers that appear here for the first time.
1936    IdentifierOffsets.resize(NextIdentID - FirstIdentID);
1937    for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
1938           ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1939         ID != IDEnd; ++ID) {
1940      assert(ID->first && "NULL identifier in identifier table");
1941      if (!Chain || !ID->first->isFromAST())
1942        Generator.insert(ID->first, ID->second, Trait);
1943    }
1944
1945    // Create the on-disk hash table in a buffer.
1946    llvm::SmallString<4096> IdentifierTable;
1947    uint32_t BucketOffset;
1948    {
1949      ASTIdentifierTableTrait Trait(*this, PP);
1950      llvm::raw_svector_ostream Out(IdentifierTable);
1951      // Make sure that no bucket is at offset 0
1952      clang::io::Emit32(Out, 0);
1953      BucketOffset = Generator.Emit(Out, Trait);
1954    }
1955
1956    // Create a blob abbreviation
1957    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1958    Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
1959    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1960    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1961    unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
1962
1963    // Write the identifier table
1964    RecordData Record;
1965    Record.push_back(IDENTIFIER_TABLE);
1966    Record.push_back(BucketOffset);
1967    Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
1968  }
1969
1970  // Write the offsets table for identifier IDs.
1971  BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1972  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
1973  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1974  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1975  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1976
1977  RecordData Record;
1978  Record.push_back(IDENTIFIER_OFFSET);
1979  Record.push_back(IdentifierOffsets.size());
1980  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1981                            (const char *)data(IdentifierOffsets),
1982                            IdentifierOffsets.size() * sizeof(uint32_t));
1983}
1984
1985//===----------------------------------------------------------------------===//
1986// DeclContext's Name Lookup Table Serialization
1987//===----------------------------------------------------------------------===//
1988
1989namespace {
1990// Trait used for the on-disk hash table used in the method pool.
1991class ASTDeclContextNameLookupTrait {
1992  ASTWriter &Writer;
1993
1994public:
1995  typedef DeclarationName key_type;
1996  typedef key_type key_type_ref;
1997
1998  typedef DeclContext::lookup_result data_type;
1999  typedef const data_type& data_type_ref;
2000
2001  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2002
2003  unsigned ComputeHash(DeclarationName Name) {
2004    llvm::FoldingSetNodeID ID;
2005    ID.AddInteger(Name.getNameKind());
2006
2007    switch (Name.getNameKind()) {
2008    case DeclarationName::Identifier:
2009      ID.AddString(Name.getAsIdentifierInfo()->getName());
2010      break;
2011    case DeclarationName::ObjCZeroArgSelector:
2012    case DeclarationName::ObjCOneArgSelector:
2013    case DeclarationName::ObjCMultiArgSelector:
2014      ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2015      break;
2016    case DeclarationName::CXXConstructorName:
2017    case DeclarationName::CXXDestructorName:
2018    case DeclarationName::CXXConversionFunctionName:
2019      ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2020      break;
2021    case DeclarationName::CXXOperatorName:
2022      ID.AddInteger(Name.getCXXOverloadedOperator());
2023      break;
2024    case DeclarationName::CXXLiteralOperatorName:
2025      ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2026    case DeclarationName::CXXUsingDirective:
2027      break;
2028    }
2029
2030    return ID.ComputeHash();
2031  }
2032
2033  std::pair<unsigned,unsigned>
2034    EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2035                      data_type_ref Lookup) {
2036    unsigned KeyLen = 1;
2037    switch (Name.getNameKind()) {
2038    case DeclarationName::Identifier:
2039    case DeclarationName::ObjCZeroArgSelector:
2040    case DeclarationName::ObjCOneArgSelector:
2041    case DeclarationName::ObjCMultiArgSelector:
2042    case DeclarationName::CXXConstructorName:
2043    case DeclarationName::CXXDestructorName:
2044    case DeclarationName::CXXConversionFunctionName:
2045    case DeclarationName::CXXLiteralOperatorName:
2046      KeyLen += 4;
2047      break;
2048    case DeclarationName::CXXOperatorName:
2049      KeyLen += 1;
2050      break;
2051    case DeclarationName::CXXUsingDirective:
2052      break;
2053    }
2054    clang::io::Emit16(Out, KeyLen);
2055
2056    // 2 bytes for num of decls and 4 for each DeclID.
2057    unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2058    clang::io::Emit16(Out, DataLen);
2059
2060    return std::make_pair(KeyLen, DataLen);
2061  }
2062
2063  void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2064    using namespace clang::io;
2065
2066    assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2067    Emit8(Out, Name.getNameKind());
2068    switch (Name.getNameKind()) {
2069    case DeclarationName::Identifier:
2070      Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2071      break;
2072    case DeclarationName::ObjCZeroArgSelector:
2073    case DeclarationName::ObjCOneArgSelector:
2074    case DeclarationName::ObjCMultiArgSelector:
2075      Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2076      break;
2077    case DeclarationName::CXXConstructorName:
2078    case DeclarationName::CXXDestructorName:
2079    case DeclarationName::CXXConversionFunctionName:
2080      Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2081      break;
2082    case DeclarationName::CXXOperatorName:
2083      assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2084      Emit8(Out, Name.getCXXOverloadedOperator());
2085      break;
2086    case DeclarationName::CXXLiteralOperatorName:
2087      Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2088      break;
2089    case DeclarationName::CXXUsingDirective:
2090      break;
2091    }
2092  }
2093
2094  void EmitData(llvm::raw_ostream& Out, key_type_ref,
2095                data_type Lookup, unsigned DataLen) {
2096    uint64_t Start = Out.tell(); (void)Start;
2097    clang::io::Emit16(Out, Lookup.second - Lookup.first);
2098    for (; Lookup.first != Lookup.second; ++Lookup.first)
2099      clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2100
2101    assert(Out.tell() - Start == DataLen && "Data length is wrong");
2102  }
2103};
2104} // end anonymous namespace
2105
2106/// \brief Write the block containing all of the declaration IDs
2107/// visible from the given DeclContext.
2108///
2109/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2110/// bitstream, or 0 if no block was written.
2111uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2112                                                 DeclContext *DC) {
2113  if (DC->getPrimaryContext() != DC)
2114    return 0;
2115
2116  // Since there is no name lookup into functions or methods, don't bother to
2117  // build a visible-declarations table for these entities.
2118  if (DC->isFunctionOrMethod())
2119    return 0;
2120
2121  // If not in C++, we perform name lookup for the translation unit via the
2122  // IdentifierInfo chains, don't bother to build a visible-declarations table.
2123  // FIXME: In C++ we need the visible declarations in order to "see" the
2124  // friend declarations, is there a way to do this without writing the table ?
2125  if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2126    return 0;
2127
2128  // Force the DeclContext to build a its name-lookup table.
2129  if (DC->hasExternalVisibleStorage())
2130    DC->MaterializeVisibleDeclsFromExternalStorage();
2131  else
2132    DC->lookup(DeclarationName());
2133
2134  // Serialize the contents of the mapping used for lookup. Note that,
2135  // although we have two very different code paths, the serialized
2136  // representation is the same for both cases: a declaration name,
2137  // followed by a size, followed by references to the visible
2138  // declarations that have that name.
2139  uint64_t Offset = Stream.GetCurrentBitNo();
2140  StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2141  if (!Map || Map->empty())
2142    return 0;
2143
2144  OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2145  ASTDeclContextNameLookupTrait Trait(*this);
2146
2147  // Create the on-disk hash table representation.
2148  for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2149       D != DEnd; ++D) {
2150    DeclarationName Name = D->first;
2151    DeclContext::lookup_result Result = D->second.getLookupResult();
2152    Generator.insert(Name, Result, Trait);
2153  }
2154
2155  // Create the on-disk hash table in a buffer.
2156  llvm::SmallString<4096> LookupTable;
2157  uint32_t BucketOffset;
2158  {
2159    llvm::raw_svector_ostream Out(LookupTable);
2160    // Make sure that no bucket is at offset 0
2161    clang::io::Emit32(Out, 0);
2162    BucketOffset = Generator.Emit(Out, Trait);
2163  }
2164
2165  // Write the lookup table
2166  RecordData Record;
2167  Record.push_back(DECL_CONTEXT_VISIBLE);
2168  Record.push_back(BucketOffset);
2169  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2170                            LookupTable.str());
2171
2172  Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2173  ++NumVisibleDeclContexts;
2174  return Offset;
2175}
2176
2177/// \brief Write an UPDATE_VISIBLE block for the given context.
2178///
2179/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2180/// DeclContext in a dependent AST file. As such, they only exist for the TU
2181/// (in C++) and for namespaces.
2182void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2183  // Make the context build its lookup table, but don't make it load external
2184  // decls.
2185  DC->lookup(DeclarationName());
2186
2187  StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2188  if (!Map || Map->empty())
2189    return;
2190
2191  OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2192  ASTDeclContextNameLookupTrait Trait(*this);
2193
2194  // Create the hash table.
2195  for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2196       D != DEnd; ++D) {
2197    DeclarationName Name = D->first;
2198    DeclContext::lookup_result Result = D->second.getLookupResult();
2199    // For any name that appears in this table, the results are complete, i.e.
2200    // they overwrite results from previous PCHs. Merging is always a mess.
2201    Generator.insert(Name, Result, Trait);
2202  }
2203
2204  // Create the on-disk hash table in a buffer.
2205  llvm::SmallString<4096> LookupTable;
2206  uint32_t BucketOffset;
2207  {
2208    llvm::raw_svector_ostream Out(LookupTable);
2209    // Make sure that no bucket is at offset 0
2210    clang::io::Emit32(Out, 0);
2211    BucketOffset = Generator.Emit(Out, Trait);
2212  }
2213
2214  // Write the lookup table
2215  RecordData Record;
2216  Record.push_back(UPDATE_VISIBLE);
2217  Record.push_back(getDeclID(cast<Decl>(DC)));
2218  Record.push_back(BucketOffset);
2219  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2220}
2221
2222//===----------------------------------------------------------------------===//
2223// General Serialization Routines
2224//===----------------------------------------------------------------------===//
2225
2226/// \brief Write a record containing the given attributes.
2227void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2228  Record.push_back(Attrs.size());
2229  for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2230    const Attr * A = *i;
2231    Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2232    AddSourceLocation(A->getLocation(), Record);
2233    Record.push_back(A->isInherited());
2234
2235#include "clang/Serialization/AttrPCHWrite.inc"
2236
2237  }
2238}
2239
2240void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2241  Record.push_back(Str.size());
2242  Record.insert(Record.end(), Str.begin(), Str.end());
2243}
2244
2245/// \brief Note that the identifier II occurs at the given offset
2246/// within the identifier table.
2247void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2248  IdentID ID = IdentifierIDs[II];
2249  // Only store offsets new to this AST file. Other identifier names are looked
2250  // up earlier in the chain and thus don't need an offset.
2251  if (ID >= FirstIdentID)
2252    IdentifierOffsets[ID - FirstIdentID] = Offset;
2253}
2254
2255/// \brief Note that the selector Sel occurs at the given offset
2256/// within the method pool/selector table.
2257void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2258  unsigned ID = SelectorIDs[Sel];
2259  assert(ID && "Unknown selector");
2260  // Don't record offsets for selectors that are also available in a different
2261  // file.
2262  if (ID < FirstSelectorID)
2263    return;
2264  SelectorOffsets[ID - FirstSelectorID] = Offset;
2265}
2266
2267ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2268  : Stream(Stream), Chain(0), SerializationListener(0),
2269    FirstDeclID(1), NextDeclID(FirstDeclID),
2270    FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2271    FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2272    NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2273    CollectedStmts(&StmtsToEmit),
2274    NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2275    NumVisibleDeclContexts(0), FirstCXXBaseSpecifiersID(1),
2276    NextCXXBaseSpecifiersID(1)
2277{
2278}
2279
2280void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2281                         const char *isysroot) {
2282  // Emit the file header.
2283  Stream.Emit((unsigned)'C', 8);
2284  Stream.Emit((unsigned)'P', 8);
2285  Stream.Emit((unsigned)'C', 8);
2286  Stream.Emit((unsigned)'H', 8);
2287
2288  WriteBlockInfoBlock();
2289
2290  if (Chain)
2291    WriteASTChain(SemaRef, StatCalls, isysroot);
2292  else
2293    WriteASTCore(SemaRef, StatCalls, isysroot);
2294}
2295
2296void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2297                             const char *isysroot) {
2298  using namespace llvm;
2299
2300  ASTContext &Context = SemaRef.Context;
2301  Preprocessor &PP = SemaRef.PP;
2302
2303  // The translation unit is the first declaration we'll emit.
2304  DeclIDs[Context.getTranslationUnitDecl()] = 1;
2305  ++NextDeclID;
2306  DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2307
2308  // Make sure that we emit IdentifierInfos (and any attached
2309  // declarations) for builtins.
2310  {
2311    IdentifierTable &Table = PP.getIdentifierTable();
2312    llvm::SmallVector<const char *, 32> BuiltinNames;
2313    Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2314                                        Context.getLangOptions().NoBuiltin);
2315    for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2316      getIdentifierRef(&Table.get(BuiltinNames[I]));
2317  }
2318
2319  // Build a record containing all of the tentative definitions in this file, in
2320  // TentativeDefinitions order.  Generally, this record will be empty for
2321  // headers.
2322  RecordData TentativeDefinitions;
2323  for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2324    AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2325  }
2326
2327  // Build a record containing all of the file scoped decls in this file.
2328  RecordData UnusedFileScopedDecls;
2329  for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2330    AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2331
2332  RecordData WeakUndeclaredIdentifiers;
2333  if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2334    WeakUndeclaredIdentifiers.push_back(
2335                                      SemaRef.WeakUndeclaredIdentifiers.size());
2336    for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2337         I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2338         E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2339      AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2340      AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2341      AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2342      WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2343    }
2344  }
2345
2346  // Build a record containing all of the locally-scoped external
2347  // declarations in this header file. Generally, this record will be
2348  // empty.
2349  RecordData LocallyScopedExternalDecls;
2350  // FIXME: This is filling in the AST file in densemap order which is
2351  // nondeterminstic!
2352  for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2353         TD = SemaRef.LocallyScopedExternalDecls.begin(),
2354         TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2355       TD != TDEnd; ++TD)
2356    AddDeclRef(TD->second, LocallyScopedExternalDecls);
2357
2358  // Build a record containing all of the ext_vector declarations.
2359  RecordData ExtVectorDecls;
2360  for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2361    AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2362
2363  // Build a record containing all of the VTable uses information.
2364  RecordData VTableUses;
2365  if (!SemaRef.VTableUses.empty()) {
2366    VTableUses.push_back(SemaRef.VTableUses.size());
2367    for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2368      AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2369      AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2370      VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2371    }
2372  }
2373
2374  // Build a record containing all of dynamic classes declarations.
2375  RecordData DynamicClasses;
2376  for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2377    AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2378
2379  // Build a record containing all of pending implicit instantiations.
2380  RecordData PendingInstantiations;
2381  for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2382         I = SemaRef.PendingInstantiations.begin(),
2383         N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2384    AddDeclRef(I->first, PendingInstantiations);
2385    AddSourceLocation(I->second, PendingInstantiations);
2386  }
2387  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2388         "There are local ones at end of translation unit!");
2389
2390  // Build a record containing some declaration references.
2391  RecordData SemaDeclRefs;
2392  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2393    AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2394    AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2395  }
2396
2397  // Write the remaining AST contents.
2398  RecordData Record;
2399  Stream.EnterSubblock(AST_BLOCK_ID, 5);
2400  WriteMetadata(Context, isysroot);
2401  WriteLanguageOptions(Context.getLangOptions());
2402  if (StatCalls && !isysroot)
2403    WriteStatCache(*StatCalls);
2404  WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2405  // Write the record of special types.
2406  Record.clear();
2407
2408  AddTypeRef(Context.getBuiltinVaListType(), Record);
2409  AddTypeRef(Context.getObjCIdType(), Record);
2410  AddTypeRef(Context.getObjCSelType(), Record);
2411  AddTypeRef(Context.getObjCProtoType(), Record);
2412  AddTypeRef(Context.getObjCClassType(), Record);
2413  AddTypeRef(Context.getRawCFConstantStringType(), Record);
2414  AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2415  AddTypeRef(Context.getFILEType(), Record);
2416  AddTypeRef(Context.getjmp_bufType(), Record);
2417  AddTypeRef(Context.getsigjmp_bufType(), Record);
2418  AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2419  AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2420  AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2421  AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2422  AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2423  AddTypeRef(Context.getRawNSConstantStringType(), Record);
2424  Record.push_back(Context.isInt128Installed());
2425  Stream.EmitRecord(SPECIAL_TYPES, Record);
2426
2427  // Keep writing types and declarations until all types and
2428  // declarations have been written.
2429  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2430  WriteDeclsBlockAbbrevs();
2431  while (!DeclTypesToEmit.empty()) {
2432    DeclOrType DOT = DeclTypesToEmit.front();
2433    DeclTypesToEmit.pop();
2434    if (DOT.isType())
2435      WriteType(DOT.getType());
2436    else
2437      WriteDecl(Context, DOT.getDecl());
2438  }
2439  Stream.ExitBlock();
2440
2441  WritePreprocessor(PP);
2442  WriteSelectors(SemaRef);
2443  WriteReferencedSelectorsPool(SemaRef);
2444  WriteIdentifierTable(PP);
2445
2446  WriteTypeDeclOffsets();
2447  WriteUserDiagnosticMappings(Context.getDiagnostics());
2448
2449  // Write the C++ base-specifier set offsets.
2450  if (!CXXBaseSpecifiersOffsets.empty()) {
2451    // Create a blob abbreviation for the C++ base specifiers offsets.
2452    using namespace llvm;
2453
2454    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2455    Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2456    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2457    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2458    unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2459
2460    // Write the selector offsets table.
2461    Record.clear();
2462    Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2463    Record.push_back(CXXBaseSpecifiersOffsets.size());
2464    Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2465                              (const char *)CXXBaseSpecifiersOffsets.data(),
2466                            CXXBaseSpecifiersOffsets.size() * sizeof(uint32_t));
2467  }
2468
2469  // Write the record containing external, unnamed definitions.
2470  if (!ExternalDefinitions.empty())
2471    Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2472
2473  // Write the record containing tentative definitions.
2474  if (!TentativeDefinitions.empty())
2475    Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2476
2477  // Write the record containing unused file scoped decls.
2478  if (!UnusedFileScopedDecls.empty())
2479    Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2480
2481  // Write the record containing weak undeclared identifiers.
2482  if (!WeakUndeclaredIdentifiers.empty())
2483    Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2484                      WeakUndeclaredIdentifiers);
2485
2486  // Write the record containing locally-scoped external definitions.
2487  if (!LocallyScopedExternalDecls.empty())
2488    Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2489                      LocallyScopedExternalDecls);
2490
2491  // Write the record containing ext_vector type names.
2492  if (!ExtVectorDecls.empty())
2493    Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2494
2495  // Write the record containing VTable uses information.
2496  if (!VTableUses.empty())
2497    Stream.EmitRecord(VTABLE_USES, VTableUses);
2498
2499  // Write the record containing dynamic classes declarations.
2500  if (!DynamicClasses.empty())
2501    Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2502
2503  // Write the record containing pending implicit instantiations.
2504  if (!PendingInstantiations.empty())
2505    Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2506
2507  // Write the record containing declaration references of Sema.
2508  if (!SemaDeclRefs.empty())
2509    Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2510
2511  // Some simple statistics
2512  Record.clear();
2513  Record.push_back(NumStatements);
2514  Record.push_back(NumMacros);
2515  Record.push_back(NumLexicalDeclContexts);
2516  Record.push_back(NumVisibleDeclContexts);
2517  Stream.EmitRecord(STATISTICS, Record);
2518  Stream.ExitBlock();
2519}
2520
2521void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2522                              const char *isysroot) {
2523  using namespace llvm;
2524
2525  ASTContext &Context = SemaRef.Context;
2526  Preprocessor &PP = SemaRef.PP;
2527
2528  RecordData Record;
2529  Stream.EnterSubblock(AST_BLOCK_ID, 5);
2530  WriteMetadata(Context, isysroot);
2531  if (StatCalls && !isysroot)
2532    WriteStatCache(*StatCalls);
2533  // FIXME: Source manager block should only write new stuff, which could be
2534  // done by tracking the largest ID in the chain
2535  WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2536
2537  // The special types are in the chained PCH.
2538
2539  // We don't start with the translation unit, but with its decls that
2540  // don't come from the chained PCH.
2541  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2542  llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
2543  for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
2544                                  E = TU->noload_decls_end();
2545       I != E; ++I) {
2546    if ((*I)->getPCHLevel() == 0)
2547      NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
2548    else if ((*I)->isChangedSinceDeserialization())
2549      (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
2550  }
2551  // We also need to write a lexical updates block for the TU.
2552  llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
2553  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
2554  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2555  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
2556  Record.clear();
2557  Record.push_back(TU_UPDATE_LEXICAL);
2558  Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
2559                          reinterpret_cast<const char*>(NewGlobalDecls.data()),
2560                          NewGlobalDecls.size() * sizeof(KindDeclIDPair));
2561  // And a visible updates block for the DeclContexts.
2562  Abv = new llvm::BitCodeAbbrev();
2563  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
2564  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
2565  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
2566  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2567  UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
2568  WriteDeclContextVisibleUpdate(TU);
2569
2570  // Build a record containing all of the new tentative definitions in this
2571  // file, in TentativeDefinitions order.
2572  RecordData TentativeDefinitions;
2573  for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2574    if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
2575      AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2576  }
2577
2578  // Build a record containing all of the file scoped decls in this file.
2579  RecordData UnusedFileScopedDecls;
2580  for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
2581    if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
2582      AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2583  }
2584
2585  // We write the entire table, overwriting the tables from the chain.
2586  RecordData WeakUndeclaredIdentifiers;
2587  if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2588    WeakUndeclaredIdentifiers.push_back(
2589                                      SemaRef.WeakUndeclaredIdentifiers.size());
2590    for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2591         I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2592         E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2593      AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2594      AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2595      AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2596      WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2597    }
2598  }
2599
2600  // Build a record containing all of the locally-scoped external
2601  // declarations in this header file. Generally, this record will be
2602  // empty.
2603  RecordData LocallyScopedExternalDecls;
2604  // FIXME: This is filling in the AST file in densemap order which is
2605  // nondeterminstic!
2606  for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2607         TD = SemaRef.LocallyScopedExternalDecls.begin(),
2608         TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2609       TD != TDEnd; ++TD) {
2610    if (TD->second->getPCHLevel() == 0)
2611      AddDeclRef(TD->second, LocallyScopedExternalDecls);
2612  }
2613
2614  // Build a record containing all of the ext_vector declarations.
2615  RecordData ExtVectorDecls;
2616  for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
2617    if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
2618      AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2619  }
2620
2621  // Build a record containing all of the VTable uses information.
2622  // We write everything here, because it's too hard to determine whether
2623  // a use is new to this part.
2624  RecordData VTableUses;
2625  if (!SemaRef.VTableUses.empty()) {
2626    VTableUses.push_back(SemaRef.VTableUses.size());
2627    for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2628      AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2629      AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2630      VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2631    }
2632  }
2633
2634  // Build a record containing all of dynamic classes declarations.
2635  RecordData DynamicClasses;
2636  for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2637    if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
2638      AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2639
2640  // Build a record containing all of pending implicit instantiations.
2641  RecordData PendingInstantiations;
2642  for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2643         I = SemaRef.PendingInstantiations.begin(),
2644         N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2645    if (I->first->getPCHLevel() == 0) {
2646      AddDeclRef(I->first, PendingInstantiations);
2647      AddSourceLocation(I->second, PendingInstantiations);
2648    }
2649  }
2650  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2651         "There are local ones at end of translation unit!");
2652
2653  // Build a record containing some declaration references.
2654  // It's not worth the effort to avoid duplication here.
2655  RecordData SemaDeclRefs;
2656  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2657    AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2658    AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2659  }
2660
2661  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2662  WriteDeclsBlockAbbrevs();
2663  for (DeclsToRewriteTy::iterator
2664         I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
2665    DeclTypesToEmit.push(const_cast<Decl*>(*I));
2666  while (!DeclTypesToEmit.empty()) {
2667    DeclOrType DOT = DeclTypesToEmit.front();
2668    DeclTypesToEmit.pop();
2669    if (DOT.isType())
2670      WriteType(DOT.getType());
2671    else
2672      WriteDecl(Context, DOT.getDecl());
2673  }
2674  Stream.ExitBlock();
2675
2676  WritePreprocessor(PP);
2677  WriteSelectors(SemaRef);
2678  WriteReferencedSelectorsPool(SemaRef);
2679  WriteIdentifierTable(PP);
2680  WriteTypeDeclOffsets();
2681  // FIXME: For chained PCH only write the new mappings (we currently
2682  // write all of them again).
2683  WriteUserDiagnosticMappings(Context.getDiagnostics());
2684
2685  /// Build a record containing first declarations from a chained PCH and the
2686  /// most recent declarations in this AST that they point to.
2687  RecordData FirstLatestDeclIDs;
2688  for (FirstLatestDeclMap::iterator
2689        I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
2690    assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
2691           "Expected first & second to be in different PCHs");
2692    AddDeclRef(I->first, FirstLatestDeclIDs);
2693    AddDeclRef(I->second, FirstLatestDeclIDs);
2694  }
2695  if (!FirstLatestDeclIDs.empty())
2696    Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
2697
2698  // Write the record containing external, unnamed definitions.
2699  if (!ExternalDefinitions.empty())
2700    Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2701
2702  // Write the record containing tentative definitions.
2703  if (!TentativeDefinitions.empty())
2704    Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2705
2706  // Write the record containing unused file scoped decls.
2707  if (!UnusedFileScopedDecls.empty())
2708    Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2709
2710  // Write the record containing weak undeclared identifiers.
2711  if (!WeakUndeclaredIdentifiers.empty())
2712    Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2713                      WeakUndeclaredIdentifiers);
2714
2715  // Write the record containing locally-scoped external definitions.
2716  if (!LocallyScopedExternalDecls.empty())
2717    Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2718                      LocallyScopedExternalDecls);
2719
2720  // Write the record containing ext_vector type names.
2721  if (!ExtVectorDecls.empty())
2722    Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2723
2724  // Write the record containing VTable uses information.
2725  if (!VTableUses.empty())
2726    Stream.EmitRecord(VTABLE_USES, VTableUses);
2727
2728  // Write the record containing dynamic classes declarations.
2729  if (!DynamicClasses.empty())
2730    Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2731
2732  // Write the record containing pending implicit instantiations.
2733  if (!PendingInstantiations.empty())
2734    Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2735
2736  // Write the record containing declaration references of Sema.
2737  if (!SemaDeclRefs.empty())
2738    Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2739
2740  // Write the updates to DeclContexts.
2741  for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
2742           I = UpdatedDeclContexts.begin(),
2743           E = UpdatedDeclContexts.end();
2744         I != E; ++I)
2745    WriteDeclContextVisibleUpdate(*I);
2746
2747  WriteDeclUpdatesBlocks();
2748
2749  Record.clear();
2750  Record.push_back(NumStatements);
2751  Record.push_back(NumMacros);
2752  Record.push_back(NumLexicalDeclContexts);
2753  Record.push_back(NumVisibleDeclContexts);
2754  WriteDeclReplacementsBlock();
2755  Stream.EmitRecord(STATISTICS, Record);
2756  Stream.ExitBlock();
2757}
2758
2759void ASTWriter::WriteDeclUpdatesBlocks() {
2760  if (DeclUpdates.empty())
2761    return;
2762
2763  RecordData OffsetsRecord;
2764  Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, 3);
2765  for (DeclUpdateMap::iterator
2766         I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
2767    const Decl *D = I->first;
2768    UpdateRecord &URec = I->second;
2769
2770    if (DeclsToRewrite.count(D))
2771      continue; // The decl will be written completely,no need to store updates.
2772
2773    uint64_t Offset = Stream.GetCurrentBitNo();
2774    Stream.EmitRecord(DECL_UPDATES, URec);
2775
2776    OffsetsRecord.push_back(GetDeclRef(D));
2777    OffsetsRecord.push_back(Offset);
2778  }
2779  Stream.ExitBlock();
2780  Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
2781}
2782
2783void ASTWriter::WriteDeclReplacementsBlock() {
2784  if (ReplacedDecls.empty())
2785    return;
2786
2787  RecordData Record;
2788  for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
2789           I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
2790    Record.push_back(I->first);
2791    Record.push_back(I->second);
2792  }
2793  Stream.EmitRecord(DECL_REPLACEMENTS, Record);
2794}
2795
2796void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
2797  Record.push_back(Loc.getRawEncoding());
2798}
2799
2800void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
2801  AddSourceLocation(Range.getBegin(), Record);
2802  AddSourceLocation(Range.getEnd(), Record);
2803}
2804
2805void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
2806  Record.push_back(Value.getBitWidth());
2807  const uint64_t *Words = Value.getRawData();
2808  Record.append(Words, Words + Value.getNumWords());
2809}
2810
2811void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
2812  Record.push_back(Value.isUnsigned());
2813  AddAPInt(Value, Record);
2814}
2815
2816void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
2817  AddAPInt(Value.bitcastToAPInt(), Record);
2818}
2819
2820void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
2821  Record.push_back(getIdentifierRef(II));
2822}
2823
2824IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
2825  if (II == 0)
2826    return 0;
2827
2828  IdentID &ID = IdentifierIDs[II];
2829  if (ID == 0)
2830    ID = NextIdentID++;
2831  return ID;
2832}
2833
2834MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
2835  if (MD == 0)
2836    return 0;
2837
2838  MacroID &ID = MacroDefinitions[MD];
2839  if (ID == 0)
2840    ID = NextMacroID++;
2841  return ID;
2842}
2843
2844void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
2845  Record.push_back(getSelectorRef(SelRef));
2846}
2847
2848SelectorID ASTWriter::getSelectorRef(Selector Sel) {
2849  if (Sel.getAsOpaquePtr() == 0) {
2850    return 0;
2851  }
2852
2853  SelectorID &SID = SelectorIDs[Sel];
2854  if (SID == 0 && Chain) {
2855    // This might trigger a ReadSelector callback, which will set the ID for
2856    // this selector.
2857    Chain->LoadSelector(Sel);
2858  }
2859  if (SID == 0) {
2860    SID = NextSelectorID++;
2861  }
2862  return SID;
2863}
2864
2865void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
2866  AddDeclRef(Temp->getDestructor(), Record);
2867}
2868
2869void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
2870                                      CXXBaseSpecifier const *BasesEnd,
2871                                        RecordDataImpl &Record) {
2872  assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
2873  CXXBaseSpecifiersToWrite.push_back(
2874                                QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
2875                                                        Bases, BasesEnd));
2876  Record.push_back(NextCXXBaseSpecifiersID++);
2877}
2878
2879void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2880                                           const TemplateArgumentLocInfo &Arg,
2881                                           RecordDataImpl &Record) {
2882  switch (Kind) {
2883  case TemplateArgument::Expression:
2884    AddStmt(Arg.getAsExpr());
2885    break;
2886  case TemplateArgument::Type:
2887    AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
2888    break;
2889  case TemplateArgument::Template:
2890    AddSourceRange(Arg.getTemplateQualifierRange(), Record);
2891    AddSourceLocation(Arg.getTemplateNameLoc(), Record);
2892    break;
2893  case TemplateArgument::Null:
2894  case TemplateArgument::Integral:
2895  case TemplateArgument::Declaration:
2896  case TemplateArgument::Pack:
2897    break;
2898  }
2899}
2900
2901void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
2902                                       RecordDataImpl &Record) {
2903  AddTemplateArgument(Arg.getArgument(), Record);
2904
2905  if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
2906    bool InfoHasSameExpr
2907      = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
2908    Record.push_back(InfoHasSameExpr);
2909    if (InfoHasSameExpr)
2910      return; // Avoid storing the same expr twice.
2911  }
2912  AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
2913                             Record);
2914}
2915
2916void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record) {
2917  if (TInfo == 0) {
2918    AddTypeRef(QualType(), Record);
2919    return;
2920  }
2921
2922  AddTypeRef(TInfo->getType(), Record);
2923  TypeLocWriter TLW(*this, Record);
2924  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2925    TLW.Visit(TL);
2926}
2927
2928void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
2929  Record.push_back(GetOrCreateTypeID(T));
2930}
2931
2932TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
2933  return MakeTypeID(T,
2934              std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
2935}
2936
2937TypeID ASTWriter::getTypeID(QualType T) const {
2938  return MakeTypeID(T,
2939              std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
2940}
2941
2942TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
2943  if (T.isNull())
2944    return TypeIdx();
2945  assert(!T.getLocalFastQualifiers());
2946
2947  TypeIdx &Idx = TypeIdxs[T];
2948  if (Idx.getIndex() == 0) {
2949    // We haven't seen this type before. Assign it a new ID and put it
2950    // into the queue of types to emit.
2951    Idx = TypeIdx(NextTypeID++);
2952    DeclTypesToEmit.push(T);
2953  }
2954  return Idx;
2955}
2956
2957TypeIdx ASTWriter::getTypeIdx(QualType T) const {
2958  if (T.isNull())
2959    return TypeIdx();
2960  assert(!T.getLocalFastQualifiers());
2961
2962  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
2963  assert(I != TypeIdxs.end() && "Type not emitted!");
2964  return I->second;
2965}
2966
2967void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
2968  Record.push_back(GetDeclRef(D));
2969}
2970
2971DeclID ASTWriter::GetDeclRef(const Decl *D) {
2972  if (D == 0) {
2973    return 0;
2974  }
2975  assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
2976  DeclID &ID = DeclIDs[D];
2977  if (ID == 0) {
2978    // We haven't seen this declaration before. Give it a new ID and
2979    // enqueue it in the list of declarations to emit.
2980    ID = NextDeclID++;
2981    DeclTypesToEmit.push(const_cast<Decl *>(D));
2982  } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
2983    // We don't add it to the replacement collection here, because we don't
2984    // have the offset yet.
2985    DeclTypesToEmit.push(const_cast<Decl *>(D));
2986    // Reset the flag, so that we don't add this decl multiple times.
2987    const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
2988  }
2989
2990  return ID;
2991}
2992
2993DeclID ASTWriter::getDeclID(const Decl *D) {
2994  if (D == 0)
2995    return 0;
2996
2997  assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2998  return DeclIDs[D];
2999}
3000
3001void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3002  // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
3003  Record.push_back(Name.getNameKind());
3004  switch (Name.getNameKind()) {
3005  case DeclarationName::Identifier:
3006    AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3007    break;
3008
3009  case DeclarationName::ObjCZeroArgSelector:
3010  case DeclarationName::ObjCOneArgSelector:
3011  case DeclarationName::ObjCMultiArgSelector:
3012    AddSelectorRef(Name.getObjCSelector(), Record);
3013    break;
3014
3015  case DeclarationName::CXXConstructorName:
3016  case DeclarationName::CXXDestructorName:
3017  case DeclarationName::CXXConversionFunctionName:
3018    AddTypeRef(Name.getCXXNameType(), Record);
3019    break;
3020
3021  case DeclarationName::CXXOperatorName:
3022    Record.push_back(Name.getCXXOverloadedOperator());
3023    break;
3024
3025  case DeclarationName::CXXLiteralOperatorName:
3026    AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3027    break;
3028
3029  case DeclarationName::CXXUsingDirective:
3030    // No extra data to emit
3031    break;
3032  }
3033}
3034
3035void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3036                                     DeclarationName Name, RecordDataImpl &Record) {
3037  switch (Name.getNameKind()) {
3038  case DeclarationName::CXXConstructorName:
3039  case DeclarationName::CXXDestructorName:
3040  case DeclarationName::CXXConversionFunctionName:
3041    AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3042    break;
3043
3044  case DeclarationName::CXXOperatorName:
3045    AddSourceLocation(
3046       SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3047       Record);
3048    AddSourceLocation(
3049        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3050        Record);
3051    break;
3052
3053  case DeclarationName::CXXLiteralOperatorName:
3054    AddSourceLocation(
3055     SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3056     Record);
3057    break;
3058
3059  case DeclarationName::Identifier:
3060  case DeclarationName::ObjCZeroArgSelector:
3061  case DeclarationName::ObjCOneArgSelector:
3062  case DeclarationName::ObjCMultiArgSelector:
3063  case DeclarationName::CXXUsingDirective:
3064    break;
3065  }
3066}
3067
3068void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3069                                       RecordDataImpl &Record) {
3070  AddDeclarationName(NameInfo.getName(), Record);
3071  AddSourceLocation(NameInfo.getLoc(), Record);
3072  AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3073}
3074
3075void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3076                                 RecordDataImpl &Record) {
3077  AddNestedNameSpecifier(Info.NNS, Record);
3078  AddSourceRange(Info.NNSRange, Record);
3079  Record.push_back(Info.NumTemplParamLists);
3080  for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3081    AddTemplateParameterList(Info.TemplParamLists[i], Record);
3082}
3083
3084void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3085                                       RecordDataImpl &Record) {
3086  // Nested name specifiers usually aren't too long. I think that 8 would
3087  // typically accomodate the vast majority.
3088  llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3089
3090  // Push each of the NNS's onto a stack for serialization in reverse order.
3091  while (NNS) {
3092    NestedNames.push_back(NNS);
3093    NNS = NNS->getPrefix();
3094  }
3095
3096  Record.push_back(NestedNames.size());
3097  while(!NestedNames.empty()) {
3098    NNS = NestedNames.pop_back_val();
3099    NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3100    Record.push_back(Kind);
3101    switch (Kind) {
3102    case NestedNameSpecifier::Identifier:
3103      AddIdentifierRef(NNS->getAsIdentifier(), Record);
3104      break;
3105
3106    case NestedNameSpecifier::Namespace:
3107      AddDeclRef(NNS->getAsNamespace(), Record);
3108      break;
3109
3110    case NestedNameSpecifier::TypeSpec:
3111    case NestedNameSpecifier::TypeSpecWithTemplate:
3112      AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3113      Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3114      break;
3115
3116    case NestedNameSpecifier::Global:
3117      // Don't need to write an associated value.
3118      break;
3119    }
3120  }
3121}
3122
3123void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3124  TemplateName::NameKind Kind = Name.getKind();
3125  Record.push_back(Kind);
3126  switch (Kind) {
3127  case TemplateName::Template:
3128    AddDeclRef(Name.getAsTemplateDecl(), Record);
3129    break;
3130
3131  case TemplateName::OverloadedTemplate: {
3132    OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3133    Record.push_back(OvT->size());
3134    for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3135           I != E; ++I)
3136      AddDeclRef(*I, Record);
3137    break;
3138  }
3139
3140  case TemplateName::QualifiedTemplate: {
3141    QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3142    AddNestedNameSpecifier(QualT->getQualifier(), Record);
3143    Record.push_back(QualT->hasTemplateKeyword());
3144    AddDeclRef(QualT->getTemplateDecl(), Record);
3145    break;
3146  }
3147
3148  case TemplateName::DependentTemplate: {
3149    DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3150    AddNestedNameSpecifier(DepT->getQualifier(), Record);
3151    Record.push_back(DepT->isIdentifier());
3152    if (DepT->isIdentifier())
3153      AddIdentifierRef(DepT->getIdentifier(), Record);
3154    else
3155      Record.push_back(DepT->getOperator());
3156    break;
3157  }
3158  }
3159}
3160
3161void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3162                                    RecordDataImpl &Record) {
3163  Record.push_back(Arg.getKind());
3164  switch (Arg.getKind()) {
3165  case TemplateArgument::Null:
3166    break;
3167  case TemplateArgument::Type:
3168    AddTypeRef(Arg.getAsType(), Record);
3169    break;
3170  case TemplateArgument::Declaration:
3171    AddDeclRef(Arg.getAsDecl(), Record);
3172    break;
3173  case TemplateArgument::Integral:
3174    AddAPSInt(*Arg.getAsIntegral(), Record);
3175    AddTypeRef(Arg.getIntegralType(), Record);
3176    break;
3177  case TemplateArgument::Template:
3178    AddTemplateName(Arg.getAsTemplate(), Record);
3179    break;
3180  case TemplateArgument::Expression:
3181    AddStmt(Arg.getAsExpr());
3182    break;
3183  case TemplateArgument::Pack:
3184    Record.push_back(Arg.pack_size());
3185    for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3186           I != E; ++I)
3187      AddTemplateArgument(*I, Record);
3188    break;
3189  }
3190}
3191
3192void
3193ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3194                                    RecordDataImpl &Record) {
3195  assert(TemplateParams && "No TemplateParams!");
3196  AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3197  AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3198  AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3199  Record.push_back(TemplateParams->size());
3200  for (TemplateParameterList::const_iterator
3201         P = TemplateParams->begin(), PEnd = TemplateParams->end();
3202         P != PEnd; ++P)
3203    AddDeclRef(*P, Record);
3204}
3205
3206/// \brief Emit a template argument list.
3207void
3208ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3209                                   RecordDataImpl &Record) {
3210  assert(TemplateArgs && "No TemplateArgs!");
3211  Record.push_back(TemplateArgs->size());
3212  for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3213    AddTemplateArgument(TemplateArgs->get(i), Record);
3214}
3215
3216
3217void
3218ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3219  Record.push_back(Set.size());
3220  for (UnresolvedSetImpl::const_iterator
3221         I = Set.begin(), E = Set.end(); I != E; ++I) {
3222    AddDeclRef(I.getDecl(), Record);
3223    Record.push_back(I.getAccess());
3224  }
3225}
3226
3227void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3228                                    RecordDataImpl &Record) {
3229  Record.push_back(Base.isVirtual());
3230  Record.push_back(Base.isBaseOfClass());
3231  Record.push_back(Base.getAccessSpecifierAsWritten());
3232  AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3233  AddSourceRange(Base.getSourceRange(), Record);
3234  AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3235                                          : SourceLocation(),
3236                    Record);
3237}
3238
3239void ASTWriter::FlushCXXBaseSpecifiers() {
3240  RecordData Record;
3241  for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3242    Record.clear();
3243
3244    // Record the offset of this base-specifier set.
3245    unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3246    if (Index == CXXBaseSpecifiersOffsets.size())
3247      CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3248    else {
3249      if (Index > CXXBaseSpecifiersOffsets.size())
3250        CXXBaseSpecifiersOffsets.resize(Index + 1);
3251      CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3252    }
3253
3254    const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3255                        *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3256    Record.push_back(BEnd - B);
3257    for (; B != BEnd; ++B)
3258      AddCXXBaseSpecifier(*B, Record);
3259    Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3260
3261    // Flush any expressions that were written as part of the base specifiers.
3262    FlushStmts();
3263  }
3264
3265  CXXBaseSpecifiersToWrite.clear();
3266}
3267
3268void ASTWriter::AddCXXBaseOrMemberInitializers(
3269                        const CXXBaseOrMemberInitializer * const *BaseOrMembers,
3270                        unsigned NumBaseOrMembers, RecordDataImpl &Record) {
3271  Record.push_back(NumBaseOrMembers);
3272  for (unsigned i=0; i != NumBaseOrMembers; ++i) {
3273    const CXXBaseOrMemberInitializer *Init = BaseOrMembers[i];
3274
3275    Record.push_back(Init->isBaseInitializer());
3276    if (Init->isBaseInitializer()) {
3277      AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3278      Record.push_back(Init->isBaseVirtual());
3279    } else {
3280      Record.push_back(Init->isIndirectMemberInitializer());
3281      if (Init->isIndirectMemberInitializer())
3282        AddDeclRef(Init->getIndirectMember(), Record);
3283      else
3284        AddDeclRef(Init->getMember(), Record);
3285    }
3286
3287    AddSourceLocation(Init->getMemberLocation(), Record);
3288    AddStmt(Init->getInit());
3289    AddSourceLocation(Init->getLParenLoc(), Record);
3290    AddSourceLocation(Init->getRParenLoc(), Record);
3291    Record.push_back(Init->isWritten());
3292    if (Init->isWritten()) {
3293      Record.push_back(Init->getSourceOrder());
3294    } else {
3295      Record.push_back(Init->getNumArrayIndices());
3296      for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3297        AddDeclRef(Init->getArrayIndex(i), Record);
3298    }
3299  }
3300}
3301
3302void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3303  assert(D->DefinitionData);
3304  struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3305  Record.push_back(Data.UserDeclaredConstructor);
3306  Record.push_back(Data.UserDeclaredCopyConstructor);
3307  Record.push_back(Data.UserDeclaredCopyAssignment);
3308  Record.push_back(Data.UserDeclaredDestructor);
3309  Record.push_back(Data.Aggregate);
3310  Record.push_back(Data.PlainOldData);
3311  Record.push_back(Data.Empty);
3312  Record.push_back(Data.Polymorphic);
3313  Record.push_back(Data.Abstract);
3314  Record.push_back(Data.HasTrivialConstructor);
3315  Record.push_back(Data.HasTrivialCopyConstructor);
3316  Record.push_back(Data.HasTrivialCopyAssignment);
3317  Record.push_back(Data.HasTrivialDestructor);
3318  Record.push_back(Data.ComputedVisibleConversions);
3319  Record.push_back(Data.DeclaredDefaultConstructor);
3320  Record.push_back(Data.DeclaredCopyConstructor);
3321  Record.push_back(Data.DeclaredCopyAssignment);
3322  Record.push_back(Data.DeclaredDestructor);
3323
3324  Record.push_back(Data.NumBases);
3325  if (Data.NumBases > 0)
3326    AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3327                            Record);
3328
3329  // FIXME: Make VBases lazily computed when needed to avoid storing them.
3330  Record.push_back(Data.NumVBases);
3331  if (Data.NumVBases > 0)
3332    AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3333                            Record);
3334
3335  AddUnresolvedSet(Data.Conversions, Record);
3336  AddUnresolvedSet(Data.VisibleConversions, Record);
3337  // Data.Definition is the owning decl, no need to write it.
3338  AddDeclRef(Data.FirstFriend, Record);
3339}
3340
3341void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3342  assert(Reader && "Cannot remove chain");
3343  assert(!Chain && "Cannot replace chain");
3344  assert(FirstDeclID == NextDeclID &&
3345         FirstTypeID == NextTypeID &&
3346         FirstIdentID == NextIdentID &&
3347         FirstSelectorID == NextSelectorID &&
3348         FirstMacroID == NextMacroID &&
3349         FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3350         "Setting chain after writing has started.");
3351  Chain = Reader;
3352
3353  FirstDeclID += Chain->getTotalNumDecls();
3354  FirstTypeID += Chain->getTotalNumTypes();
3355  FirstIdentID += Chain->getTotalNumIdentifiers();
3356  FirstSelectorID += Chain->getTotalNumSelectors();
3357  FirstMacroID += Chain->getTotalNumMacroDefinitions();
3358  FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3359  NextDeclID = FirstDeclID;
3360  NextTypeID = FirstTypeID;
3361  NextIdentID = FirstIdentID;
3362  NextSelectorID = FirstSelectorID;
3363  NextMacroID = FirstMacroID;
3364  NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3365}
3366
3367void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3368  IdentifierIDs[II] = ID;
3369}
3370
3371void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3372  // Always take the highest-numbered type index. This copes with an interesting
3373  // case for chained AST writing where we schedule writing the type and then,
3374  // later, deserialize the type from another AST. In this case, we want to
3375  // keep the higher-numbered entry so that we can properly write it out to
3376  // the AST file.
3377  TypeIdx &StoredIdx = TypeIdxs[T];
3378  if (Idx.getIndex() >= StoredIdx.getIndex())
3379    StoredIdx = Idx;
3380}
3381
3382void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3383  DeclIDs[D] = ID;
3384}
3385
3386void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3387  SelectorIDs[S] = ID;
3388}
3389
3390void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3391                                    MacroDefinition *MD) {
3392  MacroDefinitions[MD] = ID;
3393}
3394
3395void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3396  assert(D->isDefinition());
3397  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3398    // We are interested when a PCH decl is modified.
3399    if (RD->getPCHLevel() > 0) {
3400      // A forward reference was mutated into a definition. Rewrite it.
3401      // FIXME: This happens during template instantiation, should we
3402      // have created a new definition decl instead ?
3403      RewriteDecl(RD);
3404    }
3405
3406    for (CXXRecordDecl::redecl_iterator
3407           I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3408      CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3409      if (Redecl == RD)
3410        continue;
3411
3412      // We are interested when a PCH decl is modified.
3413      if (Redecl->getPCHLevel() > 0) {
3414        UpdateRecord &Record = DeclUpdates[Redecl];
3415        Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3416        assert(Redecl->DefinitionData);
3417        assert(Redecl->DefinitionData->Definition == D);
3418        AddDeclRef(D, Record); // the DefinitionDecl
3419      }
3420    }
3421  }
3422}
3423void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
3424  // TU and namespaces are handled elsewhere.
3425  if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
3426    return;
3427
3428  if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
3429    return; // Not a source decl added to a DeclContext from PCH.
3430
3431  AddUpdatedDeclContext(DC);
3432}
3433
3434void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
3435  assert(D->isImplicit());
3436  if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
3437    return; // Not a source member added to a class from PCH.
3438  if (!isa<CXXMethodDecl>(D))
3439    return; // We are interested in lazily declared implicit methods.
3440
3441  // A decl coming from PCH was modified.
3442  assert(RD->isDefinition());
3443  UpdateRecord &Record = DeclUpdates[RD];
3444  Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
3445  AddDeclRef(D, Record);
3446}
3447
3448void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
3449                                     const ClassTemplateSpecializationDecl *D) {
3450  // The specializations set is kept in the canonical template.
3451  TD = TD->getCanonicalDecl();
3452  if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
3453    return; // Not a source specialization added to a template from PCH.
3454
3455  UpdateRecord &Record = DeclUpdates[TD];
3456  Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
3457  AddDeclRef(D, Record);
3458}
3459
3460ASTSerializationListener::~ASTSerializationListener() { }
3461