blob: ba53bdaffb189a4c5ad08162b175451c09829f4a [file] [log] [blame]
Sebastian Redl4ee2ad02010-08-18 23:56:31 +00001//===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redla4232eb2010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregor2cf26342009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0eca89e2010-08-20 16:03:52 +000015#include "ASTCommon.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +000019#include "clang/AST/DeclFriend.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/DeclTemplate.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
John McCall7a1fad32010-08-24 07:32:53 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000023#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Chris Lattner10e286a2010-11-23 19:19:34 +000026#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregor57016dd2012-10-16 23:40:58 +000031#include "clang/Basic/TargetOptions.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000032#include "clang/Basic/Version.h"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000033#include "clang/Basic/VersionTuple.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/IdentifierResolver.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTReader.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000043#include "llvm/ADT/APFloat.h"
44#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +000045#include "llvm/ADT/Hashing.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000046#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000047#include "llvm/Bitcode/BitstreamWriter.h"
Michael J. Spencerfbfd1802010-12-21 16:45:57 +000048#include "llvm/Support/FileSystem.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000049#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000050#include "llvm/Support/Path.h"
Douglas Gregorf62d43d2011-07-19 16:10:42 +000051#include <algorithm>
Chris Lattner3c304bd2009-04-11 18:40:46 +000052#include <cstdio>
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000053#include <string.h>
Douglas Gregorf62d43d2011-07-19 16:10:42 +000054#include <utility>
Douglas Gregor2cf26342009-04-09 22:27:44 +000055using namespace clang;
Sebastian Redl8538e8d2010-08-18 23:57:32 +000056using namespace clang::serialization;
Douglas Gregor2cf26342009-04-09 22:27:44 +000057
Sebastian Redlade50002010-07-30 17:03:48 +000058template <typename T, typename Allocator>
Chris Lattner5f9e2722011-07-23 10:55:15 +000059static StringRef data(const std::vector<T, Allocator> &v) {
60 if (v.empty()) return StringRef();
61 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramer6e089c62011-04-24 17:44:50 +000062 sizeof(T) * v.size());
Sebastian Redlade50002010-07-30 17:03:48 +000063}
Benjamin Kramer6e089c62011-04-24 17:44:50 +000064
65template <typename T>
Chris Lattner5f9e2722011-07-23 10:55:15 +000066static StringRef data(const SmallVectorImpl<T> &v) {
67 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramer6e089c62011-04-24 17:44:50 +000068 sizeof(T) * v.size());
Sebastian Redlade50002010-07-30 17:03:48 +000069}
70
Douglas Gregor2cf26342009-04-09 22:27:44 +000071//===----------------------------------------------------------------------===//
72// Type serialization
73//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000074
Douglas Gregor2cf26342009-04-09 22:27:44 +000075namespace {
Sebastian Redl3397c552010-08-18 23:56:27 +000076 class ASTTypeWriter {
Sebastian Redla4232eb2010-08-18 23:56:21 +000077 ASTWriter &Writer;
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +000078 ASTWriter::RecordDataImpl &Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +000079
80 public:
81 /// \brief Type code that corresponds to the record generated.
Sebastian Redl8538e8d2010-08-18 23:57:32 +000082 TypeCode Code;
Douglas Gregor2cf26342009-04-09 22:27:44 +000083
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +000084 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Sebastian Redl8538e8d2010-08-18 23:57:32 +000085 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000086
87 void VisitArrayType(const ArrayType *T);
88 void VisitFunctionType(const FunctionType *T);
89 void VisitTagType(const TagType *T);
90
91#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
92#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor2cf26342009-04-09 22:27:44 +000093#include "clang/AST/TypeNodes.def"
94 };
95}
96
Sebastian Redl3397c552010-08-18 23:56:27 +000097void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikieb219cfc2011-09-23 05:06:16 +000098 llvm_unreachable("Built-in types are never serialized");
Douglas Gregor2cf26342009-04-09 22:27:44 +000099}
100
Sebastian Redl3397c552010-08-18 23:56:27 +0000101void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000102 Writer.AddTypeRef(T->getElementType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000103 Code = TYPE_COMPLEX;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104}
105
Sebastian Redl3397c552010-08-18 23:56:27 +0000106void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000107 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000108 Code = TYPE_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000109}
110
Sebastian Redl3397c552010-08-18 23:56:27 +0000111void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000112 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000113 Code = TYPE_BLOCK_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000114}
115
Sebastian Redl3397c552010-08-18 23:56:27 +0000116void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smithdf1550f2011-04-12 10:38:03 +0000117 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
118 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000119 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000120}
121
Sebastian Redl3397c552010-08-18 23:56:27 +0000122void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smithdf1550f2011-04-12 10:38:03 +0000123 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000124 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000125}
126
Sebastian Redl3397c552010-08-18 23:56:27 +0000127void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000128 Writer.AddTypeRef(T->getPointeeType(), Record);
129 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000130 Code = TYPE_MEMBER_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000131}
132
Sebastian Redl3397c552010-08-18 23:56:27 +0000133void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000134 Writer.AddTypeRef(T->getElementType(), Record);
135 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall0953e762009-09-24 19:53:00 +0000136 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregor2cf26342009-04-09 22:27:44 +0000137}
138
Sebastian Redl3397c552010-08-18 23:56:27 +0000139void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000140 VisitArrayType(T);
141 Writer.AddAPInt(T->getSize(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000142 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000143}
144
Sebastian Redl3397c552010-08-18 23:56:27 +0000145void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000146 VisitArrayType(T);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000147 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000148}
149
Sebastian Redl3397c552010-08-18 23:56:27 +0000150void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000151 VisitArrayType(T);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000152 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
153 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000154 Writer.AddStmt(T->getSizeExpr());
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000155 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000156}
157
Sebastian Redl3397c552010-08-18 23:56:27 +0000158void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000159 Writer.AddTypeRef(T->getElementType(), Record);
160 Record.push_back(T->getNumElements());
Bob Wilsone86d78c2010-11-10 21:56:12 +0000161 Record.push_back(T->getVectorKind());
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000162 Code = TYPE_VECTOR;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000163}
164
Sebastian Redl3397c552010-08-18 23:56:27 +0000165void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000166 VisitVectorType(T);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000167 Code = TYPE_EXT_VECTOR;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000168}
169
Sebastian Redl3397c552010-08-18 23:56:27 +0000170void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000171 Writer.AddTypeRef(T->getResultType(), Record);
Rafael Espindola264ba482010-03-30 20:24:48 +0000172 FunctionType::ExtInfo C = T->getExtInfo();
173 Record.push_back(C.getNoReturn());
Eli Friedmana49218e2011-04-09 08:18:08 +0000174 Record.push_back(C.getHasRegParm());
Rafael Espindola425ef722010-03-30 22:15:11 +0000175 Record.push_back(C.getRegParm());
Douglas Gregorab8bbf42010-01-18 17:14:39 +0000176 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindola264ba482010-03-30 20:24:48 +0000177 Record.push_back(C.getCC());
John McCallf85e1932011-06-15 23:02:42 +0000178 Record.push_back(C.getProducesResult());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000179}
180
Sebastian Redl3397c552010-08-18 23:56:27 +0000181void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000182 VisitFunctionType(T);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000183 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000184}
185
Sebastian Redl3397c552010-08-18 23:56:27 +0000186void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000187 VisitFunctionType(T);
188 Record.push_back(T->getNumArgs());
189 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
190 Writer.AddTypeRef(T->getArgType(I), Record);
191 Record.push_back(T->isVariadic());
Richard Smitheefb3d52012-02-10 09:58:53 +0000192 Record.push_back(T->hasTrailingReturn());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193 Record.push_back(T->getTypeQuals());
Douglas Gregorc938c162011-01-26 05:01:58 +0000194 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Sebastian Redl60618fa2011-03-12 11:50:43 +0000195 Record.push_back(T->getExceptionSpecType());
196 if (T->getExceptionSpecType() == EST_Dynamic) {
197 Record.push_back(T->getNumExceptions());
198 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
199 Writer.AddTypeRef(T->getExceptionType(I), Record);
200 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
201 Writer.AddStmt(T->getNoexceptExpr());
Richard Smith7bb698a2012-04-21 17:47:47 +0000202 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
203 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
204 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
Richard Smithb9d0b762012-07-27 04:22:15 +0000205 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
206 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000207 }
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000208 Code = TYPE_FUNCTION_PROTO;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000209}
210
Sebastian Redl3397c552010-08-18 23:56:27 +0000211void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
John McCalled976492009-12-04 22:46:56 +0000212 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000213 Code = TYPE_UNRESOLVED_USING;
John McCalled976492009-12-04 22:46:56 +0000214}
John McCalled976492009-12-04 22:46:56 +0000215
Sebastian Redl3397c552010-08-18 23:56:27 +0000216void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000217 Writer.AddDeclRef(T->getDecl(), Record);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +0000218 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
219 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000220 Code = TYPE_TYPEDEF;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000221}
222
Sebastian Redl3397c552010-08-18 23:56:27 +0000223void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000224 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000225 Code = TYPE_TYPEOF_EXPR;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000226}
227
Sebastian Redl3397c552010-08-18 23:56:27 +0000228void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000229 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000230 Code = TYPE_TYPEOF;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000231}
232
Sebastian Redl3397c552010-08-18 23:56:27 +0000233void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Douglas Gregorf8af9822012-02-12 18:42:33 +0000234 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Anders Carlsson395b4752009-06-24 19:06:50 +0000235 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000236 Code = TYPE_DECLTYPE;
Anders Carlsson395b4752009-06-24 19:06:50 +0000237}
238
Sean Huntca63c202011-05-24 22:41:36 +0000239void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
240 Writer.AddTypeRef(T->getBaseType(), Record);
241 Writer.AddTypeRef(T->getUnderlyingType(), Record);
242 Record.push_back(T->getUTTKind());
243 Code = TYPE_UNARY_TRANSFORM;
244}
245
Richard Smith34b41d92011-02-20 03:19:35 +0000246void ASTTypeWriter::VisitAutoType(const AutoType *T) {
247 Writer.AddTypeRef(T->getDeducedType(), Record);
Richard Smitha2c36462013-04-26 16:15:35 +0000248 Record.push_back(T->isDecltypeAuto());
Richard Smith34b41d92011-02-20 03:19:35 +0000249 Code = TYPE_AUTO;
250}
251
Sebastian Redl3397c552010-08-18 23:56:27 +0000252void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +0000253 Record.push_back(T->isDependentType());
Douglas Gregor56ca8a92012-01-17 19:21:53 +0000254 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +0000255 assert(!T->isBeingDefined() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +0000256 "Cannot serialize in the middle of a type definition");
257}
258
Sebastian Redl3397c552010-08-18 23:56:27 +0000259void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000260 VisitTagType(T);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000261 Code = TYPE_RECORD;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000262}
263
Sebastian Redl3397c552010-08-18 23:56:27 +0000264void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000265 VisitTagType(T);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000266 Code = TYPE_ENUM;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000267}
268
John McCall9d156a72011-01-06 01:58:22 +0000269void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
270 Writer.AddTypeRef(T->getModifiedType(), Record);
271 Writer.AddTypeRef(T->getEquivalentType(), Record);
272 Record.push_back(T->getAttrKind());
273 Code = TYPE_ATTRIBUTED;
274}
275
Mike Stump1eb44332009-09-09 15:08:12 +0000276void
Sebastian Redl3397c552010-08-18 23:56:27 +0000277ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCall49a832b2009-10-18 09:09:24 +0000278 const SubstTemplateTypeParmType *T) {
279 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
280 Writer.AddTypeRef(T->getReplacementType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000281 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCall49a832b2009-10-18 09:09:24 +0000282}
283
284void
Douglas Gregorc3069d62011-01-14 02:55:32 +0000285ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
286 const SubstTemplateTypeParmPackType *T) {
287 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
288 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
289 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
290}
291
292void
Sebastian Redl3397c552010-08-18 23:56:27 +0000293ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregor2cf26342009-04-09 22:27:44 +0000294 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +0000295 Record.push_back(T->isDependentType());
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000296 Writer.AddTemplateName(T->getTemplateName(), Record);
297 Record.push_back(T->getNumArgs());
298 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
299 ArgI != ArgE; ++ArgI)
300 Writer.AddTemplateArgument(*ArgI, Record);
Richard Smith3e4c6c42011-05-05 21:57:07 +0000301 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
302 T->isCanonicalUnqualified() ? QualType()
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +0000303 : T->getCanonicalTypeInternal(),
304 Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000305 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000306}
307
308void
Sebastian Redl3397c552010-08-18 23:56:27 +0000309ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +0000310 VisitArrayType(T);
311 Writer.AddStmt(T->getSizeExpr());
312 Writer.AddSourceRange(T->getBracketsRange(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000313 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000314}
315
316void
Sebastian Redl3397c552010-08-18 23:56:27 +0000317ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000318 const DependentSizedExtVectorType *T) {
319 // FIXME: Serialize this type (C++ only)
David Blaikieb219cfc2011-09-23 05:06:16 +0000320 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000321}
322
323void
Sebastian Redl3397c552010-08-18 23:56:27 +0000324ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000325 Record.push_back(T->getDepth());
326 Record.push_back(T->getIndex());
327 Record.push_back(T->isParameterPack());
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000328 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000329 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000330}
331
332void
Sebastian Redl3397c552010-08-18 23:56:27 +0000333ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +0000334 Record.push_back(T->getKeyword());
335 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
336 Writer.AddIdentifierRef(T->getIdentifier(), Record);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +0000337 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
338 : T->getCanonicalTypeInternal(),
339 Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000340 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000341}
342
343void
Sebastian Redl3397c552010-08-18 23:56:27 +0000344ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +0000345 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +0000346 Record.push_back(T->getKeyword());
347 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
348 Writer.AddIdentifierRef(T->getIdentifier(), Record);
349 Record.push_back(T->getNumArgs());
350 for (DependentTemplateSpecializationType::iterator
351 I = T->begin(), E = T->end(); I != E; ++I)
352 Writer.AddTemplateArgument(*I, Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000353 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000354}
355
Douglas Gregor7536dd52010-12-20 02:24:11 +0000356void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
357 Writer.AddTypeRef(T->getPattern(), Record);
David Blaikiedc84cd52013-02-20 22:23:23 +0000358 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregorcded4f62011-01-14 17:04:44 +0000359 Record.push_back(*NumExpansions + 1);
360 else
361 Record.push_back(0);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000362 Code = TYPE_PACK_EXPANSION;
363}
364
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000365void ASTTypeWriter::VisitParenType(const ParenType *T) {
366 Writer.AddTypeRef(T->getInnerType(), Record);
367 Code = TYPE_PAREN;
368}
369
Sebastian Redl3397c552010-08-18 23:56:27 +0000370void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000371 Record.push_back(T->getKeyword());
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +0000372 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
373 Writer.AddTypeRef(T->getNamedType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000374 Code = TYPE_ELABORATED;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000375}
376
Sebastian Redl3397c552010-08-18 23:56:27 +0000377void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Douglas Gregora8e0b972012-03-26 15:52:37 +0000378 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
John McCall31f17ec2010-04-27 00:57:59 +0000379 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000380 Code = TYPE_INJECTED_CLASS_NAME;
John McCall3cb0ebd2010-03-10 03:28:59 +0000381}
382
Sebastian Redl3397c552010-08-18 23:56:27 +0000383void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Douglas Gregor56ca8a92012-01-17 19:21:53 +0000384 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000385 Code = TYPE_OBJC_INTERFACE;
John McCallc12c5bb2010-05-15 11:32:37 +0000386}
387
Sebastian Redl3397c552010-08-18 23:56:27 +0000388void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
John McCallc12c5bb2010-05-15 11:32:37 +0000389 Writer.AddTypeRef(T->getBaseType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000390 Record.push_back(T->getNumProtocols());
John McCallc12c5bb2010-05-15 11:32:37 +0000391 for (ObjCObjectType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000392 E = T->qual_end(); I != E; ++I)
393 Writer.AddDeclRef(*I, Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000394 Code = TYPE_OBJC_OBJECT;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000395}
396
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000397void
Sebastian Redl3397c552010-08-18 23:56:27 +0000398ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000399 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000400 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000401}
402
Eli Friedmanb001de72011-10-06 23:00:33 +0000403void
404ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
405 Writer.AddTypeRef(T->getValueType(), Record);
406 Code = TYPE_ATOMIC;
407}
408
John McCalla1ee0c52009-10-16 21:56:05 +0000409namespace {
410
411class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Sebastian Redla4232eb2010-08-18 23:56:21 +0000412 ASTWriter &Writer;
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +0000413 ASTWriter::RecordDataImpl &Record;
John McCalla1ee0c52009-10-16 21:56:05 +0000414
415public:
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +0000416 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
John McCalla1ee0c52009-10-16 21:56:05 +0000417 : Writer(Writer), Record(Record) { }
418
John McCall51bd8032009-10-18 01:05:36 +0000419#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +0000420#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +0000421 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +0000422#include "clang/AST/TypeLocNodes.def"
423
John McCall51bd8032009-10-18 01:05:36 +0000424 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
425 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +0000426};
427
428}
429
John McCall51bd8032009-10-18 01:05:36 +0000430void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
431 // nothing to do
John McCalla1ee0c52009-10-16 21:56:05 +0000432}
John McCall51bd8032009-10-18 01:05:36 +0000433void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +0000434 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
435 if (TL.needsExtraLocalData()) {
436 Record.push_back(TL.getWrittenTypeSpec());
437 Record.push_back(TL.getWrittenSignSpec());
438 Record.push_back(TL.getWrittenWidthSpec());
439 Record.push_back(TL.hasModeAttr());
440 }
John McCalla1ee0c52009-10-16 21:56:05 +0000441}
John McCall51bd8032009-10-18 01:05:36 +0000442void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
443 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000444}
John McCall51bd8032009-10-18 01:05:36 +0000445void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
446 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000447}
John McCall51bd8032009-10-18 01:05:36 +0000448void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
449 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000450}
John McCall51bd8032009-10-18 01:05:36 +0000451void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
452 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000453}
John McCall51bd8032009-10-18 01:05:36 +0000454void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
455 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000456}
John McCall51bd8032009-10-18 01:05:36 +0000457void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
458 Writer.AddSourceLocation(TL.getStarLoc(), Record);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +0000459 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000460}
John McCall51bd8032009-10-18 01:05:36 +0000461void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
462 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
463 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
464 Record.push_back(TL.getSizeExpr() ? 1 : 0);
465 if (TL.getSizeExpr())
466 Writer.AddStmt(TL.getSizeExpr());
John McCalla1ee0c52009-10-16 21:56:05 +0000467}
John McCall51bd8032009-10-18 01:05:36 +0000468void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
469 VisitArrayTypeLoc(TL);
470}
471void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
472 VisitArrayTypeLoc(TL);
473}
474void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
475 VisitArrayTypeLoc(TL);
476}
477void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
478 DependentSizedArrayTypeLoc TL) {
479 VisitArrayTypeLoc(TL);
480}
481void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
482 DependentSizedExtVectorTypeLoc TL) {
483 Writer.AddSourceLocation(TL.getNameLoc(), Record);
484}
485void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
486 Writer.AddSourceLocation(TL.getNameLoc(), Record);
487}
488void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
489 Writer.AddSourceLocation(TL.getNameLoc(), Record);
490}
491void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnara796aa442011-03-12 11:17:06 +0000492 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000493 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
494 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
Abramo Bagnara796aa442011-03-12 11:17:06 +0000495 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000496 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
497 Writer.AddDeclRef(TL.getArg(i), Record);
498}
499void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
500 VisitFunctionTypeLoc(TL);
501}
502void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
503 VisitFunctionTypeLoc(TL);
504}
John McCalled976492009-12-04 22:46:56 +0000505void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
506 Writer.AddSourceLocation(TL.getNameLoc(), Record);
507}
John McCall51bd8032009-10-18 01:05:36 +0000508void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
509 Writer.AddSourceLocation(TL.getNameLoc(), Record);
510}
511void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +0000512 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
513 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
514 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000515}
516void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +0000517 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
518 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
519 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
520 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000521}
522void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
523 Writer.AddSourceLocation(TL.getNameLoc(), Record);
524}
Sean Huntca63c202011-05-24 22:41:36 +0000525void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
526 Writer.AddSourceLocation(TL.getKWLoc(), Record);
527 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
528 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
529 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
530}
Richard Smith34b41d92011-02-20 03:19:35 +0000531void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
532 Writer.AddSourceLocation(TL.getNameLoc(), Record);
533}
John McCall51bd8032009-10-18 01:05:36 +0000534void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
535 Writer.AddSourceLocation(TL.getNameLoc(), Record);
536}
537void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
538 Writer.AddSourceLocation(TL.getNameLoc(), Record);
539}
John McCall9d156a72011-01-06 01:58:22 +0000540void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
541 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
542 if (TL.hasAttrOperand()) {
543 SourceRange range = TL.getAttrOperandParensRange();
544 Writer.AddSourceLocation(range.getBegin(), Record);
545 Writer.AddSourceLocation(range.getEnd(), Record);
546 }
547 if (TL.hasAttrExprOperand()) {
548 Expr *operand = TL.getAttrExprOperand();
549 Record.push_back(operand ? 1 : 0);
550 if (operand) Writer.AddStmt(operand);
551 } else if (TL.hasAttrEnumOperand()) {
552 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
553 }
554}
John McCall51bd8032009-10-18 01:05:36 +0000555void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
556 Writer.AddSourceLocation(TL.getNameLoc(), Record);
557}
John McCall49a832b2009-10-18 09:09:24 +0000558void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
559 SubstTemplateTypeParmTypeLoc TL) {
560 Writer.AddSourceLocation(TL.getNameLoc(), Record);
561}
Douglas Gregorc3069d62011-01-14 02:55:32 +0000562void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
563 SubstTemplateTypeParmPackTypeLoc TL) {
564 Writer.AddSourceLocation(TL.getNameLoc(), Record);
565}
John McCall51bd8032009-10-18 01:05:36 +0000566void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
567 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000568 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
John McCall833ca992009-10-29 08:12:44 +0000569 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
570 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
571 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
572 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +0000573 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
574 TL.getArgLoc(i).getLocInfo(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000575}
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000576void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
577 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
578 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
579}
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000580void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +0000581 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor9e876872011-03-01 18:12:44 +0000582 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000583}
John McCall3cb0ebd2010-03-10 03:28:59 +0000584void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
585 Writer.AddSourceLocation(TL.getNameLoc(), Record);
586}
Douglas Gregor4714c122010-03-31 17:34:00 +0000587void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +0000588 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000589 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall51bd8032009-10-18 01:05:36 +0000590 Writer.AddSourceLocation(TL.getNameLoc(), Record);
591}
John McCall33500952010-06-11 00:33:02 +0000592void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
593 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000594 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000595 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
Abramo Bagnara66581d42012-02-06 22:45:07 +0000596 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000597 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
John McCall33500952010-06-11 00:33:02 +0000598 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
599 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
600 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +0000601 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
602 TL.getArgLoc(I).getLocInfo(), Record);
John McCall33500952010-06-11 00:33:02 +0000603}
Douglas Gregor7536dd52010-12-20 02:24:11 +0000604void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
605 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
606}
John McCall51bd8032009-10-18 01:05:36 +0000607void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
608 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCallc12c5bb2010-05-15 11:32:37 +0000609}
610void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
611 Record.push_back(TL.hasBaseTypeAsWritten());
John McCall51bd8032009-10-18 01:05:36 +0000612 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
613 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
614 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
615 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
John McCalla1ee0c52009-10-16 21:56:05 +0000616}
John McCall54e14c42009-10-22 22:37:11 +0000617void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
618 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCall54e14c42009-10-22 22:37:11 +0000619}
Eli Friedmanb001de72011-10-06 23:00:33 +0000620void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
621 Writer.AddSourceLocation(TL.getKWLoc(), Record);
622 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
623 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
624}
John McCalla1ee0c52009-10-16 21:56:05 +0000625
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000626//===----------------------------------------------------------------------===//
Sebastian Redla4232eb2010-08-18 23:56:21 +0000627// ASTWriter Implementation
Douglas Gregor2cf26342009-04-09 22:27:44 +0000628//===----------------------------------------------------------------------===//
629
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000630static void EmitBlockID(unsigned ID, const char *Name,
631 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +0000632 ASTWriter::RecordDataImpl &Record) {
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000633 Record.clear();
634 Record.push_back(ID);
635 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
636
637 // Emit the block name if present.
638 if (Name == 0 || Name[0] == 0) return;
639 Record.clear();
640 while (*Name)
641 Record.push_back(*Name++);
642 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
643}
644
645static void EmitRecordID(unsigned ID, const char *Name,
646 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +0000647 ASTWriter::RecordDataImpl &Record) {
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000648 Record.clear();
649 Record.push_back(ID);
650 while (*Name)
651 Record.push_back(*Name++);
652 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000653}
654
655static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +0000656 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000657#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattner0558df22009-04-27 00:49:53 +0000658 RECORD(STMT_STOP);
659 RECORD(STMT_NULL_PTR);
660 RECORD(STMT_NULL);
661 RECORD(STMT_COMPOUND);
662 RECORD(STMT_CASE);
663 RECORD(STMT_DEFAULT);
664 RECORD(STMT_LABEL);
Richard Smith534986f2012-04-14 00:33:13 +0000665 RECORD(STMT_ATTRIBUTED);
Chris Lattner0558df22009-04-27 00:49:53 +0000666 RECORD(STMT_IF);
667 RECORD(STMT_SWITCH);
668 RECORD(STMT_WHILE);
669 RECORD(STMT_DO);
670 RECORD(STMT_FOR);
671 RECORD(STMT_GOTO);
672 RECORD(STMT_INDIRECT_GOTO);
673 RECORD(STMT_CONTINUE);
674 RECORD(STMT_BREAK);
675 RECORD(STMT_RETURN);
676 RECORD(STMT_DECL);
Chad Rosierdf5faf52012-08-25 00:11:56 +0000677 RECORD(STMT_GCCASM);
Chad Rosiercd518a02012-08-24 23:51:02 +0000678 RECORD(STMT_MSASM);
Chris Lattner0558df22009-04-27 00:49:53 +0000679 RECORD(EXPR_PREDEFINED);
680 RECORD(EXPR_DECL_REF);
681 RECORD(EXPR_INTEGER_LITERAL);
682 RECORD(EXPR_FLOATING_LITERAL);
683 RECORD(EXPR_IMAGINARY_LITERAL);
684 RECORD(EXPR_STRING_LITERAL);
685 RECORD(EXPR_CHARACTER_LITERAL);
686 RECORD(EXPR_PAREN);
687 RECORD(EXPR_UNARY_OPERATOR);
688 RECORD(EXPR_SIZEOF_ALIGN_OF);
689 RECORD(EXPR_ARRAY_SUBSCRIPT);
690 RECORD(EXPR_CALL);
691 RECORD(EXPR_MEMBER);
692 RECORD(EXPR_BINARY_OPERATOR);
693 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
694 RECORD(EXPR_CONDITIONAL_OPERATOR);
695 RECORD(EXPR_IMPLICIT_CAST);
696 RECORD(EXPR_CSTYLE_CAST);
697 RECORD(EXPR_COMPOUND_LITERAL);
698 RECORD(EXPR_EXT_VECTOR_ELEMENT);
699 RECORD(EXPR_INIT_LIST);
700 RECORD(EXPR_DESIGNATED_INIT);
701 RECORD(EXPR_IMPLICIT_VALUE_INIT);
702 RECORD(EXPR_VA_ARG);
703 RECORD(EXPR_ADDR_LABEL);
704 RECORD(EXPR_STMT);
Chris Lattner0558df22009-04-27 00:49:53 +0000705 RECORD(EXPR_CHOOSE);
706 RECORD(EXPR_GNU_NULL);
707 RECORD(EXPR_SHUFFLE_VECTOR);
708 RECORD(EXPR_BLOCK);
Peter Collingbournef111d932011-04-15 00:35:48 +0000709 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattner0558df22009-04-27 00:49:53 +0000710 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000711 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000712 RECORD(EXPR_OBJC_ARRAY_LITERAL);
713 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattner0558df22009-04-27 00:49:53 +0000714 RECORD(EXPR_OBJC_ENCODE);
715 RECORD(EXPR_OBJC_SELECTOR_EXPR);
716 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
717 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
718 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
719 RECORD(EXPR_OBJC_KVC_REF_EXPR);
720 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattner0558df22009-04-27 00:49:53 +0000721 RECORD(STMT_OBJC_FOR_COLLECTION);
722 RECORD(STMT_OBJC_CATCH);
723 RECORD(STMT_OBJC_FINALLY);
724 RECORD(STMT_OBJC_AT_TRY);
725 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
726 RECORD(STMT_OBJC_AT_THROW);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000727 RECORD(EXPR_OBJC_BOOL_LITERAL);
Sam Weinigeb7f9612010-02-07 06:32:43 +0000728 RECORD(EXPR_CXX_OPERATOR_CALL);
729 RECORD(EXPR_CXX_CONSTRUCT);
730 RECORD(EXPR_CXX_STATIC_CAST);
731 RECORD(EXPR_CXX_DYNAMIC_CAST);
732 RECORD(EXPR_CXX_REINTERPRET_CAST);
733 RECORD(EXPR_CXX_CONST_CAST);
734 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smith9fcce652012-03-07 08:35:16 +0000735 RECORD(EXPR_USER_DEFINED_LITERAL);
Sam Weinigeb7f9612010-02-07 06:32:43 +0000736 RECORD(EXPR_CXX_BOOL_LITERAL);
737 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000738 RECORD(EXPR_CXX_TYPEID_EXPR);
739 RECORD(EXPR_CXX_TYPEID_TYPE);
740 RECORD(EXPR_CXX_UUIDOF_EXPR);
741 RECORD(EXPR_CXX_UUIDOF_TYPE);
742 RECORD(EXPR_CXX_THIS);
743 RECORD(EXPR_CXX_THROW);
744 RECORD(EXPR_CXX_DEFAULT_ARG);
745 RECORD(EXPR_CXX_BIND_TEMPORARY);
746 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
747 RECORD(EXPR_CXX_NEW);
748 RECORD(EXPR_CXX_DELETE);
749 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
750 RECORD(EXPR_EXPR_WITH_CLEANUPS);
751 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
752 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
753 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
754 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
755 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
756 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
757 RECORD(EXPR_CXX_NOEXCEPT);
758 RECORD(EXPR_OPAQUE_VALUE);
759 RECORD(EXPR_BINARY_TYPE_TRAIT);
760 RECORD(EXPR_PACK_EXPANSION);
761 RECORD(EXPR_SIZEOF_PACK);
762 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Peter Collingbournee08ce652011-02-09 21:07:24 +0000763 RECORD(EXPR_CUDA_KERNEL_CALL);
Chris Lattner0558df22009-04-27 00:49:53 +0000764#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000765}
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Sebastian Redla4232eb2010-08-18 23:56:21 +0000767void ASTWriter::WriteBlockInfoBlock() {
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000768 RecordData Record;
769 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Sebastian Redl8538e8d2010-08-18 23:57:32 +0000771#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
772#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregor7ae467f2012-10-18 18:27:37 +0000774 // Control Block.
775 BLOCK(CONTROL_BLOCK);
776 RECORD(METADATA);
777 RECORD(IMPORTS);
778 RECORD(LANGUAGE_OPTIONS);
779 RECORD(TARGET_OPTIONS);
Douglas Gregor39c497b2012-10-18 18:36:53 +0000780 RECORD(ORIGINAL_FILE);
Douglas Gregor7ae467f2012-10-18 18:27:37 +0000781 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis992d9172012-11-15 18:57:27 +0000782 RECORD(ORIGINAL_FILE_ID);
Douglas Gregora930dc92012-10-22 18:42:04 +0000783 RECORD(INPUT_FILE_OFFSETS);
Douglas Gregor5f3d8222012-10-24 15:17:15 +0000784 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregor1b2c3c02012-10-24 15:49:58 +0000785 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregorbbf38312012-10-24 16:50:34 +0000786 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregora71a7d82012-10-24 20:05:57 +0000787 RECORD(PREPROCESSOR_OPTIONS);
788
Douglas Gregorc337fef2012-10-19 00:45:00 +0000789 BLOCK(INPUT_FILES_BLOCK);
790 RECORD(INPUT_FILE);
791
Douglas Gregor7ae467f2012-10-18 18:27:37 +0000792 // AST Top-Level Block.
793 BLOCK(AST_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000794 RECORD(TYPE_OFFSET);
795 RECORD(DECL_OFFSET);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000796 RECORD(IDENTIFIER_OFFSET);
797 RECORD(IDENTIFIER_TABLE);
798 RECORD(EXTERNAL_DEFINITIONS);
799 RECORD(SPECIAL_TYPES);
800 RECORD(STATISTICS);
801 RECORD(TENTATIVE_DEFINITIONS);
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000802 RECORD(UNUSED_FILESCOPED_DECLS);
Richard Smith5ea6ef42013-01-10 23:43:47 +0000803 RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000804 RECORD(SELECTOR_OFFSETS);
805 RECORD(METHOD_POOL);
806 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000807 RECORD(SOURCE_LOCATION_OFFSETS);
808 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000809 RECORD(EXT_VECTOR_DECLS);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +0000810 RECORD(PPD_ENTITIES_OFFSETS);
Fariborz Jahanian32019832010-07-23 19:11:11 +0000811 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000812 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor2171bf12012-01-15 16:58:34 +0000813 RECORD(LOCAL_REDECLARATIONS_MAP);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000814 RECORD(SEMA_DECL_REFS);
815 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
816 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
817 RECORD(DECL_REPLACEMENTS);
818 RECORD(UPDATE_VISIBLE);
819 RECORD(DECL_UPDATE_OFFSETS);
820 RECORD(DECL_UPDATES);
821 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
822 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne84bccea2011-02-15 19:46:30 +0000823 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000824 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne84bccea2011-02-15 19:46:30 +0000825 RECORD(FP_PRAGMA_OPTIONS);
826 RECORD(OPENCL_EXTENSIONS);
Sean Huntebcbe1d2011-05-04 23:29:54 +0000827 RECORD(DELEGATING_CTORS);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000828 RECORD(KNOWN_NAMESPACES);
Nick Lewyckycd0655b2013-02-01 08:13:20 +0000829 RECORD(UNDEFINED_BUT_USED);
Douglas Gregor837593f2011-08-04 16:39:39 +0000830 RECORD(MODULE_OFFSET_MAP);
831 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregorcff9f262012-01-27 01:47:08 +0000832 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregora1266512011-12-19 21:09:25 +0000833 RECORD(FILE_SORTED_DECLS);
834 RECORD(IMPORTED_MODULES);
Douglas Gregor2171bf12012-01-15 16:58:34 +0000835 RECORD(MERGED_DECLARATIONS);
836 RECORD(LOCAL_REDECLARATIONS);
Douglas Gregorcff9f262012-01-27 01:47:08 +0000837 RECORD(OBJC_CATEGORIES);
Douglas Gregora8235d62012-10-09 23:05:51 +0000838 RECORD(MACRO_OFFSET);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000839 RECORD(MACRO_TABLE);
Douglas Gregor2171bf12012-01-15 16:58:34 +0000840
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000841 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000842 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000843 RECORD(SM_SLOC_FILE_ENTRY);
844 RECORD(SM_SLOC_BUFFER_ENTRY);
845 RECORD(SM_SLOC_BUFFER_BLOB);
Chandler Carruthf70d12d2011-07-15 07:25:21 +0000846 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000848 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000849 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000850 RECORD(PP_MACRO_OBJECT_LIKE);
851 RECORD(PP_MACRO_FUNCTION_LIKE);
852 RECORD(PP_TOKEN);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000853
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000854 // Decls and Types block.
855 BLOCK(DECLTYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000856 RECORD(TYPE_EXT_QUAL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000857 RECORD(TYPE_COMPLEX);
858 RECORD(TYPE_POINTER);
859 RECORD(TYPE_BLOCK_POINTER);
860 RECORD(TYPE_LVALUE_REFERENCE);
861 RECORD(TYPE_RVALUE_REFERENCE);
862 RECORD(TYPE_MEMBER_POINTER);
863 RECORD(TYPE_CONSTANT_ARRAY);
864 RECORD(TYPE_INCOMPLETE_ARRAY);
865 RECORD(TYPE_VARIABLE_ARRAY);
866 RECORD(TYPE_VECTOR);
867 RECORD(TYPE_EXT_VECTOR);
868 RECORD(TYPE_FUNCTION_PROTO);
869 RECORD(TYPE_FUNCTION_NO_PROTO);
870 RECORD(TYPE_TYPEDEF);
871 RECORD(TYPE_TYPEOF_EXPR);
872 RECORD(TYPE_TYPEOF);
873 RECORD(TYPE_RECORD);
874 RECORD(TYPE_ENUM);
875 RECORD(TYPE_OBJC_INTERFACE);
John McCalla53d2cb2010-05-16 02:12:35 +0000876 RECORD(TYPE_OBJC_OBJECT);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000877 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000878 RECORD(TYPE_DECLTYPE);
879 RECORD(TYPE_ELABORATED);
880 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
881 RECORD(TYPE_UNRESOLVED_USING);
882 RECORD(TYPE_INJECTED_CLASS_NAME);
883 RECORD(TYPE_OBJC_OBJECT);
884 RECORD(TYPE_TEMPLATE_TYPE_PARM);
885 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
886 RECORD(TYPE_DEPENDENT_NAME);
887 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
888 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
889 RECORD(TYPE_PAREN);
890 RECORD(TYPE_PACK_EXPANSION);
891 RECORD(TYPE_ATTRIBUTED);
892 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Eli Friedmanb001de72011-10-06 23:00:33 +0000893 RECORD(TYPE_ATOMIC);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000894 RECORD(DECL_TYPEDEF);
895 RECORD(DECL_ENUM);
896 RECORD(DECL_RECORD);
897 RECORD(DECL_ENUM_CONSTANT);
898 RECORD(DECL_FUNCTION);
899 RECORD(DECL_OBJC_METHOD);
900 RECORD(DECL_OBJC_INTERFACE);
901 RECORD(DECL_OBJC_PROTOCOL);
902 RECORD(DECL_OBJC_IVAR);
903 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000904 RECORD(DECL_OBJC_CATEGORY);
905 RECORD(DECL_OBJC_CATEGORY_IMPL);
906 RECORD(DECL_OBJC_IMPLEMENTATION);
907 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
908 RECORD(DECL_OBJC_PROPERTY);
909 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000910 RECORD(DECL_FIELD);
John McCall76da55d2013-04-16 07:28:30 +0000911 RECORD(DECL_MS_PROPERTY);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000912 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000913 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000914 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000915 RECORD(DECL_FILE_SCOPE_ASM);
916 RECORD(DECL_BLOCK);
917 RECORD(DECL_CONTEXT_LEXICAL);
918 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregorb6c2b3f2011-02-08 16:34:17 +0000919 RECORD(DECL_NAMESPACE);
920 RECORD(DECL_NAMESPACE_ALIAS);
921 RECORD(DECL_USING);
922 RECORD(DECL_USING_SHADOW);
923 RECORD(DECL_USING_DIRECTIVE);
924 RECORD(DECL_UNRESOLVED_USING_VALUE);
925 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
926 RECORD(DECL_LINKAGE_SPEC);
927 RECORD(DECL_CXX_RECORD);
928 RECORD(DECL_CXX_METHOD);
929 RECORD(DECL_CXX_CONSTRUCTOR);
930 RECORD(DECL_CXX_DESTRUCTOR);
931 RECORD(DECL_CXX_CONVERSION);
932 RECORD(DECL_ACCESS_SPEC);
933 RECORD(DECL_FRIEND);
934 RECORD(DECL_FRIEND_TEMPLATE);
935 RECORD(DECL_CLASS_TEMPLATE);
936 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
937 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
938 RECORD(DECL_FUNCTION_TEMPLATE);
939 RECORD(DECL_TEMPLATE_TYPE_PARM);
940 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
941 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
942 RECORD(DECL_STATIC_ASSERT);
943 RECORD(DECL_CXX_BASE_SPECIFIERS);
944 RECORD(DECL_INDIRECTFIELD);
945 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
946
Douglas Gregora72d8c42011-06-03 02:27:19 +0000947 // Statements and Exprs can occur in the Decls and Types block.
948 AddStmtsExprs(Stream, Record);
949
Douglas Gregor4800a5c2011-02-08 21:58:10 +0000950 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf70d12d2011-07-15 07:25:21 +0000951 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor4800a5c2011-02-08 21:58:10 +0000952 RECORD(PPD_MACRO_DEFINITION);
953 RECORD(PPD_INCLUSION_DIRECTIVE);
954
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000955#undef RECORD
956#undef BLOCK
957 Stream.ExitBlock();
958}
959
Douglas Gregore650c8c2009-07-07 00:12:59 +0000960/// \brief Adjusts the given filename to only write out the portion of the
961/// filename that is not part of the system root directory.
Mike Stump1eb44332009-09-09 15:08:12 +0000962///
Douglas Gregore650c8c2009-07-07 00:12:59 +0000963/// \param Filename the file name to adjust.
964///
965/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
966/// the returned filename will be adjusted by this system root.
967///
968/// \returns either the original filename (if it needs no adjustment) or the
969/// adjusted filename (which points into the @p Filename parameter).
Mike Stump1eb44332009-09-09 15:08:12 +0000970static const char *
Douglas Gregor832d6202011-07-22 16:35:34 +0000971adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000972 assert(Filename && "No file name to adjust?");
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregor832d6202011-07-22 16:35:34 +0000974 if (isysroot.empty())
Douglas Gregore650c8c2009-07-07 00:12:59 +0000975 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Douglas Gregore650c8c2009-07-07 00:12:59 +0000977 // Verify that the filename and the system root have the same prefix.
978 unsigned Pos = 0;
Douglas Gregor832d6202011-07-22 16:35:34 +0000979 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
Douglas Gregore650c8c2009-07-07 00:12:59 +0000980 if (Filename[Pos] != isysroot[Pos])
981 return Filename; // Prefixes don't match.
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Douglas Gregore650c8c2009-07-07 00:12:59 +0000983 // We hit the end of the filename before we hit the end of the system root.
984 if (!Filename[Pos])
985 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregore650c8c2009-07-07 00:12:59 +0000987 // If the file name has a '/' at the current position, skip over the '/'.
988 // We distinguish sysroot-based includes from absolute includes by the
989 // absence of '/' at the beginning of sysroot-based includes.
990 if (Filename[Pos] == '/')
991 ++Pos;
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Douglas Gregore650c8c2009-07-07 00:12:59 +0000993 return Filename + Pos;
994}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000995
Douglas Gregor1d9d9892012-10-18 05:31:06 +0000996/// \brief Write the control block.
Douglas Gregorbbf38312012-10-24 16:50:34 +0000997void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
998 StringRef isysroot,
Douglas Gregor1d9d9892012-10-18 05:31:06 +0000999 const std::string &OutputFile) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001000 using namespace llvm;
Douglas Gregor7ae467f2012-10-18 18:27:37 +00001001 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1002 RecordData Record;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001003
Douglas Gregore650c8c2009-07-07 00:12:59 +00001004 // Metadata
Douglas Gregor7ae467f2012-10-18 18:27:37 +00001005 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1006 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1007 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1008 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1009 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1010 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1011 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1012 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1013 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1014 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1015 Record.push_back(METADATA);
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001016 Record.push_back(VERSION_MAJOR);
1017 Record.push_back(VERSION_MINOR);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001018 Record.push_back(CLANG_VERSION_MAJOR);
1019 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor832d6202011-07-22 16:35:34 +00001020 Record.push_back(!isysroot.empty());
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001021 Record.push_back(ASTHasCompilerErrors);
Douglas Gregor7ae467f2012-10-18 18:27:37 +00001022 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1023 getClangFullRepositoryVersion());
Douglas Gregore95b9192011-08-17 21:07:30 +00001024
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001025 // Imports
Douglas Gregore95b9192011-08-17 21:07:30 +00001026 if (Chain) {
Douglas Gregore95b9192011-08-17 21:07:30 +00001027 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001028 SmallVector<char, 128> ModulePaths;
Douglas Gregore95b9192011-08-17 21:07:30 +00001029 Record.clear();
Douglas Gregor10bc00f2011-08-18 04:12:04 +00001030
1031 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1032 M != MEnd; ++M) {
1033 // Skip modules that weren't directly imported.
1034 if (!(*M)->isDirectlyImported())
1035 continue;
1036
1037 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +00001038 AddSourceLocation((*M)->ImportLoc, Record);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001039 Record.push_back((*M)->File->getSize());
1040 Record.push_back((*M)->File->getModificationTime());
Douglas Gregor10bc00f2011-08-18 04:12:04 +00001041 // FIXME: This writes the absolute path for AST files we depend on.
1042 const std::string &FileName = (*M)->FileName;
1043 Record.push_back(FileName.size());
1044 Record.append(FileName.begin(), FileName.end());
1045 }
Douglas Gregore95b9192011-08-17 21:07:30 +00001046 Stream.EmitRecord(IMPORTS, Record);
1047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001049 // Language options.
1050 Record.clear();
1051 const LangOptions &LangOpts = Context.getLangOpts();
1052#define LANGOPT(Name, Bits, Default, Description) \
1053 Record.push_back(LangOpts.Name);
1054#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1055 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1056#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00001057#define SANITIZER(NAME, ID) Record.push_back(LangOpts.Sanitize.ID);
1058#include "clang/Basic/Sanitizers.def"
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001059
1060 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1061 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1062
1063 Record.push_back(LangOpts.CurrentModule.size());
1064 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00001065
1066 // Comment options.
1067 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1068 for (CommentOptions::BlockCommandNamesTy::const_iterator
1069 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1070 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1071 I != IEnd; ++I) {
1072 AddString(*I, Record);
1073 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00001074 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00001075
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001076 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1077
Douglas Gregoree097c12012-10-18 17:58:09 +00001078 // Target options.
1079 Record.clear();
Douglas Gregor7ae467f2012-10-18 18:27:37 +00001080 const TargetInfo &Target = Context.getTargetInfo();
1081 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregoree097c12012-10-18 17:58:09 +00001082 AddString(TargetOpts.Triple, Record);
1083 AddString(TargetOpts.CPU, Record);
1084 AddString(TargetOpts.ABI, Record);
1085 AddString(TargetOpts.CXXABI, Record);
1086 AddString(TargetOpts.LinkerVersion, Record);
1087 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1088 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1089 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1090 }
1091 Record.push_back(TargetOpts.Features.size());
1092 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1093 AddString(TargetOpts.Features[I], Record);
1094 }
1095 Stream.EmitRecord(TARGET_OPTIONS, Record);
1096
Douglas Gregor5f3d8222012-10-24 15:17:15 +00001097 // Diagnostic options.
1098 Record.clear();
1099 const DiagnosticOptions &DiagOpts
1100 = Context.getDiagnostics().getDiagnosticOptions();
1101#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1102#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1103 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1104#include "clang/Basic/DiagnosticOptions.def"
1105 Record.push_back(DiagOpts.Warnings.size());
1106 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1107 AddString(DiagOpts.Warnings[I], Record);
1108 // Note: we don't serialize the log or serialization file names, because they
1109 // are generally transient files and will almost always be overridden.
1110 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1111
Douglas Gregor1b2c3c02012-10-24 15:49:58 +00001112 // File system options.
1113 Record.clear();
1114 const FileSystemOptions &FSOpts
1115 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1116 AddString(FSOpts.WorkingDir, Record);
1117 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1118
Douglas Gregorbbf38312012-10-24 16:50:34 +00001119 // Header search options.
1120 Record.clear();
1121 const HeaderSearchOptions &HSOpts
1122 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1123 AddString(HSOpts.Sysroot, Record);
1124
1125 // Include entries.
1126 Record.push_back(HSOpts.UserEntries.size());
1127 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1128 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1129 AddString(Entry.Path, Record);
1130 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregorbbf38312012-10-24 16:50:34 +00001131 Record.push_back(Entry.IsFramework);
1132 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregorbbf38312012-10-24 16:50:34 +00001133 }
1134
1135 // System header prefixes.
1136 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1137 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1138 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1139 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1140 }
1141
1142 AddString(HSOpts.ResourceDir, Record);
1143 AddString(HSOpts.ModuleCachePath, Record);
1144 Record.push_back(HSOpts.DisableModuleHash);
1145 Record.push_back(HSOpts.UseBuiltinIncludes);
1146 Record.push_back(HSOpts.UseStandardSystemIncludes);
1147 Record.push_back(HSOpts.UseStandardCXXIncludes);
1148 Record.push_back(HSOpts.UseLibcxx);
1149 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1150
Douglas Gregora71a7d82012-10-24 20:05:57 +00001151 // Preprocessor options.
1152 Record.clear();
1153 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1154
1155 // Macro definitions.
1156 Record.push_back(PPOpts.Macros.size());
1157 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1158 AddString(PPOpts.Macros[I].first, Record);
1159 Record.push_back(PPOpts.Macros[I].second);
1160 }
1161
1162 // Includes
1163 Record.push_back(PPOpts.Includes.size());
1164 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1165 AddString(PPOpts.Includes[I], Record);
1166
1167 // Macro includes
1168 Record.push_back(PPOpts.MacroIncludes.size());
1169 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1170 AddString(PPOpts.MacroIncludes[I], Record);
1171
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00001172 Record.push_back(PPOpts.UsePredefines);
Douglas Gregora71a7d82012-10-24 20:05:57 +00001173 AddString(PPOpts.ImplicitPCHInclude, Record);
1174 AddString(PPOpts.ImplicitPTHInclude, Record);
1175 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1176 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1177
Douglas Gregor31d375f2011-05-06 21:43:30 +00001178 // Original file name and file ID
Douglas Gregorb64c1932009-05-12 01:31:05 +00001179 SourceManager &SM = Context.getSourceManager();
1180 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1181 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
Douglas Gregor39c497b2012-10-18 18:36:53 +00001182 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1183 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregorb64c1932009-05-12 01:31:05 +00001184 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1185 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1186
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001187 SmallString<128> MainFilePath(MainFile->getName());
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Michael J. Spencerfbfd1802010-12-21 16:45:57 +00001189 llvm::sys::fs::make_absolute(MainFilePath);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001190
Kovarththanan Rajaratnamaba54a92010-03-14 07:15:57 +00001191 const char *MainFileNameStr = MainFilePath.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001192 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregore650c8c2009-07-07 00:12:59 +00001193 isysroot);
Douglas Gregora71a7d82012-10-24 20:05:57 +00001194 Record.clear();
Douglas Gregor39c497b2012-10-18 18:36:53 +00001195 Record.push_back(ORIGINAL_FILE);
Douglas Gregor31d375f2011-05-06 21:43:30 +00001196 Record.push_back(SM.getMainFileID().getOpaqueValue());
Douglas Gregor39c497b2012-10-18 18:36:53 +00001197 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001198 }
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00001199
Argyrios Kyrtzidis992d9172012-11-15 18:57:27 +00001200 Record.clear();
1201 Record.push_back(SM.getMainFileID().getOpaqueValue());
1202 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1203
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001204 // Original PCH directory
1205 if (!OutputFile.empty() && OutputFile != "-") {
1206 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1207 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1208 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1209 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1210
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001211 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001212
1213 llvm::sys::fs::make_absolute(OutputPath);
1214 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1215
1216 RecordData Record;
1217 Record.push_back(ORIGINAL_PCH_DIR);
1218 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1219 }
1220
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001221 WriteInputFiles(Context.SourceMgr,
1222 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1223 isysroot);
Douglas Gregor745e6f12012-10-19 00:38:02 +00001224 Stream.ExitBlock();
1225}
1226
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001227namespace {
1228 /// \brief An input file.
1229 struct InputFileEntry {
1230 const FileEntry *File;
1231 bool IsSystemFile;
1232 bool BufferOverridden;
1233 };
1234}
1235
1236void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1237 HeaderSearchOptions &HSOpts,
1238 StringRef isysroot) {
Douglas Gregor745e6f12012-10-19 00:38:02 +00001239 using namespace llvm;
1240 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1241 RecordData Record;
1242
1243 // Create input-file abbreviation.
1244 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1245 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregora930dc92012-10-22 18:42:04 +00001246 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor745e6f12012-10-19 00:38:02 +00001247 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1248 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregora930dc92012-10-22 18:42:04 +00001249 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Douglas Gregor745e6f12012-10-19 00:38:02 +00001250 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1251 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1252
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001253 // Get all ContentCache objects for files, sorted by whether the file is a
1254 // system one or not. System files go at the back, users files at the front.
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001255 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor745e6f12012-10-19 00:38:02 +00001256 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1257 // Get this source location entry.
1258 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumibacc2c52012-10-19 01:53:57 +00001259 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor745e6f12012-10-19 00:38:02 +00001260
1261 // We only care about file entries that were not overridden.
1262 if (!SLoc->isFile())
1263 continue;
1264 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregora930dc92012-10-22 18:42:04 +00001265 if (!Cache->OrigEntry)
Douglas Gregor745e6f12012-10-19 00:38:02 +00001266 continue;
1267
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001268 InputFileEntry Entry;
1269 Entry.File = Cache->OrigEntry;
1270 Entry.IsSystemFile = Cache->IsSystemFile;
1271 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001272 if (Cache->IsSystemFile)
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001273 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001274 else
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001275 SortedFiles.push_front(Entry);
1276 }
1277
1278 // If we have an isysroot for a Darwin SDK, include its SDKSettings.plist in
1279 // the set of (non-system) input files. This is simple heuristic for
1280 // detecting whether the system headers may have changed, because it is too
1281 // expensive to stat() all of the system headers.
1282 FileManager &FileMgr = SourceMgr.getFileManager();
Douglas Gregor2bf383d2013-03-20 16:59:53 +00001283 if (!HSOpts.Sysroot.empty() && !Chain) {
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001284 llvm::SmallString<128> SDKSettingsFileName(HSOpts.Sysroot);
1285 llvm::sys::path::append(SDKSettingsFileName, "SDKSettings.plist");
1286 if (const FileEntry *SDKSettingsFile = FileMgr.getFile(SDKSettingsFileName)) {
1287 InputFileEntry Entry = { SDKSettingsFile, false, false };
1288 SortedFiles.push_front(Entry);
1289 }
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001290 }
1291
1292 unsigned UserFilesNum = 0;
1293 // Write out all of the input files.
1294 std::vector<uint32_t> InputFileOffsets;
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001295 for (std::deque<InputFileEntry>::iterator
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001296 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001297 const InputFileEntry &Entry = *I;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001298
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001299 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidisa89b6182012-12-11 07:48:08 +00001300 if (InputFileID != 0)
1301 continue; // already recorded this file.
1302
Douglas Gregora930dc92012-10-22 18:42:04 +00001303 // Record this entry's offset.
1304 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidisa89b6182012-12-11 07:48:08 +00001305
1306 InputFileID = InputFileOffsets.size();
Douglas Gregora930dc92012-10-22 18:42:04 +00001307
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001308 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001309 ++UserFilesNum;
1310
Douglas Gregor745e6f12012-10-19 00:38:02 +00001311 Record.clear();
1312 Record.push_back(INPUT_FILE);
Douglas Gregora930dc92012-10-22 18:42:04 +00001313 Record.push_back(InputFileOffsets.size());
Douglas Gregor745e6f12012-10-19 00:38:02 +00001314
1315 // Emit size/modification time for this file.
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001316 Record.push_back(Entry.File->getSize());
1317 Record.push_back(Entry.File->getModificationTime());
Douglas Gregor745e6f12012-10-19 00:38:02 +00001318
Douglas Gregora930dc92012-10-22 18:42:04 +00001319 // Whether this file was overridden.
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001320 Record.push_back(Entry.BufferOverridden);
Douglas Gregora930dc92012-10-22 18:42:04 +00001321
Douglas Gregor745e6f12012-10-19 00:38:02 +00001322 // Turn the file name into an absolute path, if it isn't already.
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001323 const char *Filename = Entry.File->getName();
Douglas Gregor745e6f12012-10-19 00:38:02 +00001324 SmallString<128> FilePath(Filename);
1325
1326 // Ask the file manager to fixup the relative path for us. This will
1327 // honor the working directory.
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001328 FileMgr.FixupRelativePath(FilePath);
Douglas Gregor745e6f12012-10-19 00:38:02 +00001329
1330 // FIXME: This call to make_absolute shouldn't be necessary, the
1331 // call to FixupRelativePath should always return an absolute path.
1332 llvm::sys::fs::make_absolute(FilePath);
1333 Filename = FilePath.c_str();
1334
1335 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1336
1337 Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1338 }
Douglas Gregor4a18c3b2013-03-15 22:15:07 +00001339
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001340 Stream.ExitBlock();
Douglas Gregora930dc92012-10-22 18:42:04 +00001341
1342 // Create input file offsets abbreviation.
1343 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1344 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1345 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001346 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1347 // input files
Douglas Gregora930dc92012-10-22 18:42:04 +00001348 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1349 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1350
1351 // Write input file offsets.
1352 Record.clear();
1353 Record.push_back(INPUT_FILE_OFFSETS);
1354 Record.push_back(InputFileOffsets.size());
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001355 Record.push_back(UserFilesNum);
Douglas Gregora930dc92012-10-22 18:42:04 +00001356 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001357}
1358
Douglas Gregor14f79002009-04-10 03:52:48 +00001359//===----------------------------------------------------------------------===//
1360// Source Manager Serialization
1361//===----------------------------------------------------------------------===//
1362
1363/// \brief Create an abbreviation for the SLocEntry that refers to a
1364/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001365static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001366 using namespace llvm;
1367 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001368 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregor14f79002009-04-10 03:52:48 +00001369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor2d52be52010-03-21 22:49:54 +00001373 // FileEntry fields.
Douglas Gregora930dc92012-10-22 18:42:04 +00001374 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001375 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001376 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1377 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregorc9490c02009-04-16 22:23:12 +00001378 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +00001379}
1380
1381/// \brief Create an abbreviation for the SLocEntry that refers to a
1382/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001383static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001384 using namespace llvm;
1385 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001386 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregor14f79002009-04-10 03:52:48 +00001387 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1388 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1390 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1391 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +00001392 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +00001393}
1394
1395/// \brief Create an abbreviation for the SLocEntry that refers to a
1396/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001397static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001398 using namespace llvm;
1399 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001400 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
Douglas Gregor14f79002009-04-10 03:52:48 +00001401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +00001402 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +00001403}
1404
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001405/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1406/// expansion.
1407static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001408 using namespace llvm;
1409 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001410 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregor14f79002009-04-10 03:52:48 +00001411 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1413 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +00001415 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +00001416 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +00001417}
1418
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001419namespace {
1420 // Trait used for the on-disk hash table of header search information.
1421 class HeaderFileInfoTrait {
1422 ASTWriter &Writer;
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001423 const HeaderSearch &HS;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001424
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001425 // Keep track of the framework names we've used during serialization.
1426 SmallVector<char, 128> FrameworkStringData;
1427 llvm::StringMap<unsigned> FrameworkNameOffset;
1428
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001429 public:
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001430 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1431 : Writer(Writer), HS(HS) { }
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001432
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001433 struct key_type {
1434 const FileEntry *FE;
1435 const char *Filename;
1436 };
1437 typedef const key_type &key_type_ref;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001438
1439 typedef HeaderFileInfo data_type;
1440 typedef const data_type &data_type_ref;
1441
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001442 static unsigned ComputeHash(key_type_ref key) {
1443 // The hash is based only on size/time of the file, so that the reader can
1444 // match even when symlinking or excess path elements ("foo/../", "../")
1445 // change the form of the name. However, complete path is still the key.
1446 return llvm::hash_combine(key.FE->getSize(),
1447 key.FE->getModificationTime());
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001448 }
1449
1450 std::pair<unsigned,unsigned>
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001451 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1452 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1453 clang::io::Emit16(Out, KeyLen);
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001454 unsigned DataLen = 1 + 2 + 4 + 4;
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001455 if (Data.isModuleHeader)
1456 DataLen += 4;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001457 clang::io::Emit8(Out, DataLen);
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001458 return std::make_pair(KeyLen, DataLen);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001459 }
1460
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001461 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1462 clang::io::Emit64(Out, key.FE->getSize());
1463 KeyLen -= 8;
1464 clang::io::Emit64(Out, key.FE->getModificationTime());
1465 KeyLen -= 8;
1466 Out.write(key.Filename, KeyLen);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001467 }
1468
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001469 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001470 data_type_ref Data, unsigned DataLen) {
1471 using namespace clang::io;
1472 uint64_t Start = Out.tell(); (void)Start;
1473
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001474 unsigned char Flags = (Data.isImport << 5)
1475 | (Data.isPragmaOnce << 4)
1476 | (Data.DirInfo << 2)
1477 | (Data.Resolved << 1)
1478 | Data.IndexHeaderMapHeader;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001479 Emit8(Out, (uint8_t)Flags);
1480 Emit16(Out, (uint16_t) Data.NumIncludes);
1481
1482 if (!Data.ControllingMacro)
1483 Emit32(Out, (uint32_t)Data.ControllingMacroID);
1484 else
1485 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001486
1487 unsigned Offset = 0;
1488 if (!Data.Framework.empty()) {
1489 // If this header refers into a framework, save the framework name.
1490 llvm::StringMap<unsigned>::iterator Pos
1491 = FrameworkNameOffset.find(Data.Framework);
1492 if (Pos == FrameworkNameOffset.end()) {
1493 Offset = FrameworkStringData.size() + 1;
1494 FrameworkStringData.append(Data.Framework.begin(),
1495 Data.Framework.end());
1496 FrameworkStringData.push_back(0);
1497
1498 FrameworkNameOffset[Data.Framework] = Offset;
1499 } else
1500 Offset = Pos->second;
1501 }
1502 Emit32(Out, Offset);
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001503
1504 if (Data.isModuleHeader) {
1505 Module *Mod = HS.findModuleForHeader(key.FE);
1506 Emit32(Out, Writer.getExistingSubmoduleID(Mod));
1507 }
1508
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001509 assert(Out.tell() - Start == DataLen && "Wrong data length");
1510 }
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001511
1512 const char *strings_begin() const { return FrameworkStringData.begin(); }
1513 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001514 };
1515} // end anonymous namespace
1516
1517/// \brief Write the header search block for the list of files that
1518///
1519/// \param HS The header search structure to save.
Argyrios Kyrtzidis590ad932011-11-13 22:08:39 +00001520void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001521 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001522 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1523
1524 if (FilesByUID.size() > HS.header_file_size())
1525 FilesByUID.resize(HS.header_file_size());
1526
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001527 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001528 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001529 SmallVector<const char *, 4> SavedStrings;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001530 unsigned NumHeaderSearchEntries = 0;
1531 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1532 const FileEntry *File = FilesByUID[UID];
1533 if (!File)
1534 continue;
1535
Argyrios Kyrtzidis590ad932011-11-13 22:08:39 +00001536 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1537 // from the external source if it was not provided already.
1538 const HeaderFileInfo &HFI = HS.getFileInfo(File);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001539 if (HFI.External && Chain)
1540 continue;
1541
1542 // Turn the file name into an absolute path, if it isn't already.
1543 const char *Filename = File->getName();
1544 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1545
1546 // If we performed any translation on the file name at all, we need to
1547 // save this string, since the generator will refer to it later.
1548 if (Filename != File->getName()) {
1549 Filename = strdup(Filename);
1550 SavedStrings.push_back(Filename);
1551 }
1552
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001553 HeaderFileInfoTrait::key_type key = { File, Filename };
1554 Generator.insert(key, HFI, GeneratorTrait);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001555 ++NumHeaderSearchEntries;
1556 }
1557
1558 // Create the on-disk hash table in a buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001559 SmallString<4096> TableData;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001560 uint32_t BucketOffset;
1561 {
1562 llvm::raw_svector_ostream Out(TableData);
1563 // Make sure that no bucket is at offset 0
1564 clang::io::Emit32(Out, 0);
1565 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1566 }
1567
1568 // Create a blob abbreviation
1569 using namespace llvm;
1570 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1571 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1572 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1573 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1576 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1577
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001578 // Write the header search table
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001579 RecordData Record;
1580 Record.push_back(HEADER_SEARCH_TABLE);
1581 Record.push_back(BucketOffset);
1582 Record.push_back(NumHeaderSearchEntries);
Douglas Gregorb4dc4852011-07-28 04:50:02 +00001583 Record.push_back(TableData.size());
1584 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001585 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1586
1587 // Free all of the strings we had to duplicate.
1588 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greene64444832013-01-15 22:09:43 +00001589 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001590}
1591
Douglas Gregor14f79002009-04-10 03:52:48 +00001592/// \brief Writes the block containing the serialized form of the
1593/// source manager.
1594///
1595/// TODO: We should probably use an on-disk hash table (stored in a
1596/// blob), indexed based on the file name, so that we only create
1597/// entries for files that we actually need. In the common case (no
1598/// errors), we probably won't have to create file entries for any of
1599/// the files in the AST.
Sebastian Redla4232eb2010-08-18 23:56:21 +00001600void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +00001601 const Preprocessor &PP,
Douglas Gregor832d6202011-07-22 16:35:34 +00001602 StringRef isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001603 RecordData Record;
1604
Chris Lattnerf04ad692009-04-10 17:16:57 +00001605 // Enter the source manager block.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001606 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +00001607
1608 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +00001609 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1610 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1611 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001612 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +00001613
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001614 // Write out the source location entry table. We skip the first
1615 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +00001616 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001617 RecordData PreloadSLocs;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001618 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1619 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001620 I != N; ++I) {
Douglas Gregorbdfe48a2009-10-16 22:46:09 +00001621 // Get this source location entry.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001622 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidisa2ea4d92012-10-02 21:09:17 +00001623 FileID FID = FileID::get(I);
1624 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00001625
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001626 // Record the offset of this source-location entry.
1627 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1628
1629 // Figure out which record code to use.
1630 unsigned Code;
1631 if (SLoc->isFile()) {
Douglas Gregora081da52011-11-16 20:05:18 +00001632 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1633 if (Cache->OrigEntry) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001634 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis4cdb0e22011-06-02 20:01:46 +00001635 } else
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001636 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001637 } else
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001638 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001639 Record.clear();
1640 Record.push_back(Code);
1641
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001642 // Starting offset of this entry within this module, so skip the dummy.
1643 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001644 if (SLoc->isFile()) {
1645 const SrcMgr::FileInfo &File = SLoc->getFile();
1646 Record.push_back(File.getIncludeLoc().getRawEncoding());
1647 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1648 Record.push_back(File.hasLineDirectives());
1649
1650 const SrcMgr::ContentCache *Content = File.getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001651 if (Content->OrigEntry) {
1652 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregora081da52011-11-16 20:05:18 +00001653 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001654
Douglas Gregora930dc92012-10-22 18:42:04 +00001655 // The source location entry is a file. Emit input file ID.
1656 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1657 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001659 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001660
Argyrios Kyrtzidisa2ea4d92012-10-02 21:09:17 +00001661 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001662 if (FDI != FileDeclIDs.end()) {
1663 Record.push_back(FDI->second->FirstDeclIndex);
1664 Record.push_back(FDI->second->DeclIDs.size());
1665 } else {
1666 Record.push_back(0);
1667 Record.push_back(0);
1668 }
Douglas Gregora081da52011-11-16 20:05:18 +00001669
Douglas Gregora930dc92012-10-22 18:42:04 +00001670 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Douglas Gregora081da52011-11-16 20:05:18 +00001671
1672 if (Content->BufferOverridden) {
1673 Record.clear();
1674 Record.push_back(SM_SLOC_BUFFER_BLOB);
1675 const llvm::MemoryBuffer *Buffer
1676 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1677 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1678 StringRef(Buffer->getBufferStart(),
1679 Buffer->getBufferSize() + 1));
1680 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001681 } else {
1682 // The source location entry is a buffer. The blob associated
1683 // with this entry contains the contents of the buffer.
1684
1685 // We add one to the size so that we capture the trailing NULL
1686 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1687 // the reader side).
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001688 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +00001689 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001690 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbarec312a12009-08-24 09:31:37 +00001691 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001692 StringRef(Name, strlen(Name) + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001693 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001694 Record.push_back(SM_SLOC_BUFFER_BLOB);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001695 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001696 StringRef(Buffer->getBufferStart(),
Daniel Dunbarec312a12009-08-24 09:31:37 +00001697 Buffer->getBufferSize() + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001698
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001699 if (strcmp(Name, "<built-in>") == 0) {
1700 PreloadSLocs.push_back(SLocEntryOffsets.size());
1701 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001702 }
1703 } else {
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001704 // The source location entry is a macro expansion.
Chandler Carruth17287622011-07-26 04:56:51 +00001705 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +00001706 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1707 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
Argyrios Kyrtzidisd21683c2011-08-17 00:31:14 +00001708 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1709 : Expansion.getExpansionLocEnd().getRawEncoding());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001710
1711 // Compute the token length for this macro expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001712 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregorbdfe48a2009-10-16 22:46:09 +00001713 if (I + 1 != N)
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001714 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001715 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001716 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001717 }
1718 }
1719
Douglas Gregorc9490c02009-04-16 22:23:12 +00001720 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001721
1722 if (SLocEntryOffsets.empty())
1723 return;
1724
Sebastian Redl3397c552010-08-18 23:56:27 +00001725 // Write the source-location offsets table into the AST block. This
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001726 // table is used for lazily loading source-location information.
1727 using namespace llvm;
1728 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001729 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001730 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001731 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001732 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1733 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001735 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001736 Record.push_back(SOURCE_LOCATION_OFFSETS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001737 Record.push_back(SLocEntryOffsets.size());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001738 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
Benjamin Kramer6e089c62011-04-24 17:44:50 +00001739 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001740
Sebastian Redl3397c552010-08-18 23:56:27 +00001741 // Write the source location entry preloads array, telling the AST
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001742 // reader which source locations entries it should load eagerly.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001743 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001744
1745 // Write the line table. It depends on remapping working, so it must come
1746 // after the source location offsets.
1747 if (SourceMgr.hasLineTable()) {
1748 LineTableInfo &LineTable = SourceMgr.getLineTable();
1749
1750 Record.clear();
1751 // Emit the file names
1752 Record.push_back(LineTable.getNumFilenames());
1753 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1754 // Emit the file name
1755 const char *Filename = LineTable.getFilename(I);
1756 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1757 unsigned FilenameLen = Filename? strlen(Filename) : 0;
1758 Record.push_back(FilenameLen);
1759 if (FilenameLen)
1760 Record.insert(Record.end(), Filename, Filename + FilenameLen);
1761 }
1762
1763 // Emit the line entries
1764 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1765 L != LEnd; ++L) {
1766 // Only emit entries for local files.
Douglas Gregor47d9de62012-06-08 16:40:28 +00001767 if (L->first.ID < 0)
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001768 continue;
1769
1770 // Emit the file ID
Douglas Gregor47d9de62012-06-08 16:40:28 +00001771 Record.push_back(L->first.ID);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001772
1773 // Emit the line entries
1774 Record.push_back(L->second.size());
1775 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1776 LEEnd = L->second.end();
1777 LE != LEEnd; ++LE) {
1778 Record.push_back(LE->FileOffset);
1779 Record.push_back(LE->LineNo);
1780 Record.push_back(LE->FilenameID);
1781 Record.push_back((unsigned)LE->FileKind);
1782 Record.push_back(LE->IncludeOffset);
1783 }
1784 }
1785 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1786 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001787}
1788
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001789//===----------------------------------------------------------------------===//
1790// Preprocessor Serialization
1791//===----------------------------------------------------------------------===//
1792
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001793namespace {
1794class ASTMacroTableTrait {
1795public:
1796 typedef IdentID key_type;
1797 typedef key_type key_type_ref;
1798
1799 struct Data {
1800 uint32_t MacroDirectivesOffset;
1801 };
1802
1803 typedef Data data_type;
1804 typedef const data_type &data_type_ref;
1805
1806 static unsigned ComputeHash(IdentID IdID) {
1807 return llvm::hash_value(IdID);
1808 }
1809
1810 std::pair<unsigned,unsigned>
1811 static EmitKeyDataLength(raw_ostream& Out,
1812 key_type_ref Key, data_type_ref Data) {
1813 unsigned KeyLen = 4; // IdentID.
1814 unsigned DataLen = 4; // MacroDirectivesOffset.
1815 return std::make_pair(KeyLen, DataLen);
1816 }
1817
1818 static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
1819 clang::io::Emit32(Out, Key);
1820 }
1821
1822 static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
1823 unsigned) {
1824 clang::io::Emit32(Out, Data.MacroDirectivesOffset);
1825 }
1826};
1827} // end anonymous namespace
1828
1829static int compareMacroDirectives(const void *XPtr, const void *YPtr) {
1830 const std::pair<const IdentifierInfo *, MacroDirective *> &X =
1831 *(const std::pair<const IdentifierInfo *, MacroDirective *>*)XPtr;
1832 const std::pair<const IdentifierInfo *, MacroDirective *> &Y =
1833 *(const std::pair<const IdentifierInfo *, MacroDirective *>*)YPtr;
Douglas Gregor9c736102011-02-10 18:20:09 +00001834 return X.first->getName().compare(Y.first->getName());
1835}
1836
Argyrios Kyrtzidis9cc3ed42013-03-15 22:43:10 +00001837static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1838 const Preprocessor &PP) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001839 if (MacroInfo *MI = MD->getMacroInfo())
1840 if (MI->isBuiltinMacro())
1841 return true;
Argyrios Kyrtzidis9cc3ed42013-03-15 22:43:10 +00001842
1843 if (IsModule) {
1844 SourceLocation Loc = MD->getLocation();
1845 if (Loc.isInvalid())
1846 return true;
1847 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1848 return true;
1849 }
1850
1851 return false;
1852}
1853
Chris Lattner0b1fb982009-04-10 17:15:23 +00001854/// \brief Writes the block containing the serialized form of the
1855/// preprocessor.
1856///
Douglas Gregor7143aab2011-09-01 17:04:32 +00001857void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00001858 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1859 if (PPRec)
1860 WritePreprocessorDetail(*PPRec);
1861
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001862 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +00001863
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001864 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1865 if (PP.getCounterValue() != 0) {
1866 Record.push_back(PP.getCounterValue());
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001867 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001868 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001869 }
1870
1871 // Enter the preprocessor block.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001872 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Sebastian Redl3397c552010-08-18 23:56:27 +00001874 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001875 // FIXME: use diagnostics subsystem for localization etc.
1876 if (PP.SawDateOrTime())
1877 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregorecdcb882010-10-20 22:00:55 +00001879
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001880 // Loop over all the macro directives that are live at the end of the file,
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001881 // emitting each to the PP section.
Michael J. Spencer20249a12010-10-21 03:16:25 +00001882
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001883 // Construct the list of macro directives that need to be serialized.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00001884 SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2>
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001885 MacroDirectives;
1886 for (Preprocessor::macro_iterator
1887 I = PP.macro_begin(/*IncludeExternalMacros=*/false),
1888 E = PP.macro_end(/*IncludeExternalMacros=*/false);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001889 I != E; ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001890 MacroDirectives.push_back(std::make_pair(I->first, I->second));
Douglas Gregor9c736102011-02-10 18:20:09 +00001891 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001892
Douglas Gregor9c736102011-02-10 18:20:09 +00001893 // Sort the set of macro definitions that need to be serialized by the
1894 // name of the macro, to provide a stable ordering.
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001895 llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(),
1896 &compareMacroDirectives);
1897
1898 OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator;
1899
1900 // Emit the macro directives as a list and associate the offset with the
1901 // identifier they belong to.
1902 for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) {
1903 const IdentifierInfo *Name = MacroDirectives[I].first;
1904 uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo();
1905 MacroDirective *MD = MacroDirectives[I].second;
1906
1907 // If the macro or identifier need no updates, don't write the macro history
1908 // for this one.
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001909 // FIXME: Chain the macro history instead of re-writing it.
1910 if (MD->isFromPCH() &&
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001911 Name->isFromAST() && !Name->hasChangedSinceDeserialization())
1912 continue;
1913
1914 // Emit the macro directives in reverse source order.
1915 for (; MD; MD = MD->getPrevious()) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001916 if (MD->isHidden())
1917 continue;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001918 if (shouldIgnoreMacro(MD, IsModule, PP))
1919 continue;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001920
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001921 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001922 Record.push_back(MD->getKind());
1923 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
1924 MacroID InfoID = getMacroRef(DefMD->getInfo(), Name);
1925 Record.push_back(InfoID);
1926 Record.push_back(DefMD->isImported());
1927 Record.push_back(DefMD->isAmbiguous());
1928
1929 } else if (VisibilityMacroDirective *
1930 VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
1931 Record.push_back(VisMD->isPublic());
1932 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001933 }
1934 if (Record.empty())
1935 continue;
1936
1937 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
1938 Record.clear();
1939
1940 IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset;
1941
1942 IdentID NameID = getIdentifierRef(Name);
1943 ASTMacroTableTrait::Data data;
1944 data.MacroDirectivesOffset = MacroDirectiveOffset;
1945 Generator.insert(NameID, data);
1946 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001947
Douglas Gregora8235d62012-10-09 23:05:51 +00001948 /// \brief Offsets of each of the macros into the bitstream, indexed by
1949 /// the local macro ID
1950 ///
1951 /// For each identifier that is associated with a macro, this map
1952 /// provides the offset into the bitstream where that macro is
1953 /// defined.
1954 std::vector<uint32_t> MacroOffsets;
1955
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001956 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
1957 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
1958 MacroInfo *MI = MacroInfosToEmit[I].MI;
1959 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoree9b0ba2010-10-01 01:03:07 +00001960
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001961 if (ID < FirstMacroID) {
1962 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
1963 continue;
Chris Lattnerdf961c22009-04-10 18:08:30 +00001964 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001965
1966 // Record the local offset of this macro.
1967 unsigned Index = ID - FirstMacroID;
1968 if (Index == MacroOffsets.size())
1969 MacroOffsets.push_back(Stream.GetCurrentBitNo());
1970 else {
1971 if (Index > MacroOffsets.size())
1972 MacroOffsets.resize(Index + 1);
1973
1974 MacroOffsets[Index] = Stream.GetCurrentBitNo();
1975 }
1976
1977 AddIdentifierRef(Name, Record);
1978 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
1979 AddSourceLocation(MI->getDefinitionLoc(), Record);
1980 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
1981 Record.push_back(MI->isUsed());
1982 unsigned Code;
1983 if (MI->isObjectLike()) {
1984 Code = PP_MACRO_OBJECT_LIKE;
1985 } else {
1986 Code = PP_MACRO_FUNCTION_LIKE;
1987
1988 Record.push_back(MI->isC99Varargs());
1989 Record.push_back(MI->isGNUVarargs());
1990 Record.push_back(MI->hasCommaPasting());
1991 Record.push_back(MI->getNumArgs());
1992 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1993 I != E; ++I)
1994 AddIdentifierRef(*I, Record);
1995 }
1996
1997 // If we have a detailed preprocessing record, record the macro definition
1998 // ID that corresponds to this macro.
1999 if (PPRec)
2000 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2001
2002 Stream.EmitRecord(Code, Record);
2003 Record.clear();
2004
2005 // Emit the tokens array.
2006 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2007 // Note that we know that the preprocessor does not have any annotation
2008 // tokens in it because they are created by the parser, and thus can't
2009 // be in a macro definition.
2010 const Token &Tok = MI->getReplacementToken(TokNo);
2011
2012 Record.push_back(Tok.getLocation().getRawEncoding());
2013 Record.push_back(Tok.getLength());
2014
2015 // FIXME: When reading literal tokens, reconstruct the literal pointer
2016 // if it is needed.
2017 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
2018 // FIXME: Should translate token kind to a stable encoding.
2019 Record.push_back(Tok.getKind());
2020 // FIXME: Should translate token flags to a stable encoding.
2021 Record.push_back(Tok.getFlags());
2022
2023 Stream.EmitRecord(PP_TOKEN, Record);
2024 Record.clear();
2025 }
2026 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00002027 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002028
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002029 Stream.ExitBlock();
Douglas Gregora8235d62012-10-09 23:05:51 +00002030
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002031 // Create the on-disk hash table in a buffer.
2032 SmallString<4096> MacroTable;
2033 uint32_t BucketOffset;
2034 {
2035 llvm::raw_svector_ostream Out(MacroTable);
2036 // Make sure that no bucket is at offset 0
2037 clang::io::Emit32(Out, 0);
2038 BucketOffset = Generator.Emit(Out);
2039 }
2040
2041 // Write the macro table
2042 using namespace llvm;
2043 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2044 Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE));
2045 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2047 unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev);
2048
2049 Record.push_back(MACRO_TABLE);
2050 Record.push_back(BucketOffset);
2051 Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str());
2052 Record.clear();
2053
Douglas Gregora8235d62012-10-09 23:05:51 +00002054 // Write the offsets table for macro IDs.
2055 using namespace llvm;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002056 Abbrev = new BitCodeAbbrev();
Douglas Gregora8235d62012-10-09 23:05:51 +00002057 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2058 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2059 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2060 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2061
2062 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2063 Record.clear();
2064 Record.push_back(MACRO_OFFSET);
2065 Record.push_back(MacroOffsets.size());
2066 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2067 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2068 data(MacroOffsets));
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002069}
2070
2071void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidisb6441ef2011-09-19 20:40:42 +00002072 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002073 return;
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002074
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002075 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002076
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002077 // Enter the preprocessor block.
2078 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer20249a12010-10-21 03:16:25 +00002079
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002080 // If the preprocessor has a preprocessing record, emit it.
2081 unsigned NumPreprocessingRecords = 0;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002082 using namespace llvm;
2083
2084 // Set up the abbreviation for
2085 unsigned InclusionAbbrev = 0;
2086 {
2087 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2088 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002089 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2090 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2091 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidis8dd927c2012-10-02 16:10:46 +00002092 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002093 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2094 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2095 }
2096
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002097 unsigned FirstPreprocessorEntityID
2098 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2099 + NUM_PREDEF_PP_ENTITY_IDS;
2100 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002101 RecordData Record;
Argyrios Kyrtzidisb6441ef2011-09-19 20:40:42 +00002102 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2103 EEnd = PPRec.local_end();
Douglas Gregor7338a922011-08-04 17:06:18 +00002104 E != EEnd;
2105 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002106 Record.clear();
Michael J. Spencer20249a12010-10-21 03:16:25 +00002107
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002108 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2109 Stream.GetCurrentBitNo()));
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002110
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002111 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002112 // Record this macro definition's ID.
2113 MacroDefinitions[MD] = NextPreprocessorEntityID;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002114
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002115 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002116 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2117 continue;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002118 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00002119
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002120 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis8f7c5402011-09-08 17:18:41 +00002121 Record.push_back(ME->isBuiltinMacro());
2122 if (ME->isBuiltinMacro())
2123 AddIdentifierRef(ME->getName(), Record);
2124 else
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002125 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf70d12d2011-07-15 07:25:21 +00002126 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002127 continue;
2128 }
2129
2130 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2131 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002132 Record.push_back(ID->getFileName().size());
2133 Record.push_back(ID->wasInQuotes());
2134 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidis8dd927c2012-10-02 16:10:46 +00002135 Record.push_back(ID->importedModule());
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002136 SmallString<64> Buffer;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002137 Buffer += ID->getFileName();
Argyrios Kyrtzidis29f98b42012-03-08 01:08:28 +00002138 // Check that the FileEntry is not null because it was not resolved and
2139 // we create a PCH even with compiler errors.
2140 if (ID->getFile())
2141 Buffer += ID->getFile()->getName();
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002142 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2143 continue;
2144 }
2145
2146 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2147 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00002148 Stream.ExitBlock();
Michael J. Spencer20249a12010-10-21 03:16:25 +00002149
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002150 // Write the offsets table for the preprocessing record.
2151 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002152 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2153
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002154 // Write the offsets table for identifier IDs.
2155 using namespace llvm;
2156 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002157 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002158 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002159 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002160 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer20249a12010-10-21 03:16:25 +00002161
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002162 Record.clear();
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002163 Record.push_back(PPD_ENTITIES_OFFSETS);
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002164 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002165 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2166 data(PreprocessedEntityOffsets));
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002167 }
Chris Lattner0b1fb982009-04-10 17:15:23 +00002168}
2169
Douglas Gregore209e502011-12-06 01:10:29 +00002170unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2171 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2172 if (Known != SubmoduleIDs.end())
2173 return Known->second;
2174
2175 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2176}
2177
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00002178unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2179 if (!Mod)
2180 return 0;
2181
2182 llvm::DenseMap<Module *, unsigned>::const_iterator
2183 Known = SubmoduleIDs.find(Mod);
2184 if (Known != SubmoduleIDs.end())
2185 return Known->second;
2186
2187 return 0;
2188}
2189
Douglas Gregor26ced122011-12-01 00:59:36 +00002190/// \brief Compute the number of modules within the given tree (including the
2191/// given module).
2192static unsigned getNumberOfModules(Module *Mod) {
2193 unsigned ChildModules = 0;
Douglas Gregorb7a78192012-01-04 23:32:19 +00002194 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2195 SubEnd = Mod->submodule_end();
Douglas Gregor26ced122011-12-01 00:59:36 +00002196 Sub != SubEnd; ++Sub)
Douglas Gregorb7a78192012-01-04 23:32:19 +00002197 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor26ced122011-12-01 00:59:36 +00002198
2199 return ChildModules + 1;
2200}
2201
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002202void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor4bc8738d2011-12-05 16:35:23 +00002203 // Determine the dependencies of our module and each of it's submodules.
Douglas Gregor55988682011-12-05 16:33:54 +00002204 // FIXME: This feels like it belongs somewhere else, but there are no
2205 // other consumers of this information.
2206 SourceManager &SrcMgr = PP->getSourceManager();
2207 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2208 for (ASTContext::import_iterator I = Context->local_import_begin(),
2209 IEnd = Context->local_import_end();
2210 I != IEnd; ++I) {
Douglas Gregor55988682011-12-05 16:33:54 +00002211 if (Module *ImportedFrom
2212 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2213 SrcMgr))) {
2214 ImportedFrom->Imports.push_back(I->getImportedModule());
2215 }
2216 }
2217
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002218 // Enter the submodule description block.
2219 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2220
2221 // Write the abbreviations needed for the submodules block.
2222 using namespace llvm;
2223 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2224 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregore209e502011-12-06 01:10:29 +00002225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Douglas Gregora1f1fad2012-01-27 19:52:33 +00002229 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2230 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor1e123682011-12-05 22:27:44 +00002231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor1e123682011-12-05 22:27:44 +00002232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor63a72682013-03-20 00:22:05 +00002233 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002234 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2235 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2236
2237 Abbrev = new BitCodeAbbrev();
Douglas Gregor77d029f2011-12-08 19:11:24 +00002238 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2240 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2241
2242 Abbrev = new BitCodeAbbrev();
2243 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2244 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2245 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor77d029f2011-12-08 19:11:24 +00002246
2247 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00002248 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2249 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2250 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2251
2252 Abbrev = new BitCodeAbbrev();
Douglas Gregor77d029f2011-12-08 19:11:24 +00002253 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2255 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2256
Douglas Gregor51f564f2011-12-31 04:05:44 +00002257 Abbrev = new BitCodeAbbrev();
2258 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2259 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2260 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2261
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00002262 Abbrev = new BitCodeAbbrev();
2263 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2264 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2265 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2266
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002267 Abbrev = new BitCodeAbbrev();
2268 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2269 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2270 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2271 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2272
Douglas Gregor63a72682013-03-20 00:22:05 +00002273 Abbrev = new BitCodeAbbrev();
2274 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2275 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2276 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2277
Douglas Gregor906d66a2013-03-20 21:10:35 +00002278 Abbrev = new BitCodeAbbrev();
2279 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2280 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2281 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2282 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2283
Douglas Gregor26ced122011-12-01 00:59:36 +00002284 // Write the submodule metadata block.
2285 RecordData Record;
2286 Record.push_back(getNumberOfModules(WritingModule));
2287 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2288 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2289
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002290 // Write all of the submodules.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002291 std::queue<Module *> Q;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002292 Q.push(WritingModule);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002293 while (!Q.empty()) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002294 Module *Mod = Q.front();
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002295 Q.pop();
Douglas Gregore209e502011-12-06 01:10:29 +00002296 unsigned ID = getSubmoduleID(Mod);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002297
2298 // Emit the definition of the block.
2299 Record.clear();
2300 Record.push_back(SUBMODULE_DEFINITION);
Douglas Gregore209e502011-12-06 01:10:29 +00002301 Record.push_back(ID);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002302 if (Mod->Parent) {
2303 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2304 Record.push_back(SubmoduleIDs[Mod->Parent]);
2305 } else {
2306 Record.push_back(0);
2307 }
2308 Record.push_back(Mod->IsFramework);
2309 Record.push_back(Mod->IsExplicit);
Douglas Gregora1f1fad2012-01-27 19:52:33 +00002310 Record.push_back(Mod->IsSystem);
Douglas Gregor1e123682011-12-05 22:27:44 +00002311 Record.push_back(Mod->InferSubmodules);
2312 Record.push_back(Mod->InferExplicitSubmodules);
2313 Record.push_back(Mod->InferExportWildcard);
Douglas Gregor63a72682013-03-20 00:22:05 +00002314 Record.push_back(Mod->ConfigMacrosExhaustive);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002315 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2316
Douglas Gregor51f564f2011-12-31 04:05:44 +00002317 // Emit the requirements.
2318 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
2319 Record.clear();
2320 Record.push_back(SUBMODULE_REQUIRES);
2321 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2322 Mod->Requires[I].data(),
2323 Mod->Requires[I].size());
2324 }
2325
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002326 // Emit the umbrella header, if there is one.
Douglas Gregor10694ce2011-12-08 17:39:04 +00002327 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002328 Record.clear();
Douglas Gregor77d029f2011-12-08 19:11:24 +00002329 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002330 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
Douglas Gregor10694ce2011-12-08 17:39:04 +00002331 UmbrellaHeader->getName());
Douglas Gregor77d029f2011-12-08 19:11:24 +00002332 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2333 Record.clear();
2334 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2335 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2336 UmbrellaDir->getName());
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002337 }
2338
2339 // Emit the headers.
2340 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
2341 Record.clear();
2342 Record.push_back(SUBMODULE_HEADER);
2343 Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2344 Mod->Headers[I]->getName());
2345 }
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00002346 // Emit the excluded headers.
2347 for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2348 Record.clear();
2349 Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2350 Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2351 Mod->ExcludedHeaders[I]->getName());
2352 }
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00002353 ArrayRef<const FileEntry *>
2354 TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2355 for (unsigned I = 0, N = TopHeaders.size(); I != N; ++I) {
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00002356 Record.clear();
2357 Record.push_back(SUBMODULE_TOPHEADER);
2358 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00002359 TopHeaders[I]->getName());
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00002360 }
Douglas Gregor55988682011-12-05 16:33:54 +00002361
2362 // Emit the imports.
2363 if (!Mod->Imports.empty()) {
2364 Record.clear();
2365 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
Douglas Gregorbab9f4a2011-12-12 23:17:57 +00002366 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
Douglas Gregor55988682011-12-05 16:33:54 +00002367 assert(ImportedID && "Unknown submodule!");
2368 Record.push_back(ImportedID);
2369 }
2370 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2371 }
2372
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00002373 // Emit the exports.
2374 if (!Mod->Exports.empty()) {
2375 Record.clear();
2376 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
Douglas Gregorbab9f4a2011-12-12 23:17:57 +00002377 if (Module *Exported = Mod->Exports[I].getPointer()) {
2378 unsigned ExportedID = SubmoduleIDs[Exported];
2379 assert(ExportedID > 0 && "Unknown submodule ID?");
2380 Record.push_back(ExportedID);
2381 } else {
2382 Record.push_back(0);
2383 }
2384
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00002385 Record.push_back(Mod->Exports[I].getInt());
2386 }
2387 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2388 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002389
2390 // Emit the link libraries.
2391 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2392 Record.clear();
2393 Record.push_back(SUBMODULE_LINK_LIBRARY);
2394 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2395 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2396 Mod->LinkLibraries[I].Library);
2397 }
2398
Douglas Gregor906d66a2013-03-20 21:10:35 +00002399 // Emit the conflicts.
2400 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2401 Record.clear();
2402 Record.push_back(SUBMODULE_CONFLICT);
2403 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2404 assert(OtherID && "Unknown submodule!");
2405 Record.push_back(OtherID);
2406 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2407 Mod->Conflicts[I].Message);
2408 }
2409
Douglas Gregor63a72682013-03-20 00:22:05 +00002410 // Emit the configuration macros.
2411 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2412 Record.clear();
2413 Record.push_back(SUBMODULE_CONFIG_MACRO);
2414 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2415 Mod->ConfigMacros[I]);
2416 }
2417
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002418 // Queue up the submodules of this module.
Douglas Gregorb7a78192012-01-04 23:32:19 +00002419 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2420 SubEnd = Mod->submodule_end();
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002421 Sub != SubEnd; ++Sub)
Douglas Gregorb7a78192012-01-04 23:32:19 +00002422 Q.push(*Sub);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002423 }
2424
2425 Stream.ExitBlock();
Douglas Gregore209e502011-12-06 01:10:29 +00002426
2427 assert((NextSubmoduleID - FirstSubmoduleID
2428 == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002429}
2430
Douglas Gregor185dbd72011-12-01 02:07:58 +00002431serialization::SubmoduleID
2432ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregore209e502011-12-06 01:10:29 +00002433 if (Loc.isInvalid() || !WritingModule)
Douglas Gregor185dbd72011-12-01 02:07:58 +00002434 return 0; // No submodule
Douglas Gregor55988682011-12-05 16:33:54 +00002435
2436 // Find the module that owns this location.
Douglas Gregor185dbd72011-12-01 02:07:58 +00002437 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor55988682011-12-05 16:33:54 +00002438 Module *OwningMod
2439 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregor185dbd72011-12-01 02:07:58 +00002440 if (!OwningMod)
2441 return 0;
2442
Douglas Gregore209e502011-12-06 01:10:29 +00002443 // Check whether this submodule is part of our own module.
2444 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregor185dbd72011-12-01 02:07:58 +00002445 return 0;
2446
Douglas Gregore209e502011-12-06 01:10:29 +00002447 return getSubmoduleID(OwningMod);
Douglas Gregor185dbd72011-12-01 02:07:58 +00002448}
2449
Argyrios Kyrtzidisea744ab2013-03-27 17:17:23 +00002450void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2451 bool isModule) {
2452 // Make sure set diagnostic pragmas don't affect the translation unit that
2453 // imports the module.
2454 // FIXME: Make diagnostic pragma sections work properly with modules.
2455 if (isModule)
2456 return;
2457
Argyrios Kyrtzidis33e15762012-10-30 00:27:21 +00002458 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2459 DiagStateIDMap;
2460 unsigned CurrID = 0;
2461 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002462 RecordData Record;
David Blaikied6471f72011-09-25 23:23:43 +00002463 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002464 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2465 I != E; ++I) {
Argyrios Kyrtzidis33e15762012-10-30 00:27:21 +00002466 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002467 if (point.Loc.isInvalid())
2468 continue;
2469
2470 Record.push_back(point.Loc.getRawEncoding());
Argyrios Kyrtzidis33e15762012-10-30 00:27:21 +00002471 unsigned &DiagStateID = DiagStateIDMap[point.State];
2472 Record.push_back(DiagStateID);
2473
2474 if (DiagStateID == 0) {
2475 DiagStateID = ++CurrID;
2476 for (DiagnosticsEngine::DiagState::const_iterator
2477 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2478 if (I->second.isPragma()) {
2479 Record.push_back(I->first);
2480 Record.push_back(I->second.getMapping());
2481 }
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002482 }
Argyrios Kyrtzidis33e15762012-10-30 00:27:21 +00002483 Record.push_back(-1); // mark the end of the diag/map pairs for this
2484 // location.
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002485 }
2486 }
2487
Argyrios Kyrtzidis60f76842010-11-05 22:20:49 +00002488 if (!Record.empty())
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002489 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002490}
2491
Anders Carlssonc8505782011-03-06 18:41:18 +00002492void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2493 if (CXXBaseSpecifiersOffsets.empty())
2494 return;
2495
2496 RecordData Record;
2497
2498 // Create a blob abbreviation for the C++ base specifiers offsets.
2499 using namespace llvm;
2500
2501 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2502 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2504 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2505 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2506
Douglas Gregore92b8a12011-08-04 00:01:48 +00002507 // Write the base specifier offsets table.
Anders Carlssonc8505782011-03-06 18:41:18 +00002508 Record.clear();
2509 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2510 Record.push_back(CXXBaseSpecifiersOffsets.size());
2511 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Benjamin Kramer6e089c62011-04-24 17:44:50 +00002512 data(CXXBaseSpecifiersOffsets));
Anders Carlssonc8505782011-03-06 18:41:18 +00002513}
2514
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002515//===----------------------------------------------------------------------===//
2516// Type Serialization
2517//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00002518
Sebastian Redl3397c552010-08-18 23:56:27 +00002519/// \brief Write the representation of a type to the AST stream.
Sebastian Redla4232eb2010-08-18 23:56:21 +00002520void ASTWriter::WriteType(QualType T) {
Argyrios Kyrtzidis01b81c42010-08-20 16:04:04 +00002521 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00002522 if (Idx.getIndex() == 0) // we haven't seen this type before.
2523 Idx = TypeIdx(NextTypeID++);
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Douglas Gregor97475832010-10-05 18:37:06 +00002525 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregor55f48de2010-10-04 18:21:45 +00002526
Douglas Gregor2cf26342009-04-09 22:27:44 +00002527 // Record the offset for this type.
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00002528 unsigned Index = Idx.getIndex() - FirstTypeID;
Sebastian Redl681d7232010-07-27 00:17:23 +00002529 if (TypeOffsets.size() == Index)
Douglas Gregorc9490c02009-04-16 22:23:12 +00002530 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Sebastian Redl681d7232010-07-27 00:17:23 +00002531 else if (TypeOffsets.size() < Index) {
2532 TypeOffsets.resize(Index + 1);
2533 TypeOffsets[Index] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002534 }
2535
2536 RecordData Record;
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregor2cf26342009-04-09 22:27:44 +00002538 // Emit the type's representation.
Sebastian Redl3397c552010-08-18 23:56:27 +00002539 ASTTypeWriter W(*this, Record);
John McCall0953e762009-09-24 19:53:00 +00002540
Douglas Gregora4923eb2009-11-16 21:35:15 +00002541 if (T.hasLocalNonFastQualifiers()) {
2542 Qualifiers Qs = T.getLocalQualifiers();
2543 AddTypeRef(T.getLocalUnqualifiedType(), Record);
John McCall0953e762009-09-24 19:53:00 +00002544 Record.push_back(Qs.getAsOpaqueValue());
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002545 W.Code = TYPE_EXT_QUAL;
John McCall0953e762009-09-24 19:53:00 +00002546 } else {
2547 switch (T->getTypeClass()) {
2548 // For all of the concrete, non-dependent types, call the
2549 // appropriate visitor function.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002550#define TYPE(Class, Base) \
Mike Stumpb7166332010-01-20 02:03:14 +00002551 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002552#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor2cf26342009-04-09 22:27:44 +00002553#include "clang/AST/TypeNodes.def"
John McCall0953e762009-09-24 19:53:00 +00002554 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002555 }
2556
2557 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00002558 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00002559
2560 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00002561 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002562}
2563
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002564//===----------------------------------------------------------------------===//
2565// Declaration Serialization
2566//===----------------------------------------------------------------------===//
2567
Douglas Gregor2cf26342009-04-09 22:27:44 +00002568/// \brief Write the block containing all of the declaration IDs
2569/// lexically declared within the given DeclContext.
2570///
2571/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2572/// bistream, or 0 if no block was written.
Sebastian Redla4232eb2010-08-18 23:56:21 +00002573uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregor2cf26342009-04-09 22:27:44 +00002574 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002575 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00002576 return 0;
2577
Douglas Gregorc9490c02009-04-16 22:23:12 +00002578 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002579 RecordData Record;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002580 Record.push_back(DECL_CONTEXT_LEXICAL);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002581 SmallVector<KindDeclIDPair, 64> Decls;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002582 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
2583 D != DEnd; ++D)
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002584 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002585
Douglas Gregor25123082009-04-22 22:34:57 +00002586 ++NumLexicalDeclContexts;
Benjamin Kramer6e089c62011-04-24 17:44:50 +00002587 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002588 return Offset;
2589}
2590
Sebastian Redla4232eb2010-08-18 23:56:21 +00002591void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1476ed42010-07-16 16:36:56 +00002592 using namespace llvm;
2593 RecordData Record;
2594
2595 // Write the type offsets array
2596 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002597 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1476ed42010-07-16 16:36:56 +00002598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregora119da02011-08-02 16:26:37 +00002599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1476ed42010-07-16 16:36:56 +00002600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2601 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2602 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002603 Record.push_back(TYPE_OFFSET);
Sebastian Redl1476ed42010-07-16 16:36:56 +00002604 Record.push_back(TypeOffsets.size());
Douglas Gregora119da02011-08-02 16:26:37 +00002605 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
Benjamin Kramer6e089c62011-04-24 17:44:50 +00002606 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
Sebastian Redl1476ed42010-07-16 16:36:56 +00002607
2608 // Write the declaration offsets array
2609 Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002610 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1476ed42010-07-16 16:36:56 +00002611 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregor496c7092011-08-03 15:48:04 +00002612 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1476ed42010-07-16 16:36:56 +00002613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2614 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2615 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002616 Record.push_back(DECL_OFFSET);
Sebastian Redl1476ed42010-07-16 16:36:56 +00002617 Record.push_back(DeclOffsets.size());
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00002618 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
Benjamin Kramer6e089c62011-04-24 17:44:50 +00002619 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
Sebastian Redl1476ed42010-07-16 16:36:56 +00002620}
2621
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002622void ASTWriter::WriteFileDeclIDsMap() {
2623 using namespace llvm;
2624 RecordData Record;
2625
2626 // Join the vectors of DeclIDs from all files.
2627 SmallVector<DeclID, 256> FileSortedIDs;
2628 for (FileDeclIDsTy::iterator
2629 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2630 DeclIDInFileInfo &Info = *FI->second;
2631 Info.FirstDeclIndex = FileSortedIDs.size();
2632 for (LocDeclIDsTy::iterator
2633 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2634 FileSortedIDs.push_back(DI->second);
2635 }
2636
2637 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2638 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2641 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2642 Record.push_back(FILE_SORTED_DECLS);
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002643 Record.push_back(FileSortedIDs.size());
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002644 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2645}
2646
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002647void ASTWriter::WriteComments() {
2648 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko811c8202012-07-06 18:19:34 +00002649 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002650 RecordData Record;
Dmitri Gribenko811c8202012-07-06 18:19:34 +00002651 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2652 E = RawComments.end();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002653 I != E; ++I) {
2654 Record.clear();
Dmitri Gribenko811c8202012-07-06 18:19:34 +00002655 AddSourceRange((*I)->getSourceRange(), Record);
2656 Record.push_back((*I)->getKind());
2657 Record.push_back((*I)->isTrailingComment());
2658 Record.push_back((*I)->isAlmostTrailingComment());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002659 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2660 }
2661 Stream.ExitBlock();
2662}
2663
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002664//===----------------------------------------------------------------------===//
2665// Global Method Pool and Selector Serialization
2666//===----------------------------------------------------------------------===//
2667
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002668namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002669// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl3397c552010-08-18 23:56:27 +00002670class ASTMethodPoolTrait {
Sebastian Redla4232eb2010-08-18 23:56:21 +00002671 ASTWriter &Writer;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002672
2673public:
2674 typedef Selector key_type;
2675 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Sebastian Redl5d050072010-08-04 17:20:04 +00002677 struct data_type {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002678 SelectorID ID;
Sebastian Redl5d050072010-08-04 17:20:04 +00002679 ObjCMethodList Instance, Factory;
2680 };
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002681 typedef const data_type& data_type_ref;
2682
Sebastian Redl3397c552010-08-18 23:56:27 +00002683 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002685 static unsigned ComputeHash(Selector Sel) {
Argyrios Kyrtzidis0eca89e2010-08-20 16:03:52 +00002686 return serialization::ComputeHash(Sel);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002687 }
Mike Stump1eb44332009-09-09 15:08:12 +00002688
2689 std::pair<unsigned,unsigned>
Chris Lattner5f9e2722011-07-23 10:55:15 +00002690 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002691 data_type_ref Methods) {
2692 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2693 clang::io::Emit16(Out, KeyLen);
Sebastian Redl5d050072010-08-04 17:20:04 +00002694 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2695 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002696 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002697 if (Method->Method)
2698 DataLen += 4;
Sebastian Redl5d050072010-08-04 17:20:04 +00002699 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002700 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002701 if (Method->Method)
2702 DataLen += 4;
2703 clang::io::Emit16(Out, DataLen);
2704 return std::make_pair(KeyLen, DataLen);
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattner5f9e2722011-07-23 10:55:15 +00002707 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump1eb44332009-09-09 15:08:12 +00002708 uint64_t Start = Out.tell();
Douglas Gregor83941df2009-04-25 17:48:32 +00002709 assert((Start >> 32) == 0 && "Selector key offset too large");
2710 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002711 unsigned N = Sel.getNumArgs();
2712 clang::io::Emit16(Out, N);
2713 if (N == 0)
2714 N = 1;
2715 for (unsigned I = 0; I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00002716 clang::io::Emit32(Out,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002717 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2718 }
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Chris Lattner5f9e2722011-07-23 10:55:15 +00002720 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00002721 data_type_ref Methods, unsigned DataLen) {
2722 uint64_t Start = Out.tell(); (void)Start;
Sebastian Redl5d050072010-08-04 17:20:04 +00002723 clang::io::Emit32(Out, Methods.ID);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002724 unsigned NumInstanceMethods = 0;
Sebastian Redl5d050072010-08-04 17:20:04 +00002725 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002726 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002727 if (Method->Method)
2728 ++NumInstanceMethods;
2729
2730 unsigned NumFactoryMethods = 0;
Sebastian Redl5d050072010-08-04 17:20:04 +00002731 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002732 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002733 if (Method->Method)
2734 ++NumFactoryMethods;
2735
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002736 unsigned InstanceBits = Methods.Instance.getBits();
2737 assert(InstanceBits < 4);
2738 unsigned NumInstanceMethodsAndBits =
2739 (NumInstanceMethods << 2) | InstanceBits;
2740 unsigned FactoryBits = Methods.Factory.getBits();
2741 assert(FactoryBits < 4);
2742 unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
2743 clang::io::Emit16(Out, NumInstanceMethodsAndBits);
2744 clang::io::Emit16(Out, NumFactoryMethodsAndBits);
Sebastian Redl5d050072010-08-04 17:20:04 +00002745 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002746 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002747 if (Method->Method)
2748 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Sebastian Redl5d050072010-08-04 17:20:04 +00002749 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002750 Method = Method->getNext())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002751 if (Method->Method)
2752 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00002753
2754 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002755 }
2756};
2757} // end anonymous namespace
2758
Sebastian Redl059612d2010-08-03 21:58:15 +00002759/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002760///
2761/// The method pool contains both instance and factory methods, stored
Sebastian Redl059612d2010-08-03 21:58:15 +00002762/// in an on-disk hash table indexed by the selector. The hash table also
2763/// contains an empty entry for every other selector known to Sema.
Sebastian Redla4232eb2010-08-18 23:56:21 +00002764void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002765 using namespace llvm;
2766
Sebastian Redl059612d2010-08-03 21:58:15 +00002767 // Do we have to do anything at all?
Sebastian Redl5d050072010-08-04 17:20:04 +00002768 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redl059612d2010-08-03 21:58:15 +00002769 return;
Sebastian Redle58aa892010-08-04 18:21:41 +00002770 unsigned NumTableEntries = 0;
Sebastian Redl059612d2010-08-03 21:58:15 +00002771 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002772 {
Sebastian Redl3397c552010-08-18 23:56:27 +00002773 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00002774 ASTMethodPoolTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Sebastian Redl059612d2010-08-03 21:58:15 +00002776 // Create the on-disk hash table representation. We walk through every
2777 // selector we've seen and look it up in the method pool.
Sebastian Redle58aa892010-08-04 18:21:41 +00002778 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002779 for (llvm::DenseMap<Selector, SelectorID>::iterator
Sebastian Redl5d050072010-08-04 17:20:04 +00002780 I = SelectorIDs.begin(), E = SelectorIDs.end();
2781 I != E; ++I) {
2782 Selector S = I->first;
Sebastian Redl059612d2010-08-03 21:58:15 +00002783 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl3397c552010-08-18 23:56:27 +00002784 ASTMethodPoolTrait::data_type Data = {
Sebastian Redl5d050072010-08-04 17:20:04 +00002785 I->second,
2786 ObjCMethodList(),
2787 ObjCMethodList()
2788 };
2789 if (F != SemaRef.MethodPool.end()) {
2790 Data.Instance = F->second.first;
2791 Data.Factory = F->second.second;
2792 }
Sebastian Redl3397c552010-08-18 23:56:27 +00002793 // Only write this selector if it's not in an existing AST or something
Sebastian Redle58aa892010-08-04 18:21:41 +00002794 // changed.
2795 if (Chain && I->second < FirstSelectorID) {
2796 // Selector already exists. Did it change?
2797 bool changed = false;
2798 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002799 M = M->getNext()) {
Douglas Gregor919814d2011-09-09 23:01:35 +00002800 if (!M->Method->isFromASTFile())
Sebastian Redle58aa892010-08-04 18:21:41 +00002801 changed = true;
2802 }
2803 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002804 M = M->getNext()) {
Douglas Gregor919814d2011-09-09 23:01:35 +00002805 if (!M->Method->isFromASTFile())
Sebastian Redle58aa892010-08-04 18:21:41 +00002806 changed = true;
2807 }
2808 if (!changed)
2809 continue;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00002810 } else if (Data.Instance.Method || Data.Factory.Method) {
2811 // A new method pool entry.
2812 ++NumTableEntries;
Sebastian Redle58aa892010-08-04 18:21:41 +00002813 }
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00002814 Generator.insert(S, Data, Trait);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002815 }
2816
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002817 // Create the on-disk hash table in a buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002818 SmallString<4096> MethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002819 uint32_t BucketOffset;
2820 {
Sebastian Redl3397c552010-08-18 23:56:27 +00002821 ASTMethodPoolTrait Trait(*this);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002822 llvm::raw_svector_ostream Out(MethodPool);
2823 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00002824 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002825 BucketOffset = Generator.Emit(Out, Trait);
2826 }
2827
2828 // Create a blob abbreviation
2829 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002830 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002831 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00002832 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2834 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2835
Douglas Gregor83941df2009-04-25 17:48:32 +00002836 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002837 RecordData Record;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002838 Record.push_back(METHOD_POOL);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002839 Record.push_back(BucketOffset);
Sebastian Redle58aa892010-08-04 18:21:41 +00002840 Record.push_back(NumTableEntries);
Daniel Dunbarec312a12009-08-24 09:31:37 +00002841 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor83941df2009-04-25 17:48:32 +00002842
2843 // Create a blob abbreviation for the selector table offsets.
2844 Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002845 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregor7c789c12010-10-29 22:39:52 +00002846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002847 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor83941df2009-04-25 17:48:32 +00002848 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2849 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2850
2851 // Write the selector offsets table.
2852 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002853 Record.push_back(SELECTOR_OFFSETS);
Douglas Gregor83941df2009-04-25 17:48:32 +00002854 Record.push_back(SelectorOffsets.size());
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002855 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
Douglas Gregor83941df2009-04-25 17:48:32 +00002856 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
Benjamin Kramer6e089c62011-04-24 17:44:50 +00002857 data(SelectorOffsets));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002858 }
2859}
2860
Sebastian Redl3397c552010-08-18 23:56:27 +00002861/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redla4232eb2010-08-18 23:56:21 +00002862void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanian32019832010-07-23 19:11:11 +00002863 using namespace llvm;
2864 if (SemaRef.ReferencedSelectors.empty())
2865 return;
Sebastian Redl725cd962010-08-04 20:40:17 +00002866
Fariborz Jahanian32019832010-07-23 19:11:11 +00002867 RecordData Record;
Sebastian Redl725cd962010-08-04 20:40:17 +00002868
Sebastian Redl3397c552010-08-18 23:56:27 +00002869 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redla68340f2010-08-04 22:21:29 +00002870 // very tricky to fix, and given that @selector shouldn't really appear in
2871 // headers, probably not worth it. It's not a correctness issue.
Fariborz Jahanian32019832010-07-23 19:11:11 +00002872 for (DenseMap<Selector, SourceLocation>::iterator S =
2873 SemaRef.ReferencedSelectors.begin(),
2874 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2875 Selector Sel = (*S).first;
2876 SourceLocation Loc = (*S).second;
2877 AddSelectorRef(Sel, Record);
2878 AddSourceLocation(Loc, Record);
2879 }
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002880 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanian32019832010-07-23 19:11:11 +00002881}
2882
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002883//===----------------------------------------------------------------------===//
2884// Identifier Table Serialization
2885//===----------------------------------------------------------------------===//
2886
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002887namespace {
Sebastian Redl3397c552010-08-18 23:56:27 +00002888class ASTIdentifierTableTrait {
Sebastian Redla4232eb2010-08-18 23:56:21 +00002889 ASTWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00002890 Preprocessor &PP;
Douglas Gregoreee242f2011-10-27 09:33:13 +00002891 IdentifierResolver &IdResolver;
Douglas Gregor7143aab2011-09-01 17:04:32 +00002892 bool IsModule;
2893
Douglas Gregora92193e2009-04-28 21:18:29 +00002894 /// \brief Determines whether this is an "interesting" identifier
2895 /// that needs a full IdentifierInfo structure written into the hash
2896 /// table.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002897 bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) {
Douglas Gregor7143aab2011-09-01 17:04:32 +00002898 if (II->isPoisoned() ||
2899 II->isExtensionToken() ||
2900 II->getObjCOrBuiltinID() ||
Douglas Gregoreee242f2011-10-27 09:33:13 +00002901 II->hasRevertedTokenIDToIdentifier() ||
Douglas Gregor7143aab2011-09-01 17:04:32 +00002902 II->getFETokenInfo<void>())
2903 return true;
2904
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00002905 return hadMacroDefinition(II, Macro);
Douglas Gregorce835df2011-09-14 22:14:14 +00002906 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00002907
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002908 bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00002909 if (!II->hadMacroDefinition())
Douglas Gregor7143aab2011-09-01 17:04:32 +00002910 return false;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00002911
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002912 if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) {
2913 if (!IsModule)
2914 return !shouldIgnoreMacro(Macro, IsModule, PP);
2915 SubmoduleID ModID;
2916 if (getFirstPublicSubmoduleMacro(Macro, ModID))
2917 return true;
2918 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00002919
2920 return false;
Douglas Gregora92193e2009-04-28 21:18:29 +00002921 }
2922
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002923 DefMacroDirective *getFirstPublicSubmoduleMacro(MacroDirective *MD,
2924 SubmoduleID &ModID) {
2925 ModID = 0;
2926 if (DefMacroDirective *DefMD = getPublicSubmoduleMacro(MD, ModID))
2927 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2928 return DefMD;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002929 return 0;
2930 }
2931
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002932 DefMacroDirective *getNextPublicSubmoduleMacro(DefMacroDirective *MD,
2933 SubmoduleID &ModID) {
2934 if (DefMacroDirective *
2935 DefMD = getPublicSubmoduleMacro(MD->getPrevious(), ModID))
2936 if (!shouldIgnoreMacro(DefMD, IsModule, PP))
2937 return DefMD;
2938 return 0;
2939 }
2940
2941 /// \brief Traverses the macro directives history and returns the latest
2942 /// macro that is public and not undefined in the same submodule.
2943 /// A macro that is defined in submodule A and undefined in submodule B,
2944 /// will still be considered as defined/exported from submodule A.
2945 DefMacroDirective *getPublicSubmoduleMacro(MacroDirective *MD,
2946 SubmoduleID &ModID) {
2947 if (!MD)
2948 return 0;
2949
Argyrios Kyrtzidisb2dbfd82013-04-03 05:11:33 +00002950 SubmoduleID OrigModID = ModID;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002951 bool isUndefined = false;
2952 Optional<bool> isPublic;
2953 for (; MD; MD = MD->getPrevious()) {
2954 if (MD->isHidden())
2955 continue;
2956
2957 SubmoduleID ThisModID = getSubmoduleID(MD);
2958 if (ThisModID == 0) {
2959 isUndefined = false;
2960 isPublic = Optional<bool>();
2961 continue;
2962 }
2963 if (ThisModID != ModID){
2964 ModID = ThisModID;
2965 isUndefined = false;
2966 isPublic = Optional<bool>();
2967 }
Argyrios Kyrtzidisb2dbfd82013-04-03 05:11:33 +00002968 // We are looking for a definition in a different submodule than the one
2969 // that we started with. If a submodule has re-definitions of the same
2970 // macro, only the last definition will be used as the "exported" one.
2971 if (ModID == OrigModID)
2972 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002973
2974 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2975 if (!isUndefined && (!isPublic.hasValue() || isPublic.getValue()))
2976 return DefMD;
2977 continue;
2978 }
2979
2980 if (isa<UndefMacroDirective>(MD)) {
2981 isUndefined = true;
2982 continue;
2983 }
2984
2985 VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
2986 if (!isPublic.hasValue())
2987 isPublic = VisMD->isPublic();
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002988 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002989
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002990 return 0;
2991 }
2992
2993 SubmoduleID getSubmoduleID(MacroDirective *MD) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00002994 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2995 MacroInfo *MI = DefMD->getInfo();
2996 if (unsigned ID = MI->getOwningModuleID())
2997 return ID;
2998 return Writer.inferSubmoduleIDFromLocation(MI->getDefinitionLoc());
2999 }
3000 return Writer.inferSubmoduleIDFromLocation(MD->getLocation());
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003001 }
3002
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003003public:
Douglas Gregor7143aab2011-09-01 17:04:32 +00003004 typedef IdentifierInfo* key_type;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003005 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003007 typedef IdentID data_type;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003008 typedef data_type data_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Douglas Gregoreee242f2011-10-27 09:33:13 +00003010 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3011 IdentifierResolver &IdResolver, bool IsModule)
3012 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003013
3014 static unsigned ComputeHash(const IdentifierInfo* II) {
Daniel Dunbar2596e422009-10-17 23:52:28 +00003015 return llvm::HashString(II->getName());
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003016 }
Mike Stump1eb44332009-09-09 15:08:12 +00003017
3018 std::pair<unsigned,unsigned>
Douglas Gregoreee242f2011-10-27 09:33:13 +00003019 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003020 unsigned KeyLen = II->getLength() + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00003021 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00003022 MacroDirective *Macro = 0;
Douglas Gregor7143aab2011-09-01 17:04:32 +00003023 if (isInterestingIdentifier(II, Macro)) {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003024 DataLen += 2; // 2 bytes for builtin ID
3025 DataLen += 2; // 2 bytes for flags
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00003026 if (hadMacroDefinition(II, Macro)) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003027 DataLen += 4; // MacroDirectives offset.
3028 if (IsModule) {
3029 SubmoduleID ModID;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00003030 for (DefMacroDirective *
3031 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3032 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003033 DataLen += 4; // MacroInfo ID.
3034 }
3035 DataLen += 4;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00003036 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00003037 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003038
Douglas Gregoreee242f2011-10-27 09:33:13 +00003039 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3040 DEnd = IdResolver.end();
Douglas Gregora92193e2009-04-28 21:18:29 +00003041 D != DEnd; ++D)
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003042 DataLen += sizeof(DeclID);
Douglas Gregora92193e2009-04-28 21:18:29 +00003043 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003044 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00003045 // We emit the key length after the data length so that every
3046 // string is preceded by a 16-bit length. This matches the PTH
3047 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00003048 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003049 return std::make_pair(KeyLen, DataLen);
3050 }
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Chris Lattner5f9e2722011-07-23 10:55:15 +00003052 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003053 unsigned KeyLen) {
3054 // Record the location of the key data. This is used when generating
3055 // the mapping from persistent IDs to strings.
3056 Writer.SetIdentifierOffset(II, Out.tell());
Daniel Dunbare013d682009-10-18 20:26:12 +00003057 Out.write(II->getNameStart(), KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003058 }
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Douglas Gregor7143aab2011-09-01 17:04:32 +00003060 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003061 IdentID ID, unsigned) {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00003062 MacroDirective *Macro = 0;
Douglas Gregor7143aab2011-09-01 17:04:32 +00003063 if (!isInterestingIdentifier(II, Macro)) {
Douglas Gregora92193e2009-04-28 21:18:29 +00003064 clang::io::Emit32(Out, ID << 1);
3065 return;
3066 }
Douglas Gregor5998da52009-04-28 21:32:13 +00003067
Douglas Gregora92193e2009-04-28 21:18:29 +00003068 clang::io::Emit32(Out, (ID << 1) | 0x01);
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003069 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3070 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3071 clang::io::Emit16(Out, Bits);
3072 Bits = 0;
3073 bool HadMacroDefinition = hadMacroDefinition(II, Macro);
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003074 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003075 Bits = (Bits << 1) | unsigned(IsModule);
Daniel Dunbarb0b84382009-12-18 20:58:47 +00003076 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3077 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Argyrios Kyrtzidis646395b2010-08-11 22:55:12 +00003078 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbarb0b84382009-12-18 20:58:47 +00003079 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Douglas Gregor5998da52009-04-28 21:32:13 +00003080 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003081
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003082 if (HadMacroDefinition) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003083 clang::io::Emit32(Out, Writer.getMacroDirectivesOffset(II));
3084 if (IsModule) {
3085 // Write the IDs of macros coming from different submodules.
3086 SubmoduleID ModID;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00003087 for (DefMacroDirective *
3088 DefMD = getFirstPublicSubmoduleMacro(Macro, ModID);
3089 DefMD; DefMD = getNextPublicSubmoduleMacro(DefMD, ModID)) {
3090 MacroID InfoID = Writer.getMacroID(DefMD->getInfo());
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003091 assert(InfoID);
3092 clang::io::Emit32(Out, InfoID);
3093 }
3094 clang::io::Emit32(Out, 0);
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00003095 }
Douglas Gregor13292642011-12-02 15:45:10 +00003096 }
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00003097
Douglas Gregor668c1a42009-04-21 22:25:48 +00003098 // Emit the declaration IDs in reverse order, because the
3099 // IdentifierResolver provides the declarations as they would be
3100 // visible (e.g., the function "stat" would come before the struct
Douglas Gregoreee242f2011-10-27 09:33:13 +00003101 // "stat"), but the ASTReader adds declarations to the end of the list
3102 // (so we need to see the struct "status" before the function "status").
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003103 // Only emit declarations that aren't from a chained PCH, though.
Douglas Gregoreee242f2011-10-27 09:33:13 +00003104 SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
3105 IdResolver.end());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003106 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
Douglas Gregoreee242f2011-10-27 09:33:13 +00003107 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003108 D != DEnd; ++D)
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00003109 clang::io::Emit32(Out, Writer.getDeclID(getMostRecentLocalDecl(*D)));
3110 }
3111
3112 /// \brief Returns the most recent local decl or the given decl if there are
3113 /// no local ones. The given decl is assumed to be the most recent one.
3114 Decl *getMostRecentLocalDecl(Decl *Orig) {
3115 // The only way a "from AST file" decl would be more recent from a local one
3116 // is if it came from a module.
3117 if (!PP.getLangOpts().Modules)
3118 return Orig;
3119
3120 // Look for a local in the decl chain.
3121 for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
3122 if (!D->isFromASTFile())
3123 return D;
3124 // If we come up a decl from a (chained-)PCH stop since we won't find a
3125 // local one.
3126 if (D->getOwningModuleID() == 0)
3127 break;
3128 }
3129
3130 return Orig;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003131 }
3132};
3133} // end anonymous namespace
3134
Sebastian Redl3397c552010-08-18 23:56:27 +00003135/// \brief Write the identifier table into the AST file.
Douglas Gregorafaf3082009-04-11 00:14:32 +00003136///
3137/// The identifier table consists of a blob containing string data
3138/// (the actual identifiers themselves) and a separate "offsets" index
3139/// that maps identifier IDs to locations within the blob.
Douglas Gregoreee242f2011-10-27 09:33:13 +00003140void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3141 IdentifierResolver &IdResolver,
3142 bool IsModule) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003143 using namespace llvm;
3144
3145 // Create and write out the blob that contains the identifier
3146 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00003147 {
Sebastian Redl3397c552010-08-18 23:56:27 +00003148 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Douglas Gregoreee242f2011-10-27 09:33:13 +00003149 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
Mike Stump1eb44332009-09-09 15:08:12 +00003150
Douglas Gregor92b059e2009-04-28 20:33:11 +00003151 // Look for any identifiers that were named while processing the
3152 // headers, but are otherwise not needed. We add these to the hash
3153 // table to enable checking of the predefines buffer in the case
Sebastian Redl3397c552010-08-18 23:56:27 +00003154 // where the user adds new macro definitions when building the AST
Douglas Gregor92b059e2009-04-28 20:33:11 +00003155 // file.
3156 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3157 IDEnd = PP.getIdentifierTable().end();
3158 ID != IDEnd; ++ID)
3159 getIdentifierRef(ID->second);
3160
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003161 // Create the on-disk hash table representation. We only store offsets
3162 // for identifiers that appear here for the first time.
3163 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003164 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
Douglas Gregorafaf3082009-04-11 00:14:32 +00003165 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
3166 ID != IDEnd; ++ID) {
3167 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregoreee242f2011-10-27 09:33:13 +00003168 if (!Chain || !ID->first->isFromAST() ||
3169 ID->first->hasChangedSinceDeserialization())
Douglas Gregor2d1ece82013-02-08 21:30:59 +00003170 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
Douglas Gregor7143aab2011-09-01 17:04:32 +00003171 Trait);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003172 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00003173
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003174 // Create the on-disk hash table in a buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003175 SmallString<4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003176 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003177 {
Douglas Gregoreee242f2011-10-27 09:33:13 +00003178 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003179 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003180 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00003181 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003182 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003183 }
3184
3185 // Create a blob abbreviation
3186 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003187 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00003188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003189 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00003190 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003191
3192 // Write the identifier table
3193 RecordData Record;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003194 Record.push_back(IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003195 Record.push_back(BucketOffset);
Daniel Dunbarec312a12009-08-24 09:31:37 +00003196 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregorafaf3082009-04-11 00:14:32 +00003197 }
3198
3199 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003200 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003201 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor6ec60e02011-08-03 21:49:18 +00003203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003204 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3205 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3206
Douglas Gregor2d1ece82013-02-08 21:30:59 +00003207#ifndef NDEBUG
3208 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3209 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3210#endif
3211
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003212 RecordData Record;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003213 Record.push_back(IDENTIFIER_OFFSET);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003214 Record.push_back(IdentifierOffsets.size());
Douglas Gregor6ec60e02011-08-03 21:49:18 +00003215 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003216 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Benjamin Kramer6e089c62011-04-24 17:44:50 +00003217 data(IdentifierOffsets));
Douglas Gregorafaf3082009-04-11 00:14:32 +00003218}
3219
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003220//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003221// DeclContext's Name Lookup Table Serialization
3222//===----------------------------------------------------------------------===//
3223
3224namespace {
3225// Trait used for the on-disk hash table used in the method pool.
3226class ASTDeclContextNameLookupTrait {
3227 ASTWriter &Writer;
3228
3229public:
3230 typedef DeclarationName key_type;
3231 typedef key_type key_type_ref;
3232
3233 typedef DeclContext::lookup_result data_type;
3234 typedef const data_type& data_type_ref;
3235
3236 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3237
3238 unsigned ComputeHash(DeclarationName Name) {
3239 llvm::FoldingSetNodeID ID;
3240 ID.AddInteger(Name.getNameKind());
3241
3242 switch (Name.getNameKind()) {
3243 case DeclarationName::Identifier:
3244 ID.AddString(Name.getAsIdentifierInfo()->getName());
3245 break;
3246 case DeclarationName::ObjCZeroArgSelector:
3247 case DeclarationName::ObjCOneArgSelector:
3248 case DeclarationName::ObjCMultiArgSelector:
3249 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3250 break;
3251 case DeclarationName::CXXConstructorName:
3252 case DeclarationName::CXXDestructorName:
3253 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003254 break;
3255 case DeclarationName::CXXOperatorName:
3256 ID.AddInteger(Name.getCXXOverloadedOperator());
3257 break;
3258 case DeclarationName::CXXLiteralOperatorName:
3259 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3260 case DeclarationName::CXXUsingDirective:
3261 break;
3262 }
3263
3264 return ID.ComputeHash();
3265 }
3266
3267 std::pair<unsigned,unsigned>
Chris Lattner5f9e2722011-07-23 10:55:15 +00003268 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003269 data_type_ref Lookup) {
3270 unsigned KeyLen = 1;
3271 switch (Name.getNameKind()) {
3272 case DeclarationName::Identifier:
3273 case DeclarationName::ObjCZeroArgSelector:
3274 case DeclarationName::ObjCOneArgSelector:
3275 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003276 case DeclarationName::CXXLiteralOperatorName:
3277 KeyLen += 4;
3278 break;
3279 case DeclarationName::CXXOperatorName:
3280 KeyLen += 1;
3281 break;
Douglas Gregore3605012011-08-02 18:32:54 +00003282 case DeclarationName::CXXConstructorName:
3283 case DeclarationName::CXXDestructorName:
3284 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003285 case DeclarationName::CXXUsingDirective:
3286 break;
3287 }
3288 clang::io::Emit16(Out, KeyLen);
3289
3290 // 2 bytes for num of decls and 4 for each DeclID.
David Blaikie3bc93e32012-12-19 00:45:41 +00003291 unsigned DataLen = 2 + 4 * Lookup.size();
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003292 clang::io::Emit16(Out, DataLen);
3293
3294 return std::make_pair(KeyLen, DataLen);
3295 }
3296
Chris Lattner5f9e2722011-07-23 10:55:15 +00003297 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003298 using namespace clang::io;
3299
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003300 Emit8(Out, Name.getNameKind());
3301 switch (Name.getNameKind()) {
3302 case DeclarationName::Identifier:
3303 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
Benjamin Kramer59313312012-09-19 13:40:40 +00003304 return;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003305 case DeclarationName::ObjCZeroArgSelector:
3306 case DeclarationName::ObjCOneArgSelector:
3307 case DeclarationName::ObjCMultiArgSelector:
3308 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
Benjamin Kramer59313312012-09-19 13:40:40 +00003309 return;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003310 case DeclarationName::CXXOperatorName:
Benjamin Kramer59313312012-09-19 13:40:40 +00003311 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3312 "Invalid operator?");
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003313 Emit8(Out, Name.getCXXOverloadedOperator());
Benjamin Kramer59313312012-09-19 13:40:40 +00003314 return;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003315 case DeclarationName::CXXLiteralOperatorName:
3316 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
Benjamin Kramer59313312012-09-19 13:40:40 +00003317 return;
Douglas Gregore3605012011-08-02 18:32:54 +00003318 case DeclarationName::CXXConstructorName:
3319 case DeclarationName::CXXDestructorName:
3320 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003321 case DeclarationName::CXXUsingDirective:
Benjamin Kramer59313312012-09-19 13:40:40 +00003322 return;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003323 }
Benjamin Kramer59313312012-09-19 13:40:40 +00003324
3325 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003326 }
3327
Chris Lattner5f9e2722011-07-23 10:55:15 +00003328 void EmitData(raw_ostream& Out, key_type_ref,
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003329 data_type Lookup, unsigned DataLen) {
3330 uint64_t Start = Out.tell(); (void)Start;
David Blaikie3bc93e32012-12-19 00:45:41 +00003331 clang::io::Emit16(Out, Lookup.size());
3332 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3333 I != E; ++I)
3334 clang::io::Emit32(Out, Writer.GetDeclRef(*I));
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003335
3336 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3337 }
3338};
3339} // end anonymous namespace
3340
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003341/// \brief Write the block containing all of the declaration IDs
3342/// visible from the given DeclContext.
3343///
3344/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003345/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003346uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3347 DeclContext *DC) {
3348 if (DC->getPrimaryContext() != DC)
3349 return 0;
3350
3351 // Since there is no name lookup into functions or methods, don't bother to
3352 // build a visible-declarations table for these entities.
3353 if (DC->isFunctionOrMethod())
3354 return 0;
3355
3356 // If not in C++, we perform name lookup for the translation unit via the
3357 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikie4e4d0842012-03-11 07:00:24 +00003358 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003359 return 0;
3360
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003361 // Serialize the contents of the mapping used for lookup. Note that,
3362 // although we have two very different code paths, the serialized
3363 // representation is the same for both cases: a declaration name,
3364 // followed by a size, followed by references to the visible
3365 // declarations that have that name.
3366 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithc5d3e802012-03-16 06:12:59 +00003367 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003368 if (!Map || Map->empty())
3369 return 0;
3370
3371 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3372 ASTDeclContextNameLookupTrait Trait(*this);
3373
3374 // Create the on-disk hash table representation.
Douglas Gregore5a54b62011-08-30 20:49:19 +00003375 DeclarationName ConversionName;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003376 SmallVector<NamedDecl *, 4> ConversionDecls;
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003377 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3378 D != DEnd; ++D) {
3379 DeclarationName Name = D->first;
3380 DeclContext::lookup_result Result = D->second.getLookupResult();
David Blaikie3bc93e32012-12-19 00:45:41 +00003381 if (!Result.empty()) {
Douglas Gregore5a54b62011-08-30 20:49:19 +00003382 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3383 // Hash all conversion function names to the same name. The actual
3384 // type information in conversion function name is not used in the
3385 // key (since such type information is not stable across different
3386 // modules), so the intended effect is to coalesce all of the conversion
3387 // functions under a single key.
3388 if (!ConversionName)
3389 ConversionName = Name;
David Blaikie3bc93e32012-12-19 00:45:41 +00003390 ConversionDecls.append(Result.begin(), Result.end());
Douglas Gregore5a54b62011-08-30 20:49:19 +00003391 continue;
3392 }
3393
Argyrios Kyrtzidis45118d82011-08-30 19:43:23 +00003394 Generator.insert(Name, Result, Trait);
Douglas Gregore5a54b62011-08-30 20:49:19 +00003395 }
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003396 }
3397
Douglas Gregore5a54b62011-08-30 20:49:19 +00003398 // Add the conversion functions
3399 if (!ConversionDecls.empty()) {
3400 Generator.insert(ConversionName,
3401 DeclContext::lookup_result(ConversionDecls.begin(),
3402 ConversionDecls.end()),
3403 Trait);
3404 }
3405
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003406 // Create the on-disk hash table in a buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003407 SmallString<4096> LookupTable;
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00003408 uint32_t BucketOffset;
3409 {
3410 llvm::raw_svector_ostream Out(LookupTable);
3411 // Make sure that no bucket is at offset 0
3412 clang::io::Emit32(Out, 0);
3413 BucketOffset = Generator.Emit(Out, Trait);
3414 }
3415
3416 // Write the lookup table
3417 RecordData Record;
3418 Record.push_back(DECL_CONTEXT_VISIBLE);
3419 Record.push_back(BucketOffset);
3420 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3421 LookupTable.str());
3422
3423 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
3424 ++NumVisibleDeclContexts;
3425 return Offset;
3426}
3427
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003428/// \brief Write an UPDATE_VISIBLE block for the given context.
3429///
3430/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3431/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithc5d3e802012-03-16 06:12:59 +00003432/// (in C++), for namespaces, and for classes with forward-declared unscoped
3433/// enumeration members (in C++11).
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003434void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003435 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
3436 if (!Map || Map->empty())
3437 return;
3438
3439 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
3440 ASTDeclContextNameLookupTrait Trait(*this);
3441
3442 // Create the hash table.
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003443 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
3444 D != DEnd; ++D) {
3445 DeclarationName Name = D->first;
3446 DeclContext::lookup_result Result = D->second.getLookupResult();
Sebastian Redl5967d622010-08-24 00:50:16 +00003447 // For any name that appears in this table, the results are complete, i.e.
3448 // they overwrite results from previous PCHs. Merging is always a mess.
David Blaikie3bc93e32012-12-19 00:45:41 +00003449 if (!Result.empty())
Argyrios Kyrtzidis45118d82011-08-30 19:43:23 +00003450 Generator.insert(Name, Result, Trait);
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003451 }
3452
3453 // Create the on-disk hash table in a buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003454 SmallString<4096> LookupTable;
Sebastian Redl1d1e42b2010-08-24 00:50:09 +00003455 uint32_t BucketOffset;
3456 {
3457 llvm::raw_svector_ostream Out(LookupTable);
3458 // Make sure that no bucket is at offset 0
3459 clang::io::Emit32(Out, 0);
3460 BucketOffset = Generator.Emit(Out, Trait);
3461 }
3462
3463 // Write the lookup table
3464 RecordData Record;
3465 Record.push_back(UPDATE_VISIBLE);
3466 Record.push_back(getDeclID(cast<Decl>(DC)));
3467 Record.push_back(BucketOffset);
3468 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3469}
3470
Peter Collingbourne84bccea2011-02-15 19:46:30 +00003471/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3472void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3473 RecordData Record;
3474 Record.push_back(Opts.fp_contract);
3475 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3476}
3477
3478/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3479void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003480 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne84bccea2011-02-15 19:46:30 +00003481 return;
3482
3483 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3484 RecordData Record;
3485#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3486#include "clang/Basic/OpenCLExtensions.def"
3487 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3488}
3489
Douglas Gregor2171bf12012-01-15 16:58:34 +00003490void ASTWriter::WriteRedeclarations() {
3491 RecordData LocalRedeclChains;
3492 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3493
3494 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3495 Decl *First = Redeclarations[I];
3496 assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
3497
3498 Decl *MostRecent = First->getMostRecentDecl();
3499
3500 // If we only have a single declaration, there is no point in storing
3501 // a redeclaration chain.
3502 if (First == MostRecent)
3503 continue;
3504
3505 unsigned Offset = LocalRedeclChains.size();
3506 unsigned Size = 0;
3507 LocalRedeclChains.push_back(0); // Placeholder for the size.
3508
3509 // Collect the set of local redeclarations of this declaration.
Douglas Gregoraa945902013-02-18 15:53:43 +00003510 for (Decl *Prev = MostRecent; Prev != First;
Douglas Gregor2171bf12012-01-15 16:58:34 +00003511 Prev = Prev->getPreviousDecl()) {
3512 if (!Prev->isFromASTFile()) {
3513 AddDeclRef(Prev, LocalRedeclChains);
3514 ++Size;
3515 }
3516 }
Douglas Gregoraa945902013-02-18 15:53:43 +00003517
3518 if (!First->isFromASTFile() && Chain) {
3519 Decl *FirstFromAST = MostRecent;
3520 for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3521 if (Prev->isFromASTFile())
3522 FirstFromAST = Prev;
3523 }
3524
3525 Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3526 }
3527
Douglas Gregor2171bf12012-01-15 16:58:34 +00003528 LocalRedeclChains[Offset] = Size;
3529
3530 // Reverse the set of local redeclarations, so that we store them in
3531 // order (since we found them in reverse order).
3532 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3533
Douglas Gregoraa945902013-02-18 15:53:43 +00003534 // Add the mapping from the first ID from the AST to the set of local
3535 // declarations.
Douglas Gregor2171bf12012-01-15 16:58:34 +00003536 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3537 LocalRedeclsMap.push_back(Info);
3538
3539 assert(N == Redeclarations.size() &&
3540 "Deserialized a declaration we shouldn't have");
3541 }
3542
3543 if (LocalRedeclChains.empty())
3544 return;
3545
3546 // Sort the local redeclarations map by the first declaration ID,
3547 // since the reader will be performing binary searches on this information.
3548 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3549
3550 // Emit the local redeclarations map.
3551 using namespace llvm;
3552 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3553 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3556 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3557
3558 RecordData Record;
3559 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3560 Record.push_back(LocalRedeclsMap.size());
3561 Stream.EmitRecordWithBlob(AbbrevID, Record,
3562 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3563 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3564
3565 // Emit the redeclaration chains.
3566 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3567}
3568
Douglas Gregorcff9f262012-01-27 01:47:08 +00003569void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003570 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregorcff9f262012-01-27 01:47:08 +00003571 RecordData Categories;
3572
3573 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3574 unsigned Size = 0;
3575 unsigned StartIndex = Categories.size();
3576
3577 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3578
3579 // Allocate space for the size.
3580 Categories.push_back(0);
3581
3582 // Add the categories.
Douglas Gregord3297242013-01-16 23:00:23 +00003583 for (ObjCInterfaceDecl::known_categories_iterator
3584 Cat = Class->known_categories_begin(),
3585 CatEnd = Class->known_categories_end();
3586 Cat != CatEnd; ++Cat, ++Size) {
3587 assert(getDeclID(*Cat) != 0 && "Bogus category");
3588 AddDeclRef(*Cat, Categories);
Douglas Gregorcff9f262012-01-27 01:47:08 +00003589 }
3590
3591 // Update the size.
3592 Categories[StartIndex] = Size;
3593
3594 // Record this interface -> category map.
3595 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3596 CategoriesMap.push_back(CatInfo);
3597 }
3598
3599 // Sort the categories map by the definition ID, since the reader will be
3600 // performing binary searches on this information.
3601 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3602
3603 // Emit the categories map.
3604 using namespace llvm;
3605 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3606 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3609 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3610
3611 RecordData Record;
3612 Record.push_back(OBJC_CATEGORIES_MAP);
3613 Record.push_back(CategoriesMap.size());
3614 Stream.EmitRecordWithBlob(AbbrevID, Record,
3615 reinterpret_cast<char*>(CategoriesMap.data()),
3616 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3617
3618 // Emit the category lists.
3619 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3620}
3621
Douglas Gregorc3cfd2a2011-12-22 21:40:42 +00003622void ASTWriter::WriteMergedDecls() {
3623 if (!Chain || Chain->MergedDecls.empty())
3624 return;
3625
3626 RecordData Record;
3627 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3628 IEnd = Chain->MergedDecls.end();
3629 I != IEnd; ++I) {
Douglas Gregorb6b60c12012-01-05 22:27:05 +00003630 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
Douglas Gregorc3cfd2a2011-12-22 21:40:42 +00003631 : getDeclID(I->first);
3632 assert(CanonID && "Merged declaration not known?");
3633
3634 Record.push_back(CanonID);
3635 Record.push_back(I->second.size());
3636 Record.append(I->second.begin(), I->second.end());
3637 }
3638 Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3639}
3640
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00003641//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003642// General Serialization Routines
3643//===----------------------------------------------------------------------===//
3644
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003645/// \brief Write a record containing the given attributes.
Alexander Kornienko49908902012-07-09 10:04:07 +00003646void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3647 RecordDataImpl &Record) {
Argyrios Kyrtzidis4eb9fc02010-10-18 19:20:11 +00003648 Record.push_back(Attrs.size());
Alexander Kornienko49908902012-07-09 10:04:07 +00003649 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3650 e = Attrs.end(); i != e; ++i){
3651 const Attr *A = *i;
Sean Huntcf807c42010-08-18 23:23:40 +00003652 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Argyrios Kyrtzidis768d6ca2011-09-13 16:05:58 +00003653 AddSourceRange(A->getRange(), Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003654
Sean Huntcf807c42010-08-18 23:23:40 +00003655#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbar4e9255f2010-05-27 02:25:39 +00003656
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003657 }
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003658}
3659
Chris Lattner5f9e2722011-07-23 10:55:15 +00003660void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003661 Record.push_back(Str.size());
3662 Record.insert(Record.end(), Str.begin(), Str.end());
3663}
3664
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00003665void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3666 RecordDataImpl &Record) {
3667 Record.push_back(Version.getMajor());
David Blaikiedc84cd52013-02-20 22:23:23 +00003668 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00003669 Record.push_back(*Minor + 1);
3670 else
3671 Record.push_back(0);
David Blaikiedc84cd52013-02-20 22:23:23 +00003672 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00003673 Record.push_back(*Subminor + 1);
3674 else
3675 Record.push_back(0);
3676}
3677
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003678/// \brief Note that the identifier II occurs at the given offset
3679/// within the identifier table.
Sebastian Redla4232eb2010-08-18 23:56:21 +00003680void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003681 IdentID ID = IdentifierIDs[II];
Sebastian Redl3397c552010-08-18 23:56:27 +00003682 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003683 // up earlier in the chain and thus don't need an offset.
3684 if (ID >= FirstIdentID)
3685 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00003686}
3687
Douglas Gregor83941df2009-04-25 17:48:32 +00003688/// \brief Note that the selector Sel occurs at the given offset
3689/// within the method pool/selector table.
Sebastian Redla4232eb2010-08-18 23:56:21 +00003690void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003691 unsigned ID = SelectorIDs[Sel];
3692 assert(ID && "Unknown selector");
Sebastian Redle58aa892010-08-04 18:21:41 +00003693 // Don't record offsets for selectors that are also available in a different
3694 // file.
3695 if (ID < FirstSelectorID)
3696 return;
3697 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor83941df2009-04-25 17:48:32 +00003698}
3699
Sebastian Redla4232eb2010-08-18 23:56:21 +00003700ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore209e502011-12-06 01:10:29 +00003701 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00003702 WritingAST(false), DoneWritingDeclsAndTypes(false),
3703 ASTHasCompilerErrors(false),
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00003704 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003705 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
Douglas Gregora8235d62012-10-09 23:05:51 +00003706 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3707 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
Douglas Gregor26ced122011-12-01 00:59:36 +00003708 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3709 NextSubmoduleID(FirstSubmoduleID),
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00003710 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
Douglas Gregor77424bc2010-10-02 19:29:26 +00003711 CollectedStmts(&StmtsToEmit),
Sebastian Redle58aa892010-08-04 18:21:41 +00003712 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
Douglas Gregora72d8c42011-06-03 02:27:19 +00003713 NumVisibleDeclContexts(0),
Douglas Gregore92b8a12011-08-04 00:01:48 +00003714 NextCXXBaseSpecifiersID(1),
Jonathan D. Turner953c5642011-06-03 23:11:16 +00003715 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
Douglas Gregora72d8c42011-06-03 02:27:19 +00003716 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3717 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3718 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
Jonathan D. Turner953c5642011-06-03 23:11:16 +00003719 DeclTypedefAbbrev(0),
3720 DeclVarAbbrev(0), DeclFieldAbbrev(0),
3721 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
Douglas Gregor7c789c12010-10-29 22:39:52 +00003722{
Sebastian Redl30c514c2010-07-14 23:45:08 +00003723}
Douglas Gregor2cf26342009-04-09 22:27:44 +00003724
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00003725ASTWriter::~ASTWriter() {
3726 for (FileDeclIDsTy::iterator
3727 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
3728 delete I->second;
3729}
3730
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00003731void ASTWriter::WriteAST(Sema &SemaRef,
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00003732 const std::string &OutputFile,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00003733 Module *WritingModule, StringRef isysroot,
3734 bool hasErrors) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00003735 WritingAST = true;
3736
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00003737 ASTHasCompilerErrors = hasErrors;
3738
Douglas Gregor2cf26342009-04-09 22:27:44 +00003739 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00003740 Stream.Emit((unsigned)'C', 8);
3741 Stream.Emit((unsigned)'P', 8);
3742 Stream.Emit((unsigned)'C', 8);
3743 Stream.Emit((unsigned)'H', 8);
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Chris Lattnerb145b1e2009-04-26 22:26:21 +00003745 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00003746
Douglas Gregor3b8043b2011-08-09 15:13:55 +00003747 Context = &SemaRef.Context;
Douglas Gregor185dbd72011-12-01 02:07:58 +00003748 PP = &SemaRef.PP;
Douglas Gregore209e502011-12-06 01:10:29 +00003749 this->WritingModule = WritingModule;
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00003750 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Douglas Gregor3b8043b2011-08-09 15:13:55 +00003751 Context = 0;
Douglas Gregor185dbd72011-12-01 02:07:58 +00003752 PP = 0;
Douglas Gregore209e502011-12-06 01:10:29 +00003753 this->WritingModule = 0;
Douglas Gregor61c5e342011-09-17 00:05:03 +00003754
3755 WritingAST = false;
Sebastian Redl1dc13a12010-07-12 22:02:52 +00003756}
3757
Douglas Gregora2ee20a2011-07-27 21:45:57 +00003758template<typename Vector>
3759static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
3760 ASTWriter::RecordData &Record) {
3761 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
3762 I != E; ++I) {
3763 Writer.AddDeclRef(*I, Record);
3764 }
3765}
3766
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00003767void ASTWriter::WriteASTCore(Sema &SemaRef,
Douglas Gregor832d6202011-07-22 16:35:34 +00003768 StringRef isysroot,
Douglas Gregora8cc6ce2011-11-30 04:39:39 +00003769 const std::string &OutputFile,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003770 Module *WritingModule) {
Sebastian Redl1dc13a12010-07-12 22:02:52 +00003771 using namespace llvm;
3772
Argyrios Kyrtzidis975d3532013-03-14 04:44:56 +00003773 bool isModule = WritingModule != 0;
3774
Douglas Gregorecc2c092011-12-01 22:20:10 +00003775 // Make sure that the AST reader knows to finalize itself.
3776 if (Chain)
3777 Chain->finalizeForWriting();
3778
Sebastian Redl1dc13a12010-07-12 22:02:52 +00003779 ASTContext &Context = SemaRef.Context;
3780 Preprocessor &PP = SemaRef.PP;
3781
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003782 // Set up predefined declaration IDs.
3783 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00003784 if (Context.ObjCIdDecl)
3785 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
Douglas Gregor7a27ea52011-08-12 06:17:30 +00003786 if (Context.ObjCSelDecl)
3787 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
Douglas Gregor79d67262011-08-12 05:59:41 +00003788 if (Context.ObjCClassDecl)
3789 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
Douglas Gregora6ea10e2012-01-17 18:09:05 +00003790 if (Context.ObjCProtocolClassDecl)
3791 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
Douglas Gregor772eeae2011-08-12 06:49:56 +00003792 if (Context.Int128Decl)
3793 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
3794 if (Context.UInt128Decl)
3795 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
Douglas Gregore97179c2011-09-08 01:46:34 +00003796 if (Context.ObjCInstanceTypeDecl)
3797 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
Meador Ingec5613b22012-06-16 03:34:49 +00003798 if (Context.BuiltinVaListDecl)
3799 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
3800
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003801 if (!Chain) {
3802 // Make sure that we emit IdentifierInfos (and any attached
3803 // declarations) for builtins. We don't need to do this when we're
3804 // emitting chained PCH files, because all of the builtins will be
3805 // in the original PCH file.
3806 // FIXME: Modules won't like this at all.
Douglas Gregor2deaea32009-04-22 18:49:13 +00003807 IdentifierTable &Table = PP.getIdentifierTable();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003808 SmallVector<const char *, 32> BuiltinNames;
Douglas Gregor2deaea32009-04-22 18:49:13 +00003809 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
David Blaikie4e4d0842012-03-11 07:00:24 +00003810 Context.getLangOpts().NoBuiltin);
Douglas Gregor2deaea32009-04-22 18:49:13 +00003811 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
3812 getIdentifierRef(&Table.get(BuiltinNames[I]));
3813 }
3814
Douglas Gregoreee242f2011-10-27 09:33:13 +00003815 // If there are any out-of-date identifiers, bring them up to date.
3816 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
Douglas Gregor589dae72013-01-07 16:56:53 +00003817 // Find out-of-date identifiers.
3818 SmallVector<IdentifierInfo *, 4> OutOfDate;
Douglas Gregoreee242f2011-10-27 09:33:13 +00003819 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3820 IDEnd = PP.getIdentifierTable().end();
Douglas Gregor589dae72013-01-07 16:56:53 +00003821 ID != IDEnd; ++ID) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00003822 if (ID->second->isOutOfDate())
Douglas Gregor589dae72013-01-07 16:56:53 +00003823 OutOfDate.push_back(ID->second);
3824 }
3825
3826 // Update the out-of-date identifiers.
3827 for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
3828 ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
3829 }
Douglas Gregoreee242f2011-10-27 09:33:13 +00003830 }
3831
Chris Lattner63d65f82009-09-08 18:19:27 +00003832 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redle9d12b62010-01-31 22:27:38 +00003833 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner63d65f82009-09-08 18:19:27 +00003834 // headers.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003835 RecordData TentativeDefinitions;
Douglas Gregora2ee20a2011-07-27 21:45:57 +00003836 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregora8623202011-07-27 20:58:46 +00003837
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00003838 // Build a record containing all of the file scoped decls in this file.
3839 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidisfaf01f02013-03-14 04:45:00 +00003840 if (!isModule)
3841 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
3842 UnusedFileScopedDecls);
Sebastian Redl40566802010-08-05 18:21:25 +00003843
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003844 // Build a record containing all of the delegating constructors we still need
3845 // to resolve.
Sean Huntebcbe1d2011-05-04 23:29:54 +00003846 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidis975d3532013-03-14 04:44:56 +00003847 if (!isModule)
3848 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Sean Huntebcbe1d2011-05-04 23:29:54 +00003849
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003850 // Write the set of weak, undeclared identifiers. We always write the
3851 // entire table, since later PCH files in a PCH chain are only interested in
3852 // the results at the end of the chain.
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00003853 RecordData WeakUndeclaredIdentifiers;
3854 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
Douglas Gregor31e37b22011-07-28 18:09:57 +00003855 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00003856 I = SemaRef.WeakUndeclaredIdentifiers.begin(),
3857 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
3858 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
3859 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
3860 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
3861 WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
3862 }
3863 }
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00003864
Richard Smith5ea6ef42013-01-10 23:43:47 +00003865 // Build a record containing all of the locally-scoped extern "C"
Douglas Gregor14c22f22009-04-22 22:18:58 +00003866 // declarations in this header file. Generally, this record will be
3867 // empty.
Richard Smith5ea6ef42013-01-10 23:43:47 +00003868 RecordData LocallyScopedExternCDecls;
Sebastian Redl3397c552010-08-18 23:56:27 +00003869 // FIXME: This is filling in the AST file in densemap order which is
Chris Lattner63d65f82009-09-08 18:19:27 +00003870 // nondeterminstic!
Mike Stump1eb44332009-09-09 15:08:12 +00003871 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Richard Smith5ea6ef42013-01-10 23:43:47 +00003872 TD = SemaRef.LocallyScopedExternCDecls.begin(),
3873 TDEnd = SemaRef.LocallyScopedExternCDecls.end();
Douglas Gregorec12ce22011-07-28 14:20:37 +00003874 TD != TDEnd; ++TD) {
Douglas Gregor919814d2011-09-09 23:01:35 +00003875 if (!TD->second->isFromASTFile())
Richard Smith5ea6ef42013-01-10 23:43:47 +00003876 AddDeclRef(TD->second, LocallyScopedExternCDecls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00003877 }
3878
Douglas Gregorb81c1702009-04-27 20:06:05 +00003879 // Build a record containing all of the ext_vector declarations.
3880 RecordData ExtVectorDecls;
Douglas Gregord58a0a52011-07-28 00:39:29 +00003881 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00003882
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003883 // Build a record containing all of the VTable uses information.
3884 RecordData VTableUses;
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003885 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003886 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3887 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3888 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3889 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3890 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003891 }
3892
3893 // Build a record containing all of dynamic classes declarations.
3894 RecordData DynamicClasses;
Douglas Gregora126f172011-07-28 00:53:40 +00003895 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003896
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00003897 // Build a record containing all of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003898 RecordData PendingInstantiations;
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00003899 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
Chandler Carruth62c78d52010-08-25 08:44:16 +00003900 I = SemaRef.PendingInstantiations.begin(),
3901 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3902 AddDeclRef(I->first, PendingInstantiations);
3903 AddSourceLocation(I->second, PendingInstantiations);
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00003904 }
3905 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3906 "There are local ones at end of translation unit!");
3907
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003908 // Build a record containing some declaration references.
3909 RecordData SemaDeclRefs;
3910 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3911 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3912 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3913 }
3914
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00003915 RecordData CUDASpecialDeclRefs;
3916 if (Context.getcudaConfigureCallDecl()) {
3917 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
3918 }
3919
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003920 // Build a record containing all of the known namespaces.
3921 RecordData KnownNamespaces;
Nick Lewycky01a41142013-01-26 00:35:08 +00003922 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
Douglas Gregord8bba9c2011-06-28 16:20:02 +00003923 I = SemaRef.KnownNamespaces.begin(),
3924 IEnd = SemaRef.KnownNamespaces.end();
3925 I != IEnd; ++I) {
3926 if (!I->second)
3927 AddDeclRef(I->first, KnownNamespaces);
3928 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003929
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003930 // Build a record of all used, undefined objects that require definitions.
3931 RecordData UndefinedButUsed;
Nick Lewycky995e26b2013-01-31 03:23:57 +00003932
3933 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003934 SemaRef.getUndefinedButUsed(Undefined);
Nick Lewycky995e26b2013-01-31 03:23:57 +00003935 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
3936 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003937 AddDeclRef(I->first, UndefinedButUsed);
3938 AddSourceLocation(I->second, UndefinedButUsed);
Nick Lewycky01a41142013-01-26 00:35:08 +00003939 }
3940
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003941 // Write the control block
Douglas Gregorbbf38312012-10-24 16:50:34 +00003942 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003943
Sebastian Redl3397c552010-08-18 23:56:27 +00003944 // Write the remaining AST contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00003945 RecordData Record;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00003946 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003947
Argyrios Kyrtzidis5e24f2d2012-12-13 21:38:23 +00003948 // This is so that older clang versions, before the introduction
3949 // of the control block, can read and reject the newer PCH format.
3950 Record.clear();
3951 Record.push_back(VERSION_MAJOR);
3952 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
3953
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003954 // Create a lexical update block containing all of the declarations in the
3955 // translation unit that do not come from other AST files.
3956 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3957 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
3958 for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
3959 E = TU->noload_decls_end();
3960 I != E; ++I) {
Douglas Gregor919814d2011-09-09 23:01:35 +00003961 if (!(*I)->isFromASTFile())
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003962 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003963 }
3964
3965 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
3966 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
3967 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3968 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
3969 Record.clear();
3970 Record.push_back(TU_UPDATE_LEXICAL);
3971 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
3972 data(NewGlobalDecls));
3973
3974 // And a visible updates block for the translation unit.
3975 Abv = new llvm::BitCodeAbbrev();
3976 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
3977 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3978 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
3979 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3980 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
3981 WriteDeclContextVisibleUpdate(TU);
3982
3983 // If the translation unit has an anonymous namespace, and we don't already
3984 // have an update block for it, write it as an update block.
3985 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
3986 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
3987 if (Record.empty()) {
3988 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
Douglas Gregor61c5e342011-09-17 00:05:03 +00003989 Record.push_back(reinterpret_cast<uint64_t>(NS));
Douglas Gregorb7c324f2011-08-12 01:39:19 +00003990 }
3991 }
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00003992
3993 // Make sure visible decls, added to DeclContexts previously loaded from
3994 // an AST file, are registered for serialization.
3995 for (SmallVector<const Decl *, 16>::iterator
3996 I = UpdatingVisibleDecls.begin(),
3997 E = UpdatingVisibleDecls.end(); I != E; ++I) {
3998 GetDeclRef(*I);
3999 }
4000
Argyrios Kyrtzidis67bc4ba2011-11-14 04:52:24 +00004001 // Resolve any declaration pointers within the declaration updates block.
Douglas Gregor61c5e342011-09-17 00:05:03 +00004002 ResolveDeclUpdatesBlocks();
Douglas Gregor61c5e342011-09-17 00:05:03 +00004003
Douglas Gregora119da02011-08-02 16:26:37 +00004004 // Form the record of special types.
4005 RecordData SpecialTypes;
Douglas Gregora119da02011-08-02 16:26:37 +00004006 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregora119da02011-08-02 16:26:37 +00004007 AddTypeRef(Context.getFILEType(), SpecialTypes);
4008 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4009 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4010 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4011 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregora119da02011-08-02 16:26:37 +00004012 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004013 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregor185dbd72011-12-01 02:07:58 +00004014
Douglas Gregor366809a2009-04-26 03:49:13 +00004015 // Keep writing types and declarations until all types and
4016 // declarations have been written.
Douglas Gregora72d8c42011-06-03 02:27:19 +00004017 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004018 WriteDeclsBlockAbbrevs();
Douglas Gregorb7c324f2011-08-12 01:39:19 +00004019 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4020 E = DeclsToRewrite.end();
4021 I != E; ++I)
4022 DeclTypesToEmit.push(const_cast<Decl*>(*I));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004023 while (!DeclTypesToEmit.empty()) {
4024 DeclOrType DOT = DeclTypesToEmit.front();
4025 DeclTypesToEmit.pop();
4026 if (DOT.isType())
4027 WriteType(DOT.getType());
4028 else
4029 WriteDecl(Context, DOT.getDecl());
4030 }
4031 Stream.ExitBlock();
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00004032
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00004033 DoneWritingDeclsAndTypes = true;
4034
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004035 WriteFileDeclIDsMap();
4036 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00004037 WriteComments();
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004038
4039 if (Chain) {
4040 // Write the mapping information describing our module dependencies and how
4041 // each of those modules were mapped into our own offset/ID space, so that
4042 // the reader can build the appropriate mapping to its own offset/ID space.
4043 // The map consists solely of a blob with the following format:
4044 // *(module-name-len:i16 module-name:len*i8
4045 // source-location-offset:i32
4046 // identifier-id:i32
4047 // preprocessed-entity-id:i32
4048 // macro-definition-id:i32
Douglas Gregor26ced122011-12-01 00:59:36 +00004049 // submodule-id:i32
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004050 // selector-id:i32
4051 // declaration-id:i32
4052 // c++-base-specifiers-id:i32
4053 // type-id:i32)
4054 //
4055 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4056 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4057 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4058 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004059 SmallString<2048> Buffer;
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004060 {
4061 llvm::raw_svector_ostream Out(Buffer);
4062 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00004063 MEnd = Chain->ModuleMgr.end();
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004064 M != MEnd; ++M) {
4065 StringRef FileName = (*M)->FileName;
4066 io::Emit16(Out, FileName.size());
4067 Out.write(FileName.data(), FileName.size());
4068 io::Emit32(Out, (*M)->SLocEntryBaseOffset);
4069 io::Emit32(Out, (*M)->BaseIdentifierID);
Douglas Gregora8235d62012-10-09 23:05:51 +00004070 io::Emit32(Out, (*M)->BaseMacroID);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004071 io::Emit32(Out, (*M)->BasePreprocessedEntityID);
Douglas Gregor26ced122011-12-01 00:59:36 +00004072 io::Emit32(Out, (*M)->BaseSubmoduleID);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004073 io::Emit32(Out, (*M)->BaseSelectorID);
4074 io::Emit32(Out, (*M)->BaseDeclID);
4075 io::Emit32(Out, (*M)->BaseTypeIndex);
4076 }
4077 }
4078 Record.clear();
4079 Record.push_back(MODULE_OFFSET_MAP);
4080 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4081 Buffer.data(), Buffer.size());
4082 }
Argyrios Kyrtzidis975d3532013-03-14 04:44:56 +00004083 WritePreprocessor(PP, isModule);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004084 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
Sebastian Redl059612d2010-08-03 21:58:15 +00004085 WriteSelectors(SemaRef);
Fariborz Jahanian32019832010-07-23 19:11:11 +00004086 WriteReferencedSelectorsPool(SemaRef);
Argyrios Kyrtzidis975d3532013-03-14 04:44:56 +00004087 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne84bccea2011-02-15 19:46:30 +00004088 WriteFPPragmaOptions(SemaRef.getFPOptions());
4089 WriteOpenCLExtensions(SemaRef);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00004090
Sebastian Redl1476ed42010-07-16 16:36:56 +00004091 WriteTypeDeclOffsets();
Argyrios Kyrtzidisea744ab2013-03-27 17:17:23 +00004092 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregorad1de002009-04-18 05:55:16 +00004093
Anders Carlssonc8505782011-03-06 18:41:18 +00004094 WriteCXXBaseSpecifiersOffsets();
Douglas Gregor7c789c12010-10-29 22:39:52 +00004095
Douglas Gregore209e502011-12-06 01:10:29 +00004096 // If we're emitting a module, write out the submodule information.
4097 if (WritingModule)
4098 WriteSubmodules(WritingModule);
4099
Douglas Gregora119da02011-08-02 16:26:37 +00004100 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4101
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00004102 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00004103 if (!ExternalDefinitions.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004104 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00004105
4106 // Write the record containing tentative definitions.
4107 if (!TentativeDefinitions.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004108 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00004109
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00004110 // Write the record containing unused file scoped decls.
4111 if (!UnusedFileScopedDecls.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004112 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00004113
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00004114 // Write the record containing weak undeclared identifiers.
4115 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004116 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00004117 WeakUndeclaredIdentifiers);
4118
Richard Smith5ea6ef42013-01-10 23:43:47 +00004119 // Write the record containing locally-scoped extern "C" definitions.
4120 if (!LocallyScopedExternCDecls.empty())
4121 Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4122 LocallyScopedExternCDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00004123
4124 // Write the record containing ext_vector type names.
4125 if (!ExtVectorDecls.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004126 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00004128 // Write the record containing VTable uses information.
4129 if (!VTableUses.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004130 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00004131
4132 // Write the record containing dynamic classes declarations.
4133 if (!DynamicClasses.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004134 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00004135
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00004136 // Write the record containing pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00004137 if (!PendingInstantiations.empty())
4138 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00004139
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004140 // Write the record containing declaration references of Sema.
4141 if (!SemaDeclRefs.empty())
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004142 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004143
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00004144 // Write the record containing CUDA-specific declaration references.
4145 if (!CUDASpecialDeclRefs.empty())
4146 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Sean Huntebcbe1d2011-05-04 23:29:54 +00004147
4148 // Write the delegating constructors.
4149 if (!DelegatingCtorDecls.empty())
4150 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00004151
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004152 // Write the known namespaces.
4153 if (!KnownNamespaces.empty())
4154 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky01a41142013-01-26 00:35:08 +00004155
Nick Lewyckycd0655b2013-02-01 08:13:20 +00004156 // Write the undefined internal functions and variables, and inline functions.
4157 if (!UndefinedButUsed.empty())
4158 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004159
Douglas Gregorb7c324f2011-08-12 01:39:19 +00004160 // Write the visible updates to DeclContexts.
4161 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
4162 I = UpdatedDeclContexts.begin(),
4163 E = UpdatedDeclContexts.end();
4164 I != E; ++I)
4165 WriteDeclContextVisibleUpdate(*I);
4166
Douglas Gregorc5e0f9b2011-12-03 01:15:29 +00004167 if (!WritingModule) {
4168 // Write the submodules that were imported, if any.
4169 RecordData ImportedModules;
4170 for (ASTContext::import_iterator I = Context.local_import_begin(),
4171 IEnd = Context.local_import_end();
4172 I != IEnd; ++I) {
4173 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4174 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
4175 }
4176 if (!ImportedModules.empty()) {
4177 // Sort module IDs.
4178 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
4179
4180 // Unique module IDs.
4181 ImportedModules.erase(std::unique(ImportedModules.begin(),
4182 ImportedModules.end()),
4183 ImportedModules.end());
4184
4185 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4186 }
Douglas Gregorf6137e42011-12-03 00:59:55 +00004187 }
Douglas Gregora8235d62012-10-09 23:05:51 +00004188
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00004189 WriteDeclUpdatesBlocks();
Douglas Gregorb7c324f2011-08-12 01:39:19 +00004190 WriteDeclReplacementsBlock();
Douglas Gregor2171bf12012-01-15 16:58:34 +00004191 WriteRedeclarations();
Douglas Gregoraa945902013-02-18 15:53:43 +00004192 WriteMergedDecls();
Douglas Gregorcff9f262012-01-27 01:47:08 +00004193 WriteObjCCategories();
Douglas Gregora1be2782011-12-17 23:38:30 +00004194
Douglas Gregor3e1af842009-04-17 22:13:46 +00004195 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00004196 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00004197 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00004198 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00004199 Record.push_back(NumLexicalDeclContexts);
4200 Record.push_back(NumVisibleDeclContexts);
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004201 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00004202 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00004203}
4204
Douglas Gregor61c5e342011-09-17 00:05:03 +00004205/// \brief Go through the declaration update blocks and resolve declaration
4206/// pointers into declaration IDs.
4207void ASTWriter::ResolveDeclUpdatesBlocks() {
4208 for (DeclUpdateMap::iterator
4209 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4210 const Decl *D = I->first;
4211 UpdateRecord &URec = I->second;
4212
Argyrios Kyrtzidisad834d52011-11-12 21:07:46 +00004213 if (isRewritten(D))
Douglas Gregor61c5e342011-09-17 00:05:03 +00004214 continue; // The decl will be written completely
4215
4216 unsigned Idx = 0, N = URec.size();
4217 while (Idx < N) {
4218 switch ((DeclUpdateKind)URec[Idx++]) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00004219 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4220 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4221 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4222 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
4223 ++Idx;
4224 break;
4225
4226 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4227 ++Idx;
4228 break;
4229 }
4230 }
4231 }
4232}
4233
Argyrios Kyrtzidisaacdd022010-10-24 17:26:43 +00004234void ASTWriter::WriteDeclUpdatesBlocks() {
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00004235 if (DeclUpdates.empty())
4236 return;
4237
4238 RecordData OffsetsRecord;
Douglas Gregora72d8c42011-06-03 02:27:19 +00004239 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00004240 for (DeclUpdateMap::iterator
4241 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
4242 const Decl *D = I->first;
4243 UpdateRecord &URec = I->second;
4244
Argyrios Kyrtzidisad834d52011-11-12 21:07:46 +00004245 if (isRewritten(D))
Argyrios Kyrtzidisba901b52010-10-24 17:26:46 +00004246 continue; // The decl will be written completely,no need to store updates.
4247
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00004248 uint64_t Offset = Stream.GetCurrentBitNo();
4249 Stream.EmitRecord(DECL_UPDATES, URec);
4250
4251 OffsetsRecord.push_back(GetDeclRef(D));
4252 OffsetsRecord.push_back(Offset);
4253 }
4254 Stream.ExitBlock();
4255 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
4256}
4257
Argyrios Kyrtzidisaacdd022010-10-24 17:26:43 +00004258void ASTWriter::WriteDeclReplacementsBlock() {
Sebastian Redl0b17c612010-08-13 00:28:03 +00004259 if (ReplacedDecls.empty())
4260 return;
4261
4262 RecordData Record;
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00004263 for (SmallVector<ReplacedDeclInfo, 16>::iterator
Sebastian Redl0b17c612010-08-13 00:28:03 +00004264 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00004265 Record.push_back(I->ID);
4266 Record.push_back(I->Offset);
4267 Record.push_back(I->Loc);
Sebastian Redl0b17c612010-08-13 00:28:03 +00004268 }
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004269 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
Sebastian Redl0b17c612010-08-13 00:28:03 +00004270}
4271
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004272void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00004273 Record.push_back(Loc.getRawEncoding());
4274}
4275
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004276void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattner6ad9ac02010-05-07 21:43:38 +00004277 AddSourceLocation(Range.getBegin(), Record);
4278 AddSourceLocation(Range.getEnd(), Record);
4279}
4280
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004281void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00004282 Record.push_back(Value.getBitWidth());
Benjamin Kramer4ea884b2010-09-06 23:43:28 +00004283 const uint64_t *Words = Value.getRawData();
4284 Record.append(Words, Words + Value.getNumWords());
Douglas Gregor2cf26342009-04-09 22:27:44 +00004285}
4286
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004287void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00004288 Record.push_back(Value.isUnsigned());
4289 AddAPInt(Value, Record);
4290}
4291
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004292void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00004293 AddAPInt(Value.bitcastToAPInt(), Record);
4294}
4295
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004296void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00004297 Record.push_back(getIdentifierRef(II));
4298}
4299
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004300IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00004301 if (II == 0)
4302 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00004303
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004304 IdentID &ID = IdentifierIDs[II];
Douglas Gregorafaf3082009-04-11 00:14:32 +00004305 if (ID == 0)
Sebastian Redlf2f0f032010-07-23 23:49:55 +00004306 ID = NextIdentID++;
Douglas Gregor2deaea32009-04-22 18:49:13 +00004307 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00004308}
4309
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00004310MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregora8235d62012-10-09 23:05:51 +00004311 // Don't emit builtin macros like __LINE__ to the AST file unless they
4312 // have been redefined by the header (in which case they are not
4313 // isBuiltinMacro).
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00004314 if (MI == 0 || MI->isBuiltinMacro())
Douglas Gregora8235d62012-10-09 23:05:51 +00004315 return 0;
4316
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00004317 MacroID &ID = MacroIDs[MI];
4318 if (ID == 0) {
Douglas Gregora8235d62012-10-09 23:05:51 +00004319 ID = NextMacroID++;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00004320 MacroInfoToEmitData Info = { Name, MI, ID };
4321 MacroInfosToEmit.push_back(Info);
4322 }
Douglas Gregora8235d62012-10-09 23:05:51 +00004323 return ID;
4324}
4325
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00004326MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4327 if (MI == 0 || MI->isBuiltinMacro())
4328 return 0;
4329
4330 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4331 return MacroIDs[MI];
4332}
4333
4334uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4335 assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4336 return IdentMacroDirectivesOffsetMap[Name];
4337}
4338
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004339void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl5d050072010-08-04 17:20:04 +00004340 Record.push_back(getSelectorRef(SelRef));
4341}
4342
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004343SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Sebastian Redl5d050072010-08-04 17:20:04 +00004344 if (Sel.getAsOpaquePtr() == 0) {
4345 return 0;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00004346 }
4347
Douglas Gregor2d1ece82013-02-08 21:30:59 +00004348 SelectorID SID = SelectorIDs[Sel];
Sebastian Redle58aa892010-08-04 18:21:41 +00004349 if (SID == 0 && Chain) {
4350 // This might trigger a ReadSelector callback, which will set the ID for
4351 // this selector.
4352 Chain->LoadSelector(Sel);
Douglas Gregor2d1ece82013-02-08 21:30:59 +00004353 SID = SelectorIDs[Sel];
Sebastian Redle58aa892010-08-04 18:21:41 +00004354 }
Steve Naroff90cd1bb2009-04-23 10:39:46 +00004355 if (SID == 0) {
Sebastian Redle58aa892010-08-04 18:21:41 +00004356 SID = NextSelectorID++;
Douglas Gregor2d1ece82013-02-08 21:30:59 +00004357 SelectorIDs[Sel] = SID;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00004358 }
Sebastian Redl5d050072010-08-04 17:20:04 +00004359 return SID;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00004360}
4361
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004362void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnerd2598362010-05-10 00:25:06 +00004363 AddDeclRef(Temp->getDestructor(), Record);
4364}
4365
Douglas Gregor7c789c12010-10-29 22:39:52 +00004366void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4367 CXXBaseSpecifier const *BasesEnd,
4368 RecordDataImpl &Record) {
4369 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4370 CXXBaseSpecifiersToWrite.push_back(
4371 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4372 Bases, BasesEnd));
4373 Record.push_back(NextCXXBaseSpecifiersID++);
4374}
4375
Sebastian Redla4232eb2010-08-18 23:56:21 +00004376void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004377 const TemplateArgumentLocInfo &Arg,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004378 RecordDataImpl &Record) {
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004379 switch (Kind) {
John McCall833ca992009-10-29 08:12:44 +00004380 case TemplateArgument::Expression:
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004381 AddStmt(Arg.getAsExpr());
John McCall833ca992009-10-29 08:12:44 +00004382 break;
4383 case TemplateArgument::Type:
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004384 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
John McCall833ca992009-10-29 08:12:44 +00004385 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00004386 case TemplateArgument::Template:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00004387 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00004388 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregora7fc9012011-01-05 18:58:31 +00004389 break;
4390 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00004391 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Douglas Gregora7fc9012011-01-05 18:58:31 +00004392 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregorba68eca2011-01-05 17:40:24 +00004393 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
Douglas Gregor788cd062009-11-11 01:00:40 +00004394 break;
John McCall833ca992009-10-29 08:12:44 +00004395 case TemplateArgument::Null:
4396 case TemplateArgument::Integral:
4397 case TemplateArgument::Declaration:
Eli Friedmand7a6b162012-09-26 02:36:12 +00004398 case TemplateArgument::NullPtr:
John McCall833ca992009-10-29 08:12:44 +00004399 case TemplateArgument::Pack:
Eli Friedmand7a6b162012-09-26 02:36:12 +00004400 // FIXME: Is this right?
John McCall833ca992009-10-29 08:12:44 +00004401 break;
4402 }
4403}
4404
Sebastian Redla4232eb2010-08-18 23:56:21 +00004405void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004406 RecordDataImpl &Record) {
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004407 AddTemplateArgument(Arg.getArgument(), Record);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00004408
4409 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4410 bool InfoHasSameExpr
4411 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4412 Record.push_back(InfoHasSameExpr);
4413 if (InfoHasSameExpr)
4414 return; // Avoid storing the same expr twice.
4415 }
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00004416 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4417 Record);
4418}
4419
Douglas Gregordc355712011-02-25 00:36:19 +00004420void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4421 RecordDataImpl &Record) {
John McCalla93c9342009-12-07 02:54:59 +00004422 if (TInfo == 0) {
John McCalla1ee0c52009-10-16 21:56:05 +00004423 AddTypeRef(QualType(), Record);
4424 return;
4425 }
4426
Douglas Gregordc355712011-02-25 00:36:19 +00004427 AddTypeLoc(TInfo->getTypeLoc(), Record);
4428}
4429
4430void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4431 AddTypeRef(TL.getType(), Record);
4432
John McCalla1ee0c52009-10-16 21:56:05 +00004433 TypeLocWriter TLW(*this, Record);
Douglas Gregordc355712011-02-25 00:36:19 +00004434 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnam11a18f12010-03-14 07:06:50 +00004435 TLW.Visit(TL);
John McCalla1ee0c52009-10-16 21:56:05 +00004436}
4437
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004438void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis7fb35182010-08-20 16:04:14 +00004439 Record.push_back(GetOrCreateTypeID(T));
4440}
4441
Douglas Gregor3b8043b2011-08-09 15:13:55 +00004442TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4443 return MakeTypeID(*Context, T,
Argyrios Kyrtzidiseb3f04e2010-08-20 16:04:20 +00004444 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4445}
Douglas Gregor2cf26342009-04-09 22:27:44 +00004446
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00004447TypeID ASTWriter::getTypeID(QualType T) const {
Douglas Gregor3b8043b2011-08-09 15:13:55 +00004448 return MakeTypeID(*Context, T,
Argyrios Kyrtzidiseb3f04e2010-08-20 16:04:20 +00004449 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
Argyrios Kyrtzidis26fca902010-08-20 16:04:09 +00004450}
4451
4452TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4453 if (T.isNull())
4454 return TypeIdx();
4455 assert(!T.getLocalFastQualifiers());
4456
Argyrios Kyrtzidis01b81c42010-08-20 16:04:04 +00004457 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00004458 if (Idx.getIndex() == 0) {
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00004459 if (DoneWritingDeclsAndTypes) {
4460 assert(0 && "New type seen after serializing all the types to emit!");
4461 return TypeIdx();
4462 }
4463
Douglas Gregor366809a2009-04-26 03:49:13 +00004464 // We haven't seen this type before. Assign it a new ID and put it
John McCall0953e762009-09-24 19:53:00 +00004465 // into the queue of types to emit.
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00004466 Idx = TypeIdx(NextTypeID++);
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004467 DeclTypesToEmit.push(T);
Douglas Gregor366809a2009-04-26 03:49:13 +00004468 }
Argyrios Kyrtzidis26fca902010-08-20 16:04:09 +00004469 return Idx;
4470}
Douglas Gregor2cf26342009-04-09 22:27:44 +00004471
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00004472TypeIdx ASTWriter::getTypeIdx(QualType T) const {
Argyrios Kyrtzidis26fca902010-08-20 16:04:09 +00004473 if (T.isNull())
4474 return TypeIdx();
4475 assert(!T.getLocalFastQualifiers());
4476
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +00004477 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4478 assert(I != TypeIdxs.end() && "Type not emitted!");
4479 return I->second;
Douglas Gregor2cf26342009-04-09 22:27:44 +00004480}
4481
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00004482void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl681d7232010-07-27 00:17:23 +00004483 Record.push_back(GetDeclRef(D));
4484}
4485
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004486DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00004487 assert(WritingAST && "Cannot request a declaration ID before AST writing");
4488
Douglas Gregor2cf26342009-04-09 22:27:44 +00004489 if (D == 0) {
Sebastian Redl681d7232010-07-27 00:17:23 +00004490 return 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00004491 }
Douglas Gregor1c7946a2012-01-05 22:33:30 +00004492
4493 // If D comes from an AST file, its declaration ID is already known and
4494 // fixed.
4495 if (D->isFromASTFile())
4496 return D->getGlobalID();
4497
Douglas Gregor97475832010-10-05 18:37:06 +00004498 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004499 DeclID &ID = DeclIDs[D];
Mike Stump1eb44332009-09-09 15:08:12 +00004500 if (ID == 0) {
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00004501 if (DoneWritingDeclsAndTypes) {
4502 assert(0 && "New decl seen after serializing all the decls to emit!");
4503 return 0;
4504 }
4505
Douglas Gregor2cf26342009-04-09 22:27:44 +00004506 // We haven't seen this declaration before. Give it a new ID and
4507 // enqueue it in the list of declarations to emit.
Sebastian Redlf2f0f032010-07-23 23:49:55 +00004508 ID = NextDeclID++;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004509 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregor2cf26342009-04-09 22:27:44 +00004510 }
4511
Sebastian Redl681d7232010-07-27 00:17:23 +00004512 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00004513}
4514
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004515DeclID ASTWriter::getDeclID(const Decl *D) {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00004516 if (D == 0)
4517 return 0;
4518
Douglas Gregor1c7946a2012-01-05 22:33:30 +00004519 // If D comes from an AST file, its declaration ID is already known and
4520 // fixed.
4521 if (D->isFromASTFile())
4522 return D->getGlobalID();
4523
Douglas Gregor3251ceb2009-04-20 20:36:09 +00004524 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4525 return DeclIDs[D];
4526}
4527
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004528static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
4529 std::pair<unsigned, serialization::DeclID> R) {
4530 return L.first < R.first;
4531}
4532
Argyrios Kyrtzidis19645d22011-10-28 23:57:43 +00004533void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004534 assert(ID);
Argyrios Kyrtzidis19645d22011-10-28 23:57:43 +00004535 assert(D);
4536
4537 SourceLocation Loc = D->getLocation();
4538 if (Loc.isInvalid())
4539 return;
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004540
4541 // We only keep track of the file-level declarations of each file.
4542 if (!D->getLexicalDeclContext()->isFileContext())
4543 return;
Argyrios Kyrtzidis69015c22012-02-24 19:45:46 +00004544 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4545 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis8cceefa2012-02-24 01:12:38 +00004546 if (isa<ParmVarDecl>(D))
4547 return;
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004548
4549 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidis19645d22011-10-28 23:57:43 +00004550 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004551 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidisfab8d5b2011-10-28 23:57:47 +00004552 FileID FID;
4553 unsigned Offset;
4554 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004555 if (FID.isInvalid())
4556 return;
Argyrios Kyrtzidisa2ea4d92012-10-02 21:09:17 +00004557 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004558
Argyrios Kyrtzidisa2ea4d92012-10-02 21:09:17 +00004559 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004560 if (!Info)
4561 Info = new DeclIDInFileInfo();
4562
Argyrios Kyrtzidisfab8d5b2011-10-28 23:57:47 +00004563 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004564 LocDeclIDsTy &Decls = Info->DeclIDs;
4565
Argyrios Kyrtzidisfab8d5b2011-10-28 23:57:47 +00004566 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00004567 Decls.push_back(LocDecl);
4568 return;
4569 }
4570
4571 LocDeclIDsTy::iterator
4572 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
4573
4574 Decls.insert(I, LocDecl);
4575}
4576
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004577void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00004578 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00004579 Record.push_back(Name.getNameKind());
4580 switch (Name.getNameKind()) {
4581 case DeclarationName::Identifier:
4582 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4583 break;
4584
4585 case DeclarationName::ObjCZeroArgSelector:
4586 case DeclarationName::ObjCOneArgSelector:
4587 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00004588 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004589 break;
4590
4591 case DeclarationName::CXXConstructorName:
4592 case DeclarationName::CXXDestructorName:
4593 case DeclarationName::CXXConversionFunctionName:
4594 AddTypeRef(Name.getCXXNameType(), Record);
4595 break;
4596
4597 case DeclarationName::CXXOperatorName:
4598 Record.push_back(Name.getCXXOverloadedOperator());
4599 break;
4600
Sean Hunt3e518bd2009-11-29 07:34:05 +00004601 case DeclarationName::CXXLiteralOperatorName:
4602 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4603 break;
4604
Douglas Gregor2cf26342009-04-09 22:27:44 +00004605 case DeclarationName::CXXUsingDirective:
4606 // No extra data to emit
4607 break;
4608 }
4609}
Chris Lattner6ad9ac02010-05-07 21:43:38 +00004610
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00004611void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004612 DeclarationName Name, RecordDataImpl &Record) {
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00004613 switch (Name.getNameKind()) {
4614 case DeclarationName::CXXConstructorName:
4615 case DeclarationName::CXXDestructorName:
4616 case DeclarationName::CXXConversionFunctionName:
4617 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
4618 break;
4619
4620 case DeclarationName::CXXOperatorName:
4621 AddSourceLocation(
4622 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4623 Record);
4624 AddSourceLocation(
4625 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4626 Record);
4627 break;
4628
4629 case DeclarationName::CXXLiteralOperatorName:
4630 AddSourceLocation(
4631 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
4632 Record);
4633 break;
4634
4635 case DeclarationName::Identifier:
4636 case DeclarationName::ObjCZeroArgSelector:
4637 case DeclarationName::ObjCOneArgSelector:
4638 case DeclarationName::ObjCMultiArgSelector:
4639 case DeclarationName::CXXUsingDirective:
4640 break;
4641 }
4642}
4643
4644void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004645 RecordDataImpl &Record) {
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00004646 AddDeclarationName(NameInfo.getName(), Record);
4647 AddSourceLocation(NameInfo.getLoc(), Record);
4648 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
4649}
4650
4651void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004652 RecordDataImpl &Record) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004653 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00004654 Record.push_back(Info.NumTemplParamLists);
4655 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
4656 AddTemplateParameterList(Info.TemplParamLists[i], Record);
4657}
4658
Sebastian Redla4232eb2010-08-18 23:56:21 +00004659void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004660 RecordDataImpl &Record) {
Chris Lattner6ad9ac02010-05-07 21:43:38 +00004661 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004662 // typically accommodate the vast majority.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004663 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00004664
4665 // Push each of the NNS's onto a stack for serialization in reverse order.
4666 while (NNS) {
4667 NestedNames.push_back(NNS);
4668 NNS = NNS->getPrefix();
4669 }
4670
4671 Record.push_back(NestedNames.size());
4672 while(!NestedNames.empty()) {
4673 NNS = NestedNames.pop_back_val();
4674 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
4675 Record.push_back(Kind);
4676 switch (Kind) {
4677 case NestedNameSpecifier::Identifier:
4678 AddIdentifierRef(NNS->getAsIdentifier(), Record);
4679 break;
4680
4681 case NestedNameSpecifier::Namespace:
4682 AddDeclRef(NNS->getAsNamespace(), Record);
4683 break;
4684
Douglas Gregor14aba762011-02-24 02:36:08 +00004685 case NestedNameSpecifier::NamespaceAlias:
4686 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
4687 break;
4688
Chris Lattner6ad9ac02010-05-07 21:43:38 +00004689 case NestedNameSpecifier::TypeSpec:
4690 case NestedNameSpecifier::TypeSpecWithTemplate:
4691 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
4692 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4693 break;
4694
4695 case NestedNameSpecifier::Global:
4696 // Don't need to write an associated value.
4697 break;
4698 }
4699 }
4700}
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004701
Douglas Gregordc355712011-02-25 00:36:19 +00004702void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4703 RecordDataImpl &Record) {
4704 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004705 // typically accommodate the vast majority.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004706 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregordc355712011-02-25 00:36:19 +00004707
4708 // Push each of the nested-name-specifiers's onto a stack for
4709 // serialization in reverse order.
4710 while (NNS) {
4711 NestedNames.push_back(NNS);
4712 NNS = NNS.getPrefix();
4713 }
4714
4715 Record.push_back(NestedNames.size());
4716 while(!NestedNames.empty()) {
4717 NNS = NestedNames.pop_back_val();
4718 NestedNameSpecifier::SpecifierKind Kind
4719 = NNS.getNestedNameSpecifier()->getKind();
4720 Record.push_back(Kind);
4721 switch (Kind) {
4722 case NestedNameSpecifier::Identifier:
4723 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
4724 AddSourceRange(NNS.getLocalSourceRange(), Record);
4725 break;
4726
4727 case NestedNameSpecifier::Namespace:
4728 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
4729 AddSourceRange(NNS.getLocalSourceRange(), Record);
4730 break;
4731
4732 case NestedNameSpecifier::NamespaceAlias:
4733 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
4734 AddSourceRange(NNS.getLocalSourceRange(), Record);
4735 break;
4736
4737 case NestedNameSpecifier::TypeSpec:
4738 case NestedNameSpecifier::TypeSpecWithTemplate:
4739 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
4740 AddTypeLoc(NNS.getTypeLoc(), Record);
4741 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4742 break;
4743
4744 case NestedNameSpecifier::Global:
4745 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
4746 break;
4747 }
4748 }
4749}
4750
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004751void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
Michael J. Spencer20249a12010-10-21 03:16:25 +00004752 TemplateName::NameKind Kind = Name.getKind();
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004753 Record.push_back(Kind);
4754 switch (Kind) {
4755 case TemplateName::Template:
4756 AddDeclRef(Name.getAsTemplateDecl(), Record);
4757 break;
4758
4759 case TemplateName::OverloadedTemplate: {
4760 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
4761 Record.push_back(OvT->size());
4762 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
4763 I != E; ++I)
4764 AddDeclRef(*I, Record);
4765 break;
4766 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004767
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004768 case TemplateName::QualifiedTemplate: {
4769 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
4770 AddNestedNameSpecifier(QualT->getQualifier(), Record);
4771 Record.push_back(QualT->hasTemplateKeyword());
4772 AddDeclRef(QualT->getTemplateDecl(), Record);
4773 break;
4774 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004775
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004776 case TemplateName::DependentTemplate: {
4777 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
4778 AddNestedNameSpecifier(DepT->getQualifier(), Record);
4779 Record.push_back(DepT->isIdentifier());
4780 if (DepT->isIdentifier())
4781 AddIdentifierRef(DepT->getIdentifier(), Record);
4782 else
4783 Record.push_back(DepT->getOperator());
4784 break;
4785 }
John McCall14606042011-06-30 08:33:18 +00004786
4787 case TemplateName::SubstTemplateTemplateParm: {
4788 SubstTemplateTemplateParmStorage *subst
4789 = Name.getAsSubstTemplateTemplateParm();
4790 AddDeclRef(subst->getParameter(), Record);
4791 AddTemplateName(subst->getReplacement(), Record);
4792 break;
4793 }
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004794
4795 case TemplateName::SubstTemplateTemplateParmPack: {
4796 SubstTemplateTemplateParmPackStorage *SubstPack
4797 = Name.getAsSubstTemplateTemplateParmPack();
4798 AddDeclRef(SubstPack->getParameterPack(), Record);
4799 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
4800 break;
4801 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004802 }
4803}
4804
Michael J. Spencer20249a12010-10-21 03:16:25 +00004805void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004806 RecordDataImpl &Record) {
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004807 Record.push_back(Arg.getKind());
4808 switch (Arg.getKind()) {
4809 case TemplateArgument::Null:
4810 break;
4811 case TemplateArgument::Type:
4812 AddTypeRef(Arg.getAsType(), Record);
4813 break;
4814 case TemplateArgument::Declaration:
4815 AddDeclRef(Arg.getAsDecl(), Record);
Eli Friedmand7a6b162012-09-26 02:36:12 +00004816 Record.push_back(Arg.isDeclForReferenceParam());
4817 break;
4818 case TemplateArgument::NullPtr:
4819 AddTypeRef(Arg.getNullPtrType(), Record);
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004820 break;
4821 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004822 AddAPSInt(Arg.getAsIntegral(), Record);
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004823 AddTypeRef(Arg.getIntegralType(), Record);
4824 break;
4825 case TemplateArgument::Template:
Douglas Gregor2be29f42011-01-14 23:41:42 +00004826 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
4827 break;
Douglas Gregora7fc9012011-01-05 18:58:31 +00004828 case TemplateArgument::TemplateExpansion:
4829 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
David Blaikiedc84cd52013-02-20 22:23:23 +00004830 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Douglas Gregor2be29f42011-01-14 23:41:42 +00004831 Record.push_back(*NumExpansions + 1);
4832 else
4833 Record.push_back(0);
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004834 break;
4835 case TemplateArgument::Expression:
4836 AddStmt(Arg.getAsExpr());
4837 break;
4838 case TemplateArgument::Pack:
4839 Record.push_back(Arg.pack_size());
4840 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
4841 I != E; ++I)
4842 AddTemplateArgument(*I, Record);
4843 break;
4844 }
4845}
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00004846
4847void
Sebastian Redla4232eb2010-08-18 23:56:21 +00004848ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004849 RecordDataImpl &Record) {
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00004850 assert(TemplateParams && "No TemplateParams!");
4851 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
4852 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
4853 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
4854 Record.push_back(TemplateParams->size());
4855 for (TemplateParameterList::const_iterator
4856 P = TemplateParams->begin(), PEnd = TemplateParams->end();
4857 P != PEnd; ++P)
4858 AddDeclRef(*P, Record);
4859}
4860
4861/// \brief Emit a template argument list.
4862void
Sebastian Redla4232eb2010-08-18 23:56:21 +00004863ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004864 RecordDataImpl &Record) {
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00004865 assert(TemplateArgs && "No TemplateArgs!");
Douglas Gregor910f8002010-11-07 23:05:16 +00004866 Record.push_back(TemplateArgs->size());
4867 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00004868 AddTemplateArgument(TemplateArgs->get(i), Record);
4869}
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00004870
4871
4872void
Argyrios Kyrtzidis2a82ca22012-11-28 03:56:16 +00004873ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00004874 Record.push_back(Set.size());
Argyrios Kyrtzidis2a82ca22012-11-28 03:56:16 +00004875 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00004876 I = Set.begin(), E = Set.end(); I != E; ++I) {
4877 AddDeclRef(I.getDecl(), Record);
4878 Record.push_back(I.getAccess());
4879 }
4880}
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00004881
Sebastian Redla4232eb2010-08-18 23:56:21 +00004882void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004883 RecordDataImpl &Record) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00004884 Record.push_back(Base.isVirtual());
4885 Record.push_back(Base.isBaseOfClass());
4886 Record.push_back(Base.getAccessSpecifierAsWritten());
Sebastian Redlf677ea32011-02-05 19:23:19 +00004887 Record.push_back(Base.getInheritConstructors());
Nick Lewycky56062202010-07-26 16:56:01 +00004888 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00004889 AddSourceRange(Base.getSourceRange(), Record);
Douglas Gregorf90b27a2011-01-03 22:36:02 +00004890 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
4891 : SourceLocation(),
4892 Record);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00004893}
Sebastian Redl30c514c2010-07-14 23:45:08 +00004894
Douglas Gregor7c789c12010-10-29 22:39:52 +00004895void ASTWriter::FlushCXXBaseSpecifiers() {
4896 RecordData Record;
4897 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
4898 Record.clear();
4899
4900 // Record the offset of this base-specifier set.
Douglas Gregore92b8a12011-08-04 00:01:48 +00004901 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
Douglas Gregor7c789c12010-10-29 22:39:52 +00004902 if (Index == CXXBaseSpecifiersOffsets.size())
4903 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
4904 else {
4905 if (Index > CXXBaseSpecifiersOffsets.size())
4906 CXXBaseSpecifiersOffsets.resize(Index + 1);
4907 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
4908 }
4909
4910 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
4911 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
4912 Record.push_back(BEnd - B);
4913 for (; B != BEnd; ++B)
4914 AddCXXBaseSpecifier(*B, Record);
4915 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
Douglas Gregoracec34b2010-10-30 04:28:16 +00004916
4917 // Flush any expressions that were written as part of the base specifiers.
4918 FlushStmts();
Douglas Gregor7c789c12010-10-29 22:39:52 +00004919 }
4920
4921 CXXBaseSpecifiersToWrite.clear();
4922}
4923
Sean Huntcbb67482011-01-08 20:30:50 +00004924void ASTWriter::AddCXXCtorInitializers(
4925 const CXXCtorInitializer * const *CtorInitializers,
4926 unsigned NumCtorInitializers,
4927 RecordDataImpl &Record) {
4928 Record.push_back(NumCtorInitializers);
4929 for (unsigned i=0; i != NumCtorInitializers; ++i) {
4930 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004931
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004932 if (Init->isBaseInitializer()) {
Sean Hunt156b6402011-05-04 01:19:08 +00004933 Record.push_back(CTOR_INITIALIZER_BASE);
Douglas Gregor76852c22011-11-01 01:16:03 +00004934 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004935 Record.push_back(Init->isBaseVirtual());
Sean Hunt156b6402011-05-04 01:19:08 +00004936 } else if (Init->isDelegatingInitializer()) {
4937 Record.push_back(CTOR_INITIALIZER_DELEGATING);
Douglas Gregor76852c22011-11-01 01:16:03 +00004938 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Sean Hunt156b6402011-05-04 01:19:08 +00004939 } else if (Init->isMemberInitializer()){
4940 Record.push_back(CTOR_INITIALIZER_MEMBER);
4941 AddDeclRef(Init->getMember(), Record);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004942 } else {
Sean Hunt156b6402011-05-04 01:19:08 +00004943 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
4944 AddDeclRef(Init->getIndirectMember(), Record);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004945 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00004946
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004947 AddSourceLocation(Init->getMemberLocation(), Record);
4948 AddStmt(Init->getInit());
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00004949 AddSourceLocation(Init->getLParenLoc(), Record);
4950 AddSourceLocation(Init->getRParenLoc(), Record);
4951 Record.push_back(Init->isWritten());
4952 if (Init->isWritten()) {
4953 Record.push_back(Init->getSourceOrder());
4954 } else {
4955 Record.push_back(Init->getNumArrayIndices());
4956 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
4957 AddDeclRef(Init->getArrayIndex(i), Record);
4958 }
4959 }
4960}
4961
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004962void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
4963 assert(D->DefinitionData);
4964 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
Douglas Gregor9d36f5d2012-02-14 17:54:36 +00004965 Record.push_back(Data.IsLambda);
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004966 Record.push_back(Data.UserDeclaredConstructor);
Richard Smith7d04d3a2012-11-30 05:11:39 +00004967 Record.push_back(Data.UserDeclaredSpecialMembers);
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004968 Record.push_back(Data.Aggregate);
4969 Record.push_back(Data.PlainOldData);
4970 Record.push_back(Data.Empty);
4971 Record.push_back(Data.Polymorphic);
4972 Record.push_back(Data.Abstract);
Chandler Carruthec997dc2011-04-30 10:07:30 +00004973 Record.push_back(Data.IsStandardLayout);
Chandler Carrutha8225442011-04-30 09:17:45 +00004974 Record.push_back(Data.HasNoNonEmptyBases);
4975 Record.push_back(Data.HasPrivateFields);
4976 Record.push_back(Data.HasProtectedFields);
4977 Record.push_back(Data.HasPublicFields);
Douglas Gregor2bb11012011-05-13 01:05:07 +00004978 Record.push_back(Data.HasMutableFields);
Richard Smithdfefb842012-02-25 07:33:38 +00004979 Record.push_back(Data.HasOnlyCMembers);
Richard Smithd079abf2012-05-07 01:07:30 +00004980 Record.push_back(Data.HasInClassInitializer);
Richard Smithd5bc8672012-12-08 02:01:17 +00004981 Record.push_back(Data.HasUninitializedReferenceMember);
Richard Smithbc2a35d2012-12-08 08:32:28 +00004982 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
4983 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
4984 Record.push_back(Data.NeedOverloadResolutionForDestructor);
4985 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
4986 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
4987 Record.push_back(Data.DefaultedDestructorIsDeleted);
Richard Smith7d04d3a2012-11-30 05:11:39 +00004988 Record.push_back(Data.HasTrivialSpecialMembers);
4989 Record.push_back(Data.HasIrrelevantDestructor);
Richard Smith6b8bc072011-08-10 18:11:37 +00004990 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
Richard Smithdfefb842012-02-25 07:33:38 +00004991 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
Richard Smithdfefb842012-02-25 07:33:38 +00004992 Record.push_back(Data.HasConstexprDefaultConstructor);
Chandler Carruth9b6347c2011-04-24 02:49:34 +00004993 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00004994 Record.push_back(Data.ComputedVisibleConversions);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004995 Record.push_back(Data.UserProvidedDefaultConstructor);
Richard Smith7d04d3a2012-11-30 05:11:39 +00004996 Record.push_back(Data.DeclaredSpecialMembers);
Richard Smithacf796b2012-11-28 06:23:12 +00004997 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
4998 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
4999 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5000 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Sebastian Redl14c36332011-08-31 13:59:56 +00005001 Record.push_back(Data.FailedImplicitMoveConstructor);
5002 Record.push_back(Data.FailedImplicitMoveAssignment);
Richard Smithdfefb842012-02-25 07:33:38 +00005003 // IsLambda bit is already saved.
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00005004
5005 Record.push_back(Data.NumBases);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005006 if (Data.NumBases > 0)
5007 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5008 Record);
5009
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00005010 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5011 Record.push_back(Data.NumVBases);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005012 if (Data.NumVBases > 0)
5013 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5014 Record);
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00005015
5016 AddUnresolvedSet(Data.Conversions, Record);
5017 AddUnresolvedSet(Data.VisibleConversions, Record);
5018 // Data.Definition is the owning decl, no need to write it.
5019 AddDeclRef(Data.FirstFriend, Record);
Douglas Gregor9d36f5d2012-02-14 17:54:36 +00005020
5021 // Add lambda-specific data.
5022 if (Data.IsLambda) {
5023 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
Douglas Gregorf4b7de12012-02-21 19:11:17 +00005024 Record.push_back(Lambda.Dependent);
Douglas Gregor9d36f5d2012-02-14 17:54:36 +00005025 Record.push_back(Lambda.NumCaptures);
5026 Record.push_back(Lambda.NumExplicitCaptures);
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00005027 Record.push_back(Lambda.ManglingNumber);
Douglas Gregorccc1b5e2012-02-21 00:37:24 +00005028 AddDeclRef(Lambda.ContextDecl, Record);
Eli Friedman8da8a662012-09-19 01:18:11 +00005029 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
Douglas Gregor9d36f5d2012-02-14 17:54:36 +00005030 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5031 LambdaExpr::Capture &Capture = Lambda.Captures[I];
5032 AddSourceLocation(Capture.getLocation(), Record);
5033 Record.push_back(Capture.isImplicit());
5034 Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
5035 VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0;
5036 AddDeclRef(Var, Record);
5037 AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
5038 : SourceLocation(),
5039 Record);
5040 }
5041 }
Argyrios Kyrtzidis89eaf3a2010-10-24 17:26:40 +00005042}
5043
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005044void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redlffaab3e2010-07-30 00:29:29 +00005045 assert(Reader && "Cannot remove chain");
Douglas Gregor10bc00f2011-08-18 04:12:04 +00005046 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redlffaab3e2010-07-30 00:29:29 +00005047 assert(FirstDeclID == NextDeclID &&
5048 FirstTypeID == NextTypeID &&
5049 FirstIdentID == NextIdentID &&
Douglas Gregora8235d62012-10-09 23:05:51 +00005050 FirstMacroID == NextMacroID &&
Douglas Gregor26ced122011-12-01 00:59:36 +00005051 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redle58aa892010-08-04 18:21:41 +00005052 FirstSelectorID == NextSelectorID &&
Sebastian Redlffaab3e2010-07-30 00:29:29 +00005053 "Setting chain after writing has started.");
Douglas Gregorf62d43d2011-07-19 16:10:42 +00005054
Sebastian Redlffaab3e2010-07-30 00:29:29 +00005055 Chain = Reader;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005056
Douglas Gregor10bc00f2011-08-18 04:12:04 +00005057 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5058 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5059 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregora8235d62012-10-09 23:05:51 +00005060 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor26ced122011-12-01 00:59:36 +00005061 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregor10bc00f2011-08-18 04:12:04 +00005062 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005063 NextDeclID = FirstDeclID;
5064 NextTypeID = FirstTypeID;
5065 NextIdentID = FirstIdentID;
Douglas Gregora8235d62012-10-09 23:05:51 +00005066 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005067 NextSelectorID = FirstSelectorID;
Douglas Gregor26ced122011-12-01 00:59:36 +00005068 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redlffaab3e2010-07-30 00:29:29 +00005069}
5070
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005071void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor2d1ece82013-02-08 21:30:59 +00005072 // Always keep the highest ID. See \p TypeRead() for more information.
5073 IdentID &StoredID = IdentifierIDs[II];
5074 if (ID > StoredID)
5075 StoredID = ID;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00005076}
5077
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005078void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor2d1ece82013-02-08 21:30:59 +00005079 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005080 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor2d1ece82013-02-08 21:30:59 +00005081 if (ID > StoredID)
5082 StoredID = ID;
Douglas Gregora8235d62012-10-09 23:05:51 +00005083}
5084
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00005085void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor97475832010-10-05 18:37:06 +00005086 // Always take the highest-numbered type index. This copes with an interesting
5087 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer20249a12010-10-21 03:16:25 +00005088 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor97475832010-10-05 18:37:06 +00005089 // keep the higher-numbered entry so that we can properly write it out to
5090 // the AST file.
5091 TypeIdx &StoredIdx = TypeIdxs[T];
5092 if (Idx.getIndex() >= StoredIdx.getIndex())
5093 StoredIdx = Idx;
Sebastian Redl30c514c2010-07-14 23:45:08 +00005094}
5095
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005096void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor2d1ece82013-02-08 21:30:59 +00005097 // Always keep the highest ID. See \p TypeRead() for more information.
5098 SelectorID &StoredID = SelectorIDs[S];
5099 if (ID > StoredID)
5100 StoredID = ID;
Sebastian Redl5d050072010-08-04 17:20:04 +00005101}
Douglas Gregor77424bc2010-10-02 19:29:26 +00005102
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00005103void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Douglas Gregor77424bc2010-10-02 19:29:26 +00005104 MacroDefinition *MD) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00005105 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor77424bc2010-10-02 19:29:26 +00005106 MacroDefinitions[MD] = ID;
5107}
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005108
Douglas Gregora015cab2011-12-02 17:30:13 +00005109void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5110 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5111 SubmoduleIDs[Mod] = ID;
5112}
5113
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005114void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCall5e1cdac2011-10-07 06:10:15 +00005115 assert(D->isCompleteDefinition());
Douglas Gregor61c5e342011-09-17 00:05:03 +00005116 assert(!WritingAST && "Already writing the AST!");
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005117 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5118 // We are interested when a PCH decl is modified.
Douglas Gregor919814d2011-09-09 23:01:35 +00005119 if (RD->isFromASTFile()) {
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005120 // A forward reference was mutated into a definition. Rewrite it.
5121 // FIXME: This happens during template instantiation, should we
5122 // have created a new definition decl instead ?
Argyrios Kyrtzidisd3d07552010-10-28 07:38:45 +00005123 RewriteDecl(RD);
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005124 }
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00005125 }
5126}
Douglas Gregora8235d62012-10-09 23:05:51 +00005127
Argyrios Kyrtzidis100050b2010-10-28 07:38:51 +00005128void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00005129 assert(!WritingAST && "Already writing the AST!");
5130
Argyrios Kyrtzidis100050b2010-10-28 07:38:51 +00005131 // TU and namespaces are handled elsewhere.
5132 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5133 return;
5134
Douglas Gregor919814d2011-09-09 23:01:35 +00005135 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
Argyrios Kyrtzidis100050b2010-10-28 07:38:51 +00005136 return; // Not a source decl added to a DeclContext from PCH.
5137
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005138 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Argyrios Kyrtzidis100050b2010-10-28 07:38:51 +00005139 AddUpdatedDeclContext(DC);
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00005140 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis100050b2010-10-28 07:38:51 +00005141}
Argyrios Kyrtzidisb6cc0e12010-10-24 17:26:54 +00005142
5143void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00005144 assert(!WritingAST && "Already writing the AST!");
Argyrios Kyrtzidisb6cc0e12010-10-24 17:26:54 +00005145 assert(D->isImplicit());
Douglas Gregor919814d2011-09-09 23:01:35 +00005146 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
Argyrios Kyrtzidisb6cc0e12010-10-24 17:26:54 +00005147 return; // Not a source member added to a class from PCH.
5148 if (!isa<CXXMethodDecl>(D))
5149 return; // We are interested in lazily declared implicit methods.
5150
5151 // A decl coming from PCH was modified.
John McCall5e1cdac2011-10-07 06:10:15 +00005152 assert(RD->isCompleteDefinition());
Argyrios Kyrtzidisb6cc0e12010-10-24 17:26:54 +00005153 UpdateRecord &Record = DeclUpdates[RD];
5154 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
Douglas Gregor61c5e342011-09-17 00:05:03 +00005155 Record.push_back(reinterpret_cast<uint64_t>(D));
Argyrios Kyrtzidisb6cc0e12010-10-24 17:26:54 +00005156}
Argyrios Kyrtzidisbef1a7b2010-10-28 07:38:42 +00005157
5158void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5159 const ClassTemplateSpecializationDecl *D) {
Argyrios Kyrtzidis0f04f692010-10-28 07:38:47 +00005160 // The specializations set is kept in the canonical template.
Douglas Gregor61c5e342011-09-17 00:05:03 +00005161 assert(!WritingAST && "Already writing the AST!");
Argyrios Kyrtzidis0f04f692010-10-28 07:38:47 +00005162 TD = TD->getCanonicalDecl();
Douglas Gregor919814d2011-09-09 23:01:35 +00005163 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
Argyrios Kyrtzidisbef1a7b2010-10-28 07:38:42 +00005164 return; // Not a source specialization added to a template from PCH.
5165
5166 UpdateRecord &Record = DeclUpdates[TD];
5167 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
Douglas Gregor61c5e342011-09-17 00:05:03 +00005168 Record.push_back(reinterpret_cast<uint64_t>(D));
Argyrios Kyrtzidisbef1a7b2010-10-28 07:38:42 +00005169}
Douglas Gregor89d99802010-11-30 06:16:57 +00005170
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00005171void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5172 const FunctionDecl *D) {
5173 // The specializations set is kept in the canonical template.
Douglas Gregor61c5e342011-09-17 00:05:03 +00005174 assert(!WritingAST && "Already writing the AST!");
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00005175 TD = TD->getCanonicalDecl();
Douglas Gregor919814d2011-09-09 23:01:35 +00005176 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00005177 return; // Not a source specialization added to a template from PCH.
5178
5179 UpdateRecord &Record = DeclUpdates[TD];
5180 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
Douglas Gregor61c5e342011-09-17 00:05:03 +00005181 Record.push_back(reinterpret_cast<uint64_t>(D));
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00005182}
5183
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005184void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00005185 assert(!WritingAST && "Already writing the AST!");
Douglas Gregor919814d2011-09-09 23:01:35 +00005186 if (!D->isFromASTFile())
Sebastian Redl58a2cd82011-04-24 16:28:06 +00005187 return; // Declaration not imported from PCH.
5188
5189 // Implicit decl from a PCH was defined.
5190 // FIXME: Should implicit definition be a separate FunctionDecl?
5191 RewriteDecl(D);
5192}
5193
Sebastian Redlf79a7192011-04-29 08:19:30 +00005194void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00005195 assert(!WritingAST && "Already writing the AST!");
Douglas Gregor919814d2011-09-09 23:01:35 +00005196 if (!D->isFromASTFile())
Sebastian Redlf79a7192011-04-29 08:19:30 +00005197 return;
5198
5199 // Since the actual instantiation is delayed, this really means that we need
5200 // to update the instantiation location.
5201 UpdateRecord &Record = DeclUpdates[D];
5202 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
5203 AddSourceLocation(
5204 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
5205}
5206
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005207void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5208 const ObjCInterfaceDecl *IFD) {
Douglas Gregor61c5e342011-09-17 00:05:03 +00005209 assert(!WritingAST && "Already writing the AST!");
Douglas Gregor919814d2011-09-09 23:01:35 +00005210 if (!IFD->isFromASTFile())
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005211 return; // Declaration not imported from PCH.
Douglas Gregorcff9f262012-01-27 01:47:08 +00005212
5213 assert(IFD->getDefinition() && "Category on a class without a definition?");
5214 ObjCClassesWithCategories.insert(
5215 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005216}
Argyrios Kyrtzidisad834d52011-11-12 21:07:46 +00005217
Argyrios Kyrtzidis1a434152011-11-12 21:07:52 +00005218
Argyrios Kyrtzidisc80553e2011-11-14 04:52:29 +00005219void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5220 const ObjCPropertyDecl *OrigProp,
5221 const ObjCCategoryDecl *ClassExt) {
5222 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5223 if (!D)
5224 return;
5225
5226 assert(!WritingAST && "Already writing the AST!");
5227 if (!D->isFromASTFile())
5228 return; // Declaration not imported from PCH.
5229
5230 RewriteDecl(D);
5231}