blob: 1d1c99874b6573878d87b067abfca9cbb50876fc [file] [log] [blame]
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001//===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
Douglas Gregoref84c4b2009-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 Redl55c0ad52010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl1914c6f2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000015#include "clang/Serialization/ModuleFileExtension.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000016#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000017#include "ASTReaderInternals.h"
18#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000022#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000023#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000025#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000028#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000029#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000031#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000032#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000033#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000034#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000035#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000036#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000037#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Lex/HeaderSearch.h"
39#include "clang/Lex/HeaderSearchOptions.h"
40#include "clang/Lex/MacroInfo.h"
41#include "clang/Lex/PreprocessingRecord.h"
42#include "clang/Lex/Preprocessor.h"
43#include "clang/Lex/PreprocessorOptions.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/Sema.h"
46#include "clang/Serialization/ASTReader.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000047#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000050#include "llvm/ADT/Hashing.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000051#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000052#include "llvm/Bitcode/BitstreamWriter.h"
Richard Smithaada85c2016-02-06 02:06:43 +000053#include "llvm/Support/Compression.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000054#include "llvm/Support/EndianStream.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000055#include "llvm/Support/FileSystem.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000056#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000057#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000058#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000059#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000060#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000061#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000062#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000063#include <utility>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +000064
Douglas Gregoref84c4b2009-04-09 22:27:44 +000065using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000066using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000067
Sebastian Redl3df5a082010-07-30 17:03:48 +000068template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +000069static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 if (v.empty()) return StringRef();
71 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000072 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000073}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000074
75template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +000076static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000078 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000079}
80
Douglas Gregoref84c4b2009-04-09 22:27:44 +000081//===----------------------------------------------------------------------===//
82// Type serialization
83//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000084
Douglas Gregoref84c4b2009-04-09 22:27:44 +000085namespace {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000086 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000087 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000088 ASTWriter::RecordDataImpl &Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
90 public:
91 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000092 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000093 /// \brief Abbreviation to use for the record, if any.
94 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000095
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000096 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Sebastian Redl539c5062010-08-18 23:57:32 +000097 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +000098
99 void VisitArrayType(const ArrayType *T);
100 void VisitFunctionType(const FunctionType *T);
101 void VisitTagType(const TagType *T);
102
103#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
104#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000105#include "clang/AST/TypeNodes.def"
106 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000107} // end anonymous namespace
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000108
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000109void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000110 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000111}
112
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000113void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000114 Writer.AddTypeRef(T->getElementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000115 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000116}
117
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000118void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000119 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000120 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000121}
122
Reid Kleckner8a365022013-06-24 17:51:48 +0000123void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
124 Writer.AddTypeRef(T->getOriginalType(), Record);
125 Code = TYPE_DECAYED;
126}
127
Reid Kleckner0503a872013-12-05 01:23:43 +0000128void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
129 Writer.AddTypeRef(T->getOriginalType(), Record);
130 Writer.AddTypeRef(T->getAdjustedType(), Record);
131 Code = TYPE_ADJUSTED;
132}
133
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000134void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000135 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000136 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000137}
138
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000139void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000140 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
141 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000142 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000143}
144
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000145void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000146 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000147 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000148}
149
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000150void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000151 Writer.AddTypeRef(T->getPointeeType(), Record);
152 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000153 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000154}
155
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000156void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000157 Writer.AddTypeRef(T->getElementType(), Record);
158 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000159 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000163 VisitArrayType(T);
164 Writer.AddAPInt(T->getSize(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000165 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166}
167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000168void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000169 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000170 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000171}
172
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000173void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000174 VisitArrayType(T);
Douglas Gregor04318252009-07-06 15:59:29 +0000175 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
176 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +0000177 Writer.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000178 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000179}
180
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000181void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000182 Writer.AddTypeRef(T->getElementType(), Record);
183 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000184 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000185 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000186}
187
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000188void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000190 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000191}
192
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000193void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Alp Toker314cc812014-01-25 16:55:45 +0000194 Writer.AddTypeRef(T->getReturnType(), Record);
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000195 FunctionType::ExtInfo C = T->getExtInfo();
196 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000197 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000198 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000199 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000200 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000201 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000202
203 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
204 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000205}
206
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000207void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000208 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000209 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000210}
211
Richard Smith564417a2014-03-20 21:47:22 +0000212static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
213 ASTWriter::RecordDataImpl &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000214 Record.push_back(T->getExceptionSpecType());
215 if (T->getExceptionSpecType() == EST_Dynamic) {
216 Record.push_back(T->getNumExceptions());
217 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
218 Writer.AddTypeRef(T->getExceptionType(I), Record);
219 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
220 Writer.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000221 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
222 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
223 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
Richard Smithd3b5c9082012-07-27 04:22:15 +0000224 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
225 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000226 }
Richard Smith564417a2014-03-20 21:47:22 +0000227}
228
229void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
230 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000231
Richard Smith564417a2014-03-20 21:47:22 +0000232 Record.push_back(T->isVariadic());
233 Record.push_back(T->hasTrailingReturn());
234 Record.push_back(T->getTypeQuals());
235 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
236 addExceptionSpec(Writer, T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000237
238 Record.push_back(T->getNumParams());
239 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
240 Writer.AddTypeRef(T->getParamType(I), Record);
241
242 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
243 T->getRefQualifier() || T->getExceptionSpecType() != EST_None)
244 AbbrevToUse = 0;
245
Sebastian Redl539c5062010-08-18 23:57:32 +0000246 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000247}
248
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000249void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
John McCallb96ec562009-12-04 22:46:56 +0000250 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000251 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000252}
John McCallb96ec562009-12-04 22:46:56 +0000253
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000254void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255 Writer.AddDeclRef(T->getDecl(), Record);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000256 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
257 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000258 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000259}
260
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000261void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregor8f45df52009-04-16 22:23:12 +0000262 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000263 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000264}
265
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000266void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000267 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000268 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000269}
270
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000271void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Douglas Gregor81495f32012-02-12 18:42:33 +0000272 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Anders Carlsson81df7b82009-06-24 19:06:50 +0000273 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000274 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000275}
276
Alexis Hunte852b102011-05-24 22:41:36 +0000277void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
278 Writer.AddTypeRef(T->getBaseType(), Record);
279 Writer.AddTypeRef(T->getUnderlyingType(), Record);
280 Record.push_back(T->getUTTKind());
281 Code = TYPE_UNARY_TRANSFORM;
282}
283
Richard Smith30482bc2011-02-20 03:19:35 +0000284void ASTTypeWriter::VisitAutoType(const AutoType *T) {
285 Writer.AddTypeRef(T->getDeducedType(), Record);
Richard Smithe301ba22015-11-11 02:02:15 +0000286 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000287 if (T->getDeducedType().isNull())
288 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000289 Code = TYPE_AUTO;
290}
291
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000292void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000293 Record.push_back(T->isDependentType());
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000294 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Mike Stump11289f42009-09-09 15:08:12 +0000295 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000296 "Cannot serialize in the middle of a type definition");
297}
298
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000299void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000300 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000301 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000302}
303
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000304void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000305 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000306 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000307}
308
John McCall81904512011-01-06 01:58:22 +0000309void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
310 Writer.AddTypeRef(T->getModifiedType(), Record);
311 Writer.AddTypeRef(T->getEquivalentType(), Record);
312 Record.push_back(T->getAttrKind());
313 Code = TYPE_ATTRIBUTED;
314}
315
Mike Stump11289f42009-09-09 15:08:12 +0000316void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000317ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000318 const SubstTemplateTypeParmType *T) {
319 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
320 Writer.AddTypeRef(T->getReplacementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000321 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000322}
323
324void
Douglas Gregorada4b792011-01-14 02:55:32 +0000325ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
326 const SubstTemplateTypeParmPackType *T) {
327 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
328 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
329 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
330}
331
332void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000333ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000334 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000335 Record.push_back(T->isDependentType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000336 Writer.AddTemplateName(T->getTemplateName(), Record);
337 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000338 for (const auto &ArgI : *T)
339 Writer.AddTemplateArgument(ArgI, Record);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000340 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
341 T->isCanonicalUnqualified() ? QualType()
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000342 : T->getCanonicalTypeInternal(),
343 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000344 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000345}
346
347void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000348ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000349 VisitArrayType(T);
350 Writer.AddStmt(T->getSizeExpr());
351 Writer.AddSourceRange(T->getBracketsRange(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000352 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000353}
354
355void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000356ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000357 const DependentSizedExtVectorType *T) {
358 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000359 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000360}
361
362void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000363ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000364 Record.push_back(T->getDepth());
365 Record.push_back(T->getIndex());
366 Record.push_back(T->isParameterPack());
Chandler Carruth08836322011-05-01 00:51:33 +0000367 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000368 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000369}
370
371void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000372ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000373 Record.push_back(T->getKeyword());
374 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
375 Writer.AddIdentifierRef(T->getIdentifier(), Record);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +0000376 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
377 : T->getCanonicalTypeInternal(),
378 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000379 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000380}
381
382void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000383ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000384 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000385 Record.push_back(T->getKeyword());
386 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
387 Writer.AddIdentifierRef(T->getIdentifier(), Record);
388 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000389 for (const auto &I : *T)
390 Writer.AddTemplateArgument(I, Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000391 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000392}
393
Douglas Gregord2fa7662010-12-20 02:24:11 +0000394void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
395 Writer.AddTypeRef(T->getPattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +0000396 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000397 Record.push_back(*NumExpansions + 1);
398 else
399 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000400 Code = TYPE_PACK_EXPANSION;
401}
402
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000403void ASTTypeWriter::VisitParenType(const ParenType *T) {
404 Writer.AddTypeRef(T->getInnerType(), Record);
405 Code = TYPE_PAREN;
406}
407
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000408void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000409 Record.push_back(T->getKeyword());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000410 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
411 Writer.AddTypeRef(T->getNamedType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000412 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000413}
414
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000415void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Douglas Gregor9f218892012-03-26 15:52:37 +0000416 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
John McCall2408e322010-04-27 00:57:59 +0000417 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000418 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000419}
420
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000421void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000422 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000423 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000424}
425
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000426void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
John McCall8b07ec22010-05-15 11:32:37 +0000427 Writer.AddTypeRef(T->getBaseType(), Record);
Douglas Gregore83b9562015-07-07 03:57:53 +0000428 Record.push_back(T->getTypeArgsAsWritten().size());
429 for (auto TypeArg : T->getTypeArgsAsWritten())
Douglas Gregore9d95f12015-07-07 03:57:35 +0000430 Writer.AddTypeRef(TypeArg, Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000431 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000432 for (const auto *I : T->quals())
433 Writer.AddDeclRef(I, Record);
Douglas Gregorab209d82015-07-07 03:58:42 +0000434 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000435 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000436}
437
Steve Narofffb4330f2009-06-17 22:40:22 +0000438void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000439ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000440 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000441 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000442}
443
Eli Friedman0dfb8892011-10-06 23:00:33 +0000444void
445ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
446 Writer.AddTypeRef(T->getValueType(), Record);
447 Code = TYPE_ATOMIC;
448}
449
Xiuli Pan9c14e282016-01-09 12:53:17 +0000450void
451ASTTypeWriter::VisitPipeType(const PipeType *T) {
452 Writer.AddTypeRef(T->getElementType(), Record);
453 Code = TYPE_PIPE;
454}
455
John McCall8f115c62009-10-16 21:56:05 +0000456namespace {
457
458class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000459 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000460 ASTWriter::RecordDataImpl &Record;
John McCall8f115c62009-10-16 21:56:05 +0000461
462public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000463 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
John McCall8f115c62009-10-16 21:56:05 +0000464 : Writer(Writer), Record(Record) { }
465
John McCall17001972009-10-18 01:05:36 +0000466#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000467#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000468 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000469#include "clang/AST/TypeLocNodes.def"
470
John McCall17001972009-10-18 01:05:36 +0000471 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
472 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000473};
474
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000475} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000476
John McCall17001972009-10-18 01:05:36 +0000477void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
478 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000479}
John McCall17001972009-10-18 01:05:36 +0000480void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000481 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
482 if (TL.needsExtraLocalData()) {
483 Record.push_back(TL.getWrittenTypeSpec());
484 Record.push_back(TL.getWrittenSignSpec());
485 Record.push_back(TL.getWrittenWidthSpec());
486 Record.push_back(TL.hasModeAttr());
487 }
John McCall8f115c62009-10-16 21:56:05 +0000488}
John McCall17001972009-10-18 01:05:36 +0000489void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
490 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000491}
John McCall17001972009-10-18 01:05:36 +0000492void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
493 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000494}
Reid Kleckner8a365022013-06-24 17:51:48 +0000495void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
496 // nothing to do
497}
Reid Kleckner0503a872013-12-05 01:23:43 +0000498void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
499 // nothing to do
500}
John McCall17001972009-10-18 01:05:36 +0000501void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
502 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000503}
John McCall17001972009-10-18 01:05:36 +0000504void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
505 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000506}
John McCall17001972009-10-18 01:05:36 +0000507void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
508 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000509}
John McCall17001972009-10-18 01:05:36 +0000510void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
511 Writer.AddSourceLocation(TL.getStarLoc(), Record);
Abramo Bagnara509357842011-03-05 14:42:21 +0000512 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000513}
John McCall17001972009-10-18 01:05:36 +0000514void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
515 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
516 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
517 Record.push_back(TL.getSizeExpr() ? 1 : 0);
518 if (TL.getSizeExpr())
519 Writer.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000520}
John McCall17001972009-10-18 01:05:36 +0000521void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
522 VisitArrayTypeLoc(TL);
523}
524void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
525 VisitArrayTypeLoc(TL);
526}
527void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
528 VisitArrayTypeLoc(TL);
529}
530void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
531 DependentSizedArrayTypeLoc TL) {
532 VisitArrayTypeLoc(TL);
533}
534void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
535 DependentSizedExtVectorTypeLoc TL) {
536 Writer.AddSourceLocation(TL.getNameLoc(), Record);
537}
538void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
539 Writer.AddSourceLocation(TL.getNameLoc(), Record);
540}
541void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
542 Writer.AddSourceLocation(TL.getNameLoc(), Record);
543}
544void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000545 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000546 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
547 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000548 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000549 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
550 Writer.AddDeclRef(TL.getParam(i), Record);
John McCall17001972009-10-18 01:05:36 +0000551}
552void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
553 VisitFunctionTypeLoc(TL);
554}
555void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
556 VisitFunctionTypeLoc(TL);
557}
John McCallb96ec562009-12-04 22:46:56 +0000558void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
559 Writer.AddSourceLocation(TL.getNameLoc(), Record);
560}
John McCall17001972009-10-18 01:05:36 +0000561void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getNameLoc(), Record);
563}
564void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000565 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
566 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
567 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000568}
569void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000570 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
571 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
572 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
573 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000574}
575void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
576 Writer.AddSourceLocation(TL.getNameLoc(), Record);
577}
Alexis Hunte852b102011-05-24 22:41:36 +0000578void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
579 Writer.AddSourceLocation(TL.getKWLoc(), Record);
580 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
581 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
582 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
583}
Richard Smith30482bc2011-02-20 03:19:35 +0000584void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
585 Writer.AddSourceLocation(TL.getNameLoc(), Record);
586}
John McCall17001972009-10-18 01:05:36 +0000587void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
588 Writer.AddSourceLocation(TL.getNameLoc(), Record);
589}
590void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
591 Writer.AddSourceLocation(TL.getNameLoc(), Record);
592}
John McCall81904512011-01-06 01:58:22 +0000593void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
594 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
595 if (TL.hasAttrOperand()) {
596 SourceRange range = TL.getAttrOperandParensRange();
597 Writer.AddSourceLocation(range.getBegin(), Record);
598 Writer.AddSourceLocation(range.getEnd(), Record);
599 }
600 if (TL.hasAttrExprOperand()) {
601 Expr *operand = TL.getAttrExprOperand();
602 Record.push_back(operand ? 1 : 0);
603 if (operand) Writer.AddStmt(operand);
604 } else if (TL.hasAttrEnumOperand()) {
605 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
606 }
607}
John McCall17001972009-10-18 01:05:36 +0000608void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
609 Writer.AddSourceLocation(TL.getNameLoc(), Record);
610}
John McCallcebee162009-10-18 09:09:24 +0000611void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
612 SubstTemplateTypeParmTypeLoc TL) {
613 Writer.AddSourceLocation(TL.getNameLoc(), Record);
614}
Douglas Gregorada4b792011-01-14 02:55:32 +0000615void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
616 SubstTemplateTypeParmPackTypeLoc TL) {
617 Writer.AddSourceLocation(TL.getNameLoc(), Record);
618}
John McCall17001972009-10-18 01:05:36 +0000619void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
620 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000621 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
John McCall0ad16662009-10-29 08:12:44 +0000622 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
623 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
624 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
625 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000626 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
627 TL.getArgLoc(i).getLocInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000628}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000629void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
630 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
631 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
632}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000633void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000634 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor844cb502011-03-01 18:12:44 +0000635 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000636}
John McCalle78aac42010-03-10 03:28:59 +0000637void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
638 Writer.AddSourceLocation(TL.getNameLoc(), Record);
639}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000640void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000641 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +0000642 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000643 Writer.AddSourceLocation(TL.getNameLoc(), Record);
644}
John McCallc392f372010-06-11 00:33:02 +0000645void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
646 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000647 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregora7a795b2011-03-01 20:11:18 +0000648 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
Abramo Bagnarae0a70b22012-02-06 22:45:07 +0000649 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000650 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
John McCallc392f372010-06-11 00:33:02 +0000651 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
652 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
653 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000654 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
655 TL.getArgLoc(I).getLocInfo(), Record);
John McCallc392f372010-06-11 00:33:02 +0000656}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000657void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
658 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
659}
John McCall17001972009-10-18 01:05:36 +0000660void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
661 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8b07ec22010-05-15 11:32:37 +0000662}
663void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
664 Record.push_back(TL.hasBaseTypeAsWritten());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000665 Writer.AddSourceLocation(TL.getTypeArgsLAngleLoc(), Record);
666 Writer.AddSourceLocation(TL.getTypeArgsRAngleLoc(), Record);
667 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
668 Writer.AddTypeSourceInfo(TL.getTypeArgTInfo(i), Record);
669 Writer.AddSourceLocation(TL.getProtocolLAngleLoc(), Record);
670 Writer.AddSourceLocation(TL.getProtocolRAngleLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000671 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
672 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
John McCall8f115c62009-10-16 21:56:05 +0000673}
John McCallfc93cf92009-10-22 22:37:11 +0000674void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
675 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCallfc93cf92009-10-22 22:37:11 +0000676}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000677void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
678 Writer.AddSourceLocation(TL.getKWLoc(), Record);
679 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
680 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
681}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000682void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
683 Writer.AddSourceLocation(TL.getKWLoc(), Record);
684}
John McCall8f115c62009-10-16 21:56:05 +0000685
Richard Smith01b2cb42014-07-26 06:37:51 +0000686void ASTWriter::WriteTypeAbbrevs() {
687 using namespace llvm;
688
689 BitCodeAbbrev *Abv;
690
691 // Abbreviation for TYPE_EXT_QUAL
692 Abv = new BitCodeAbbrev();
693 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
694 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
695 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
696 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
697
698 // Abbreviation for TYPE_FUNCTION_PROTO
699 Abv = new BitCodeAbbrev();
700 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
701 // FunctionType
702 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
703 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
704 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
705 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
706 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
707 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
708 // FunctionProtoType
709 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
710 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
711 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
712 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
713 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
714 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
715 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
716 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
717 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
718}
719
Chris Lattner19cea4e2009-04-22 05:57:30 +0000720//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000721// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000722//===----------------------------------------------------------------------===//
723
Chris Lattner28fa4e62009-04-26 22:26:21 +0000724static void EmitBlockID(unsigned ID, const char *Name,
725 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000726 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000727 Record.clear();
728 Record.push_back(ID);
729 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
730
731 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000732 if (!Name || Name[0] == 0)
733 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000734 Record.clear();
735 while (*Name)
736 Record.push_back(*Name++);
737 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
738}
739
740static void EmitRecordID(unsigned ID, const char *Name,
741 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000742 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000743 Record.clear();
744 Record.push_back(ID);
745 while (*Name)
746 Record.push_back(*Name++);
747 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000748}
749
750static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000751 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000752#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000753 RECORD(STMT_STOP);
754 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000755 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000756 RECORD(STMT_NULL);
757 RECORD(STMT_COMPOUND);
758 RECORD(STMT_CASE);
759 RECORD(STMT_DEFAULT);
760 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000761 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000762 RECORD(STMT_IF);
763 RECORD(STMT_SWITCH);
764 RECORD(STMT_WHILE);
765 RECORD(STMT_DO);
766 RECORD(STMT_FOR);
767 RECORD(STMT_GOTO);
768 RECORD(STMT_INDIRECT_GOTO);
769 RECORD(STMT_CONTINUE);
770 RECORD(STMT_BREAK);
771 RECORD(STMT_RETURN);
772 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000773 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000774 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000775 RECORD(EXPR_PREDEFINED);
776 RECORD(EXPR_DECL_REF);
777 RECORD(EXPR_INTEGER_LITERAL);
778 RECORD(EXPR_FLOATING_LITERAL);
779 RECORD(EXPR_IMAGINARY_LITERAL);
780 RECORD(EXPR_STRING_LITERAL);
781 RECORD(EXPR_CHARACTER_LITERAL);
782 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000783 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000784 RECORD(EXPR_UNARY_OPERATOR);
785 RECORD(EXPR_SIZEOF_ALIGN_OF);
786 RECORD(EXPR_ARRAY_SUBSCRIPT);
787 RECORD(EXPR_CALL);
788 RECORD(EXPR_MEMBER);
789 RECORD(EXPR_BINARY_OPERATOR);
790 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
791 RECORD(EXPR_CONDITIONAL_OPERATOR);
792 RECORD(EXPR_IMPLICIT_CAST);
793 RECORD(EXPR_CSTYLE_CAST);
794 RECORD(EXPR_COMPOUND_LITERAL);
795 RECORD(EXPR_EXT_VECTOR_ELEMENT);
796 RECORD(EXPR_INIT_LIST);
797 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000798 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000799 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000800 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000801 RECORD(EXPR_VA_ARG);
802 RECORD(EXPR_ADDR_LABEL);
803 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000804 RECORD(EXPR_CHOOSE);
805 RECORD(EXPR_GNU_NULL);
806 RECORD(EXPR_SHUFFLE_VECTOR);
807 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000808 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000809 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000810 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000811 RECORD(EXPR_OBJC_ARRAY_LITERAL);
812 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000813 RECORD(EXPR_OBJC_ENCODE);
814 RECORD(EXPR_OBJC_SELECTOR_EXPR);
815 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
816 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
817 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
818 RECORD(EXPR_OBJC_KVC_REF_EXPR);
819 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000820 RECORD(STMT_OBJC_FOR_COLLECTION);
821 RECORD(STMT_OBJC_CATCH);
822 RECORD(STMT_OBJC_FINALLY);
823 RECORD(STMT_OBJC_AT_TRY);
824 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
825 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000826 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000827 RECORD(STMT_CXX_CATCH);
828 RECORD(STMT_CXX_TRY);
829 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000830 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000831 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000832 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000833 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000834 RECORD(EXPR_CXX_STATIC_CAST);
835 RECORD(EXPR_CXX_DYNAMIC_CAST);
836 RECORD(EXPR_CXX_REINTERPRET_CAST);
837 RECORD(EXPR_CXX_CONST_CAST);
838 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000839 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000840 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000841 RECORD(EXPR_CXX_BOOL_LITERAL);
842 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000843 RECORD(EXPR_CXX_TYPEID_EXPR);
844 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000845 RECORD(EXPR_CXX_THIS);
846 RECORD(EXPR_CXX_THROW);
847 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000848 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000849 RECORD(EXPR_CXX_BIND_TEMPORARY);
850 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
851 RECORD(EXPR_CXX_NEW);
852 RECORD(EXPR_CXX_DELETE);
853 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
854 RECORD(EXPR_EXPR_WITH_CLEANUPS);
855 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
856 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
857 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
858 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
859 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000860 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000861 RECORD(EXPR_CXX_NOEXCEPT);
862 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000863 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
864 RECORD(EXPR_TYPE_TRAIT);
865 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000866 RECORD(EXPR_PACK_EXPANSION);
867 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000868 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000869 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000870 RECORD(EXPR_FUNCTION_PARM_PACK);
871 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000872 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000873 RECORD(EXPR_CXX_UUIDOF_EXPR);
874 RECORD(EXPR_CXX_UUIDOF_TYPE);
875 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000876#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000877}
Mike Stump11289f42009-09-09 15:08:12 +0000878
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000879void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000880 RecordData Record;
881 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000882
Sebastian Redl539c5062010-08-18 23:57:32 +0000883#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
884#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000886 // Control Block.
887 BLOCK(CONTROL_BLOCK);
888 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000889 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000890 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000891 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000892 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000893 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000894 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000895 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000896 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000897 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000898
899 BLOCK(OPTIONS_BLOCK);
900 RECORD(LANGUAGE_OPTIONS);
901 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000902 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000903 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000904 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000905 RECORD(PREPROCESSOR_OPTIONS);
906
Douglas Gregor108cb222012-10-19 00:45:00 +0000907 BLOCK(INPUT_FILES_BLOCK);
908 RECORD(INPUT_FILE);
909
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000910 // AST Top-Level Block.
911 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000912 RECORD(TYPE_OFFSET);
913 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000914 RECORD(IDENTIFIER_OFFSET);
915 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000916 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000917 RECORD(SPECIAL_TYPES);
918 RECORD(STATISTICS);
919 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000920 RECORD(SELECTOR_OFFSETS);
921 RECORD(METHOD_POOL);
922 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000923 RECORD(SOURCE_LOCATION_OFFSETS);
924 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000925 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000926 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000927 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000928 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000929 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000930 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000931 RECORD(SEMA_DECL_REFS);
932 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
933 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
934 RECORD(DECL_REPLACEMENTS);
935 RECORD(UPDATE_VISIBLE);
936 RECORD(DECL_UPDATE_OFFSETS);
937 RECORD(DECL_UPDATES);
938 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
939 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000940 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000941 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000942 RECORD(FP_PRAGMA_OPTIONS);
943 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000944 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000945 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000946 RECORD(MODULE_OFFSET_MAP);
947 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000948 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000949 RECORD(FILE_SORTED_DECLS);
950 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000951 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000952 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000953 RECORD(INTERESTING_IDENTIFIERS);
954 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000955 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000956 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000957 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
958 RECORD(CXX_CTOR_INITIALIZERS_OFFSETS);
959 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000960
Chris Lattner28fa4e62009-04-26 22:26:21 +0000961 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000962 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000963 RECORD(SM_SLOC_FILE_ENTRY);
964 RECORD(SM_SLOC_BUFFER_ENTRY);
965 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000966 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000967 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattner28fa4e62009-04-26 22:26:21 +0000969 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000970 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000971 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000972 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000973 RECORD(PP_MACRO_OBJECT_LIKE);
974 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000975 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000976
Richard Smithfa715652015-08-31 22:43:10 +0000977 // Submodule Block.
978 BLOCK(SUBMODULE_BLOCK);
979 RECORD(SUBMODULE_METADATA);
980 RECORD(SUBMODULE_DEFINITION);
981 RECORD(SUBMODULE_UMBRELLA_HEADER);
982 RECORD(SUBMODULE_HEADER);
983 RECORD(SUBMODULE_TOPHEADER);
984 RECORD(SUBMODULE_UMBRELLA_DIR);
985 RECORD(SUBMODULE_IMPORTS);
986 RECORD(SUBMODULE_EXPORTS);
987 RECORD(SUBMODULE_REQUIRES);
988 RECORD(SUBMODULE_EXCLUDED_HEADER);
989 RECORD(SUBMODULE_LINK_LIBRARY);
990 RECORD(SUBMODULE_CONFIG_MACRO);
991 RECORD(SUBMODULE_CONFLICT);
992 RECORD(SUBMODULE_PRIVATE_HEADER);
993 RECORD(SUBMODULE_TEXTUAL_HEADER);
994 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
995
996 // Comments Block.
997 BLOCK(COMMENTS_BLOCK);
998 RECORD(COMMENTS_RAW_COMMENT);
999
Douglas Gregor12bfa382009-10-17 00:13:19 +00001000 // Decls and Types block.
1001 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001002 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001003 RECORD(TYPE_COMPLEX);
1004 RECORD(TYPE_POINTER);
1005 RECORD(TYPE_BLOCK_POINTER);
1006 RECORD(TYPE_LVALUE_REFERENCE);
1007 RECORD(TYPE_RVALUE_REFERENCE);
1008 RECORD(TYPE_MEMBER_POINTER);
1009 RECORD(TYPE_CONSTANT_ARRAY);
1010 RECORD(TYPE_INCOMPLETE_ARRAY);
1011 RECORD(TYPE_VARIABLE_ARRAY);
1012 RECORD(TYPE_VECTOR);
1013 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001014 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001015 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001016 RECORD(TYPE_TYPEDEF);
1017 RECORD(TYPE_TYPEOF_EXPR);
1018 RECORD(TYPE_TYPEOF);
1019 RECORD(TYPE_RECORD);
1020 RECORD(TYPE_ENUM);
1021 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001022 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001023 RECORD(TYPE_DECLTYPE);
1024 RECORD(TYPE_ELABORATED);
1025 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1026 RECORD(TYPE_UNRESOLVED_USING);
1027 RECORD(TYPE_INJECTED_CLASS_NAME);
1028 RECORD(TYPE_OBJC_OBJECT);
1029 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1030 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1031 RECORD(TYPE_DEPENDENT_NAME);
1032 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1033 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1034 RECORD(TYPE_PAREN);
1035 RECORD(TYPE_PACK_EXPANSION);
1036 RECORD(TYPE_ATTRIBUTED);
1037 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001038 RECORD(TYPE_AUTO);
1039 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001040 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001041 RECORD(TYPE_DECAYED);
1042 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001043 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001044 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001045 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001046 RECORD(DECL_ENUM);
1047 RECORD(DECL_RECORD);
1048 RECORD(DECL_ENUM_CONSTANT);
1049 RECORD(DECL_FUNCTION);
1050 RECORD(DECL_OBJC_METHOD);
1051 RECORD(DECL_OBJC_INTERFACE);
1052 RECORD(DECL_OBJC_PROTOCOL);
1053 RECORD(DECL_OBJC_IVAR);
1054 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001055 RECORD(DECL_OBJC_CATEGORY);
1056 RECORD(DECL_OBJC_CATEGORY_IMPL);
1057 RECORD(DECL_OBJC_IMPLEMENTATION);
1058 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1059 RECORD(DECL_OBJC_PROPERTY);
1060 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001061 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001062 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001063 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001064 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001065 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001066 RECORD(DECL_FILE_SCOPE_ASM);
1067 RECORD(DECL_BLOCK);
1068 RECORD(DECL_CONTEXT_LEXICAL);
1069 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001070 RECORD(DECL_NAMESPACE);
1071 RECORD(DECL_NAMESPACE_ALIAS);
1072 RECORD(DECL_USING);
1073 RECORD(DECL_USING_SHADOW);
1074 RECORD(DECL_USING_DIRECTIVE);
1075 RECORD(DECL_UNRESOLVED_USING_VALUE);
1076 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1077 RECORD(DECL_LINKAGE_SPEC);
1078 RECORD(DECL_CXX_RECORD);
1079 RECORD(DECL_CXX_METHOD);
1080 RECORD(DECL_CXX_CONSTRUCTOR);
1081 RECORD(DECL_CXX_DESTRUCTOR);
1082 RECORD(DECL_CXX_CONVERSION);
1083 RECORD(DECL_ACCESS_SPEC);
1084 RECORD(DECL_FRIEND);
1085 RECORD(DECL_FRIEND_TEMPLATE);
1086 RECORD(DECL_CLASS_TEMPLATE);
1087 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1088 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001089 RECORD(DECL_VAR_TEMPLATE);
1090 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1091 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001092 RECORD(DECL_FUNCTION_TEMPLATE);
1093 RECORD(DECL_TEMPLATE_TYPE_PARM);
1094 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1095 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1096 RECORD(DECL_STATIC_ASSERT);
1097 RECORD(DECL_CXX_BASE_SPECIFIERS);
1098 RECORD(DECL_INDIRECTFIELD);
1099 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1100
Douglas Gregor03412ba2011-06-03 02:27:19 +00001101 // Statements and Exprs can occur in the Decls and Types block.
1102 AddStmtsExprs(Stream, Record);
1103
Douglas Gregor92a96f52011-02-08 21:58:10 +00001104 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001105 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001106 RECORD(PPD_MACRO_DEFINITION);
1107 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001108
1109 // Decls and Types block.
1110 BLOCK(EXTENSION_BLOCK);
1111 RECORD(EXTENSION_METADATA);
1112
Chris Lattner28fa4e62009-04-26 22:26:21 +00001113#undef RECORD
1114#undef BLOCK
1115 Stream.ExitBlock();
1116}
1117
Richard Smith54cc3c22014-12-11 20:50:24 +00001118/// \brief Prepares a path for being written to an AST file by converting it
1119/// to an absolute path and removing nested './'s.
1120///
1121/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001122static bool cleanPathForOutput(FileManager &FileMgr,
1123 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001124 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001125 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001126}
1127
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001128/// \brief Adjusts the given filename to only write out the portion of the
1129/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001130///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001131/// \param Filename the file name to adjust.
1132///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001133/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1134/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001135///
1136/// \returns either the original filename (if it needs no adjustment) or the
1137/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001138static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001139adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001140 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001141
Richard Smith7ed1bc92014-12-05 22:42:13 +00001142 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001143 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001145 // Verify that the filename and the system root have the same prefix.
1146 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001147 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1148 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001149 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001150
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001151 // We hit the end of the filename before we hit the end of the system root.
1152 if (!Filename[Pos])
1153 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001154
Richard Smith7ed1bc92014-12-05 22:42:13 +00001155 // If there's not a path separator at the end of the base directory nor
1156 // immediately after it, then this isn't within the base directory.
1157 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1158 if (!llvm::sys::path::is_separator(BaseDir.back()))
1159 return Filename;
1160 } else {
1161 // If the file name has a '/' at the current position, skip over the '/'.
1162 // We distinguish relative paths from absolute paths by the
1163 // absence of '/' at the beginning of relative paths.
1164 //
1165 // FIXME: This is wrong. We distinguish them by asking if the path is
1166 // absolute, which isn't the same thing. And there might be multiple '/'s
1167 // in a row. Use a better mechanism to indicate whether we have emitted an
1168 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001169 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001170 }
Mike Stump11289f42009-09-09 15:08:12 +00001171
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001172 return Filename + Pos;
1173}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001174
Ben Langmuir487ea142014-10-23 18:05:36 +00001175static ASTFileSignature getSignature() {
1176 while (1) {
1177 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1178 return S;
1179 // Rely on GetRandomNumber to eventually return non-zero...
1180 }
1181}
1182
Douglas Gregor112b9072012-10-18 05:31:06 +00001183/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001184uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1185 ASTContext &Context,
1186 StringRef isysroot,
1187 const std::string &OutputFile) {
1188 ASTFileSignature Signature = 0;
1189
Douglas Gregorbfbde532009-04-10 21:16:55 +00001190 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001191 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001192 RecordData Record;
1193
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001194 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001195 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001196 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1197 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1198 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1199 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1200 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1201 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001202 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001203 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1205 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001206 assert((!WritingModule || isysroot.empty()) &&
1207 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001208 {
1209 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1210 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1211 !isysroot.empty(), IncludeTimestamps,
1212 ASTHasCompilerErrors};
1213 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1214 getClangFullRepositoryVersion());
1215 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001216 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001217 // For implicit modules we output a signature that we can use to ensure
1218 // duplicate module builds don't collide in the cache as their output order
1219 // is non-deterministic.
1220 // FIXME: Remove this when output is deterministic.
1221 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001222 Signature = getSignature();
1223 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001224 Stream.EmitRecord(SIGNATURE, Record);
1225 }
1226
Richard Smith7ed1bc92014-12-05 22:42:13 +00001227 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001228 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001229 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1230 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1231 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001232 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001233 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1234 }
1235
Richard Smith7ed1bc92014-12-05 22:42:13 +00001236 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001237 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001238 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001239
1240 // If the home of the module is the current working directory, then we
1241 // want to pick up the cwd of the build process loading the module, not
1242 // our cwd, when we load this module.
1243 if (!PP.getHeaderSearchInfo()
1244 .getHeaderSearchOpts()
1245 .ModuleMapFileHomeIsCwd ||
1246 WritingModule->Directory->getName() != StringRef(".")) {
1247 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001248 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001249 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1250 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1251 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1252
Mehdi Amini57a41912015-09-10 01:46:39 +00001253 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001254 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1255 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001256
1257 // Write out all other paths relative to the base directory if possible.
1258 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1259 } else if (!isysroot.empty()) {
1260 // Write out paths relative to the sysroot if possible.
1261 BaseDirectory = isysroot;
1262 }
1263
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001264 // Module map file
1265 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001266 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001267
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001268 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1269
1270 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001271 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001272
1273 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001274 if (auto *AdditionalModMaps =
1275 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001276 Record.push_back(AdditionalModMaps->size());
1277 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001278 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001279 } else {
1280 Record.push_back(0);
1281 }
1282
1283 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001284 }
1285
Douglas Gregor112b9072012-10-18 05:31:06 +00001286 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001287 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001288 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001289 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001290
Richard Smith7f330cd2015-03-18 01:42:29 +00001291 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001292 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001293 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001294 continue;
1295
Richard Smith7f330cd2015-03-18 01:42:29 +00001296 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1297 AddSourceLocation(M->ImportLoc, Record);
1298 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001299 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001300 Record.push_back(M->Signature);
1301 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001302 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001303 Stream.EmitRecord(IMPORTS, Record);
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
Richard Smith0516b182015-09-08 19:40:14 +00001306 // Write the options block.
1307 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1308
Douglas Gregor112b9072012-10-18 05:31:06 +00001309 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001310 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001311 const LangOptions &LangOpts = Context.getLangOpts();
1312#define LANGOPT(Name, Bits, Default, Description) \
1313 Record.push_back(LangOpts.Name);
1314#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1315 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001316#include "clang/Basic/LangOptions.def"
1317#define SANITIZER(NAME, ID) \
1318 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001319#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001320
Ben Langmuircd98cb72015-06-23 18:20:18 +00001321 Record.push_back(LangOpts.ModuleFeatures.size());
1322 for (StringRef Feature : LangOpts.ModuleFeatures)
1323 AddString(Feature, Record);
1324
Douglas Gregor112b9072012-10-18 05:31:06 +00001325 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1326 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001327
1328 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001329
1330 // Comment options.
1331 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001332 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1333 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001334 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001335 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001336
Samuel Antaoee8fb302016-01-06 13:42:12 +00001337 // OpenMP offloading options.
1338 Record.push_back(LangOpts.OMPTargetTriples.size());
1339 for (auto &T : LangOpts.OMPTargetTriples)
1340 AddString(T.getTriple(), Record);
1341
1342 AddString(LangOpts.OMPHostIRFile, Record);
1343
Douglas Gregor112b9072012-10-18 05:31:06 +00001344 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1345
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001346 // Target options.
1347 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001348 const TargetInfo &Target = Context.getTargetInfo();
1349 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001350 AddString(TargetOpts.Triple, Record);
1351 AddString(TargetOpts.CPU, Record);
1352 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001353 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1354 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1355 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1356 }
1357 Record.push_back(TargetOpts.Features.size());
1358 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1359 AddString(TargetOpts.Features[I], Record);
1360 }
1361 Stream.EmitRecord(TARGET_OPTIONS, Record);
1362
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001363 // Diagnostic options.
1364 Record.clear();
1365 const DiagnosticOptions &DiagOpts
1366 = Context.getDiagnostics().getDiagnosticOptions();
1367#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1368#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1369 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1370#include "clang/Basic/DiagnosticOptions.def"
1371 Record.push_back(DiagOpts.Warnings.size());
1372 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1373 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001374 Record.push_back(DiagOpts.Remarks.size());
1375 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1376 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001377 // Note: we don't serialize the log or serialization file names, because they
1378 // are generally transient files and will almost always be overridden.
1379 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1380
Douglas Gregorc6317db2012-10-24 15:49:58 +00001381 // File system options.
1382 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001383 const FileSystemOptions &FSOpts =
1384 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001385 AddString(FSOpts.WorkingDir, Record);
1386 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1387
Douglas Gregor2d302362012-10-24 16:50:34 +00001388 // Header search options.
1389 Record.clear();
1390 const HeaderSearchOptions &HSOpts
1391 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1392 AddString(HSOpts.Sysroot, Record);
1393
1394 // Include entries.
1395 Record.push_back(HSOpts.UserEntries.size());
1396 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1397 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1398 AddString(Entry.Path, Record);
1399 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001400 Record.push_back(Entry.IsFramework);
1401 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001402 }
1403
1404 // System header prefixes.
1405 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1406 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1407 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1408 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1409 }
1410
1411 AddString(HSOpts.ResourceDir, Record);
1412 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001413 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001414 Record.push_back(HSOpts.DisableModuleHash);
1415 Record.push_back(HSOpts.UseBuiltinIncludes);
1416 Record.push_back(HSOpts.UseStandardSystemIncludes);
1417 Record.push_back(HSOpts.UseStandardCXXIncludes);
1418 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001419 // Write out the specific module cache path that contains the module files.
1420 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001421 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1422
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001423 // Preprocessor options.
1424 Record.clear();
1425 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1426
1427 // Macro definitions.
1428 Record.push_back(PPOpts.Macros.size());
1429 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1430 AddString(PPOpts.Macros[I].first, Record);
1431 Record.push_back(PPOpts.Macros[I].second);
1432 }
1433
1434 // Includes
1435 Record.push_back(PPOpts.Includes.size());
1436 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1437 AddString(PPOpts.Includes[I], Record);
1438
1439 // Macro includes
1440 Record.push_back(PPOpts.MacroIncludes.size());
1441 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1442 AddString(PPOpts.MacroIncludes[I], Record);
1443
Douglas Gregorb6368752012-10-24 23:41:50 +00001444 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001445 // Detailed record is important since it is used for the module cache hash.
1446 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001447 AddString(PPOpts.ImplicitPCHInclude, Record);
1448 AddString(PPOpts.ImplicitPTHInclude, Record);
1449 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1450 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1451
Richard Smith0516b182015-09-08 19:40:14 +00001452 // Leave the options block.
1453 Stream.ExitBlock();
1454
Douglas Gregora3b20262011-05-06 21:43:30 +00001455 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001456 SourceManager &SM = Context.getSourceManager();
1457 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001458 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001459 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1460 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001461 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1462 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1463
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001464 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001465 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001466 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001467 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001468 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001469
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001470 Record.clear();
1471 Record.push_back(SM.getMainFileID().getOpaqueValue());
1472 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1473
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001474 // Original PCH directory
1475 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001476 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001477 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1478 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1479 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1480
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001481 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001482
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001483 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001484 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1485
Mehdi Amini57a41912015-09-10 01:46:39 +00001486 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001487 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1488 }
1489
Douglas Gregor49491f72013-03-15 22:15:07 +00001490 WriteInputFiles(Context.SourceMgr,
1491 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001492 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001493 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001494 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001495}
1496
Douglas Gregor49491f72013-03-15 22:15:07 +00001497namespace {
1498 /// \brief An input file.
1499 struct InputFileEntry {
1500 const FileEntry *File;
1501 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001502 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001503 bool BufferOverridden;
1504 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001505} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001506
1507void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1508 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001509 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001510 using namespace llvm;
1511 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001512
Douglas Gregor72be3902012-10-19 00:38:02 +00001513 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001514 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001515 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001516 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001517 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1518 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001519 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001520 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001521 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1522 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1523
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001524 // Get all ContentCache objects for files, sorted by whether the file is a
1525 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001526 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001527 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1528 // Get this source location entry.
1529 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001530 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001531
1532 // We only care about file entries that were not overridden.
1533 if (!SLoc->isFile())
1534 continue;
1535 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001536 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001537 continue;
1538
Douglas Gregor49491f72013-03-15 22:15:07 +00001539 InputFileEntry Entry;
1540 Entry.File = Cache->OrigEntry;
1541 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001542 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001543 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001544 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001545 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001546 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001547 SortedFiles.push_front(Entry);
1548 }
1549
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001550 unsigned UserFilesNum = 0;
1551 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001552 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001553 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001554 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001555 if (InputFileID != 0)
1556 continue; // already recorded this file.
1557
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001558 // Record this entry's offset.
1559 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001560
1561 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001562
Douglas Gregor49491f72013-03-15 22:15:07 +00001563 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001564 ++UserFilesNum;
1565
Douglas Gregor72be3902012-10-19 00:38:02 +00001566 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001567 // And whether this file was overridden.
1568 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001569 INPUT_FILE,
1570 InputFileOffsets.size(),
1571 (uint64_t)Entry.File->getSize(),
1572 (uint64_t)getTimestampForOutput(Entry.File),
1573 Entry.BufferOverridden,
1574 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001575
Richard Smith7ed1bc92014-12-05 22:42:13 +00001576 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1577 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001578
Douglas Gregor112b9072012-10-18 05:31:06 +00001579 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001580
1581 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001582 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001583 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1584 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001585 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1586 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001587 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1588 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1589
1590 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001591 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1592 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001593 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001594}
1595
Douglas Gregora7f71a92009-04-10 03:52:48 +00001596//===----------------------------------------------------------------------===//
1597// Source Manager Serialization
1598//===----------------------------------------------------------------------===//
1599
1600/// \brief Create an abbreviation for the SLocEntry that refers to a
1601/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001602static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001603 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001604
1605 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001606 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001611 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001612 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001614 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001616 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001617}
1618
1619/// \brief Create an abbreviation for the SLocEntry that refers to a
1620/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001621static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001622 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001623
1624 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001625 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1628 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1629 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1630 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001631 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001632}
1633
1634/// \brief Create an abbreviation for the SLocEntry that refers to a
1635/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001636static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1637 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001638 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001639
1640 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001641 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1642 : SM_SLOC_BUFFER_BLOB));
1643 if (Compressed)
1644 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001646 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001647}
1648
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001649/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1650/// expansion.
1651static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001652 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001653
1654 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001655 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1657 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001661 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001662}
1663
Douglas Gregor09b69892011-02-10 17:09:37 +00001664namespace {
1665 // Trait used for the on-disk hash table of header search information.
1666 class HeaderFileInfoTrait {
1667 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001668 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001669
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001670 // Keep track of the framework names we've used during serialization.
1671 SmallVector<char, 128> FrameworkStringData;
1672 llvm::StringMap<unsigned> FrameworkNameOffset;
1673
Douglas Gregor09b69892011-02-10 17:09:37 +00001674 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001675 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1676 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001677
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001678 struct key_type {
1679 const FileEntry *FE;
1680 const char *Filename;
1681 };
1682 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001683
1684 typedef HeaderFileInfo data_type;
1685 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001686 typedef unsigned hash_value_type;
1687 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001688
Richard Smithe75ee0f2015-08-17 07:13:32 +00001689 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001690 // The hash is based only on size/time of the file, so that the reader can
1691 // match even when symlinking or excess path elements ("foo/../", "../")
1692 // change the form of the name. However, complete path is still the key.
1693 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001694 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001695 }
1696
1697 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001698 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001699 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001700 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001701 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001702 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001703 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001704 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1705 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1706 DataLen += 4;
1707 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001708 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001709 }
1710
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001711 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001712 using namespace llvm::support;
1713 endian::Writer<little> LE(Out);
1714 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001715 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001716 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001717 KeyLen -= 8;
1718 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001719 }
1720
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001721 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001722 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001723 using namespace llvm::support;
1724 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001725 uint64_t Start = Out.tell(); (void)Start;
1726
Richard Smith386bb072015-08-18 23:42:23 +00001727 unsigned char Flags = (Data.isImport << 4)
1728 | (Data.isPragmaOnce << 3)
1729 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001730 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001731 LE.write<uint8_t>(Flags);
1732 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001733
1734 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001735 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001736 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001737 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001738
1739 unsigned Offset = 0;
1740 if (!Data.Framework.empty()) {
1741 // If this header refers into a framework, save the framework name.
1742 llvm::StringMap<unsigned>::iterator Pos
1743 = FrameworkNameOffset.find(Data.Framework);
1744 if (Pos == FrameworkNameOffset.end()) {
1745 Offset = FrameworkStringData.size() + 1;
1746 FrameworkStringData.append(Data.Framework.begin(),
1747 Data.Framework.end());
1748 FrameworkStringData.push_back(0);
1749
1750 FrameworkNameOffset[Data.Framework] = Offset;
1751 } else
1752 Offset = Pos->second;
1753 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001754 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001755
Richard Smith386bb072015-08-18 23:42:23 +00001756 // FIXME: If the header is excluded, we should write out some
1757 // record of that fact.
1758 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1759 if (uint32_t ModID =
1760 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1761 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1762 assert((Value >> 2) == ModID && "overflow in header module info");
1763 LE.write<uint32_t>(Value);
1764 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001765 }
1766
Douglas Gregor09b69892011-02-10 17:09:37 +00001767 assert(Out.tell() - Start == DataLen && "Wrong data length");
1768 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001769
1770 const char *strings_begin() const { return FrameworkStringData.begin(); }
1771 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001772 };
1773} // end anonymous namespace
1774
1775/// \brief Write the header search block for the list of files that
1776///
1777/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001778void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001779 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001780 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1781
1782 if (FilesByUID.size() > HS.header_file_size())
1783 FilesByUID.resize(HS.header_file_size());
1784
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001785 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001786 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001787 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001788 unsigned NumHeaderSearchEntries = 0;
1789 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1790 const FileEntry *File = FilesByUID[UID];
1791 if (!File)
1792 continue;
1793
Richard Smith386bb072015-08-18 23:42:23 +00001794 // Get the file info. This will load info from the external source if
1795 // necessary. Skip emitting this file if we have no information on it
1796 // as a header file (in which case HFI will be null) or if it hasn't
1797 // changed since it was loaded. Also skip it if it's for a modular header
1798 // from a different module; in that case, we rely on the module(s)
1799 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001800 const HeaderFileInfo *HFI =
1801 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1802 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001803 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001804
Richard Smith7ed1bc92014-12-05 22:42:13 +00001805 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001806 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001807 SmallString<128> FilenameTmp(Filename);
1808 if (PreparePathForOutput(FilenameTmp)) {
1809 // If we performed any translation on the file name at all, we need to
1810 // save this string, since the generator will refer to it later.
1811 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001812 SavedStrings.push_back(Filename);
1813 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001814
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001815 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001816 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001817 ++NumHeaderSearchEntries;
1818 }
1819
1820 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001821 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001822 uint32_t BucketOffset;
1823 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001824 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001825 llvm::raw_svector_ostream Out(TableData);
1826 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001827 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001828 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1829 }
1830
1831 // Create a blob abbreviation
1832 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001833
1834 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001835 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1836 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1840 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1841
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001842 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001843 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1844 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001845 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001846 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001847
1848 // Free all of the strings we had to duplicate.
1849 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001850 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001851}
1852
Douglas Gregora7f71a92009-04-10 03:52:48 +00001853/// \brief Writes the block containing the serialized form of the
1854/// source manager.
1855///
1856/// TODO: We should probably use an on-disk hash table (stored in a
1857/// blob), indexed based on the file name, so that we only create
1858/// entries for files that we actually need. In the common case (no
1859/// errors), we probably won't have to create file entries for any of
1860/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001861void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001862 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001863 RecordData Record;
1864
Chris Lattner0910e3b2009-04-10 17:16:57 +00001865 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001866 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001867
1868 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001869 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1870 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001871 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1872 unsigned SLocBufferBlobCompressedAbbrv =
1873 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001874 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001875
Douglas Gregor258ae542009-04-27 06:38:32 +00001876 // Write out the source location entry table. We skip the first
1877 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001878 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001879 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001880 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1881 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001882 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001883 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001884 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001885 FileID FID = FileID::get(I);
1886 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001887
Douglas Gregor258ae542009-04-27 06:38:32 +00001888 // Record the offset of this source-location entry.
1889 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1890
1891 // Figure out which record code to use.
1892 unsigned Code;
1893 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001894 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1895 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001896 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001897 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001898 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001899 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001900 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001901 Record.clear();
1902 Record.push_back(Code);
1903
Douglas Gregor925296b2011-07-19 16:10:42 +00001904 // Starting offset of this entry within this module, so skip the dummy.
1905 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001906 if (SLoc->isFile()) {
1907 const SrcMgr::FileInfo &File = SLoc->getFile();
1908 Record.push_back(File.getIncludeLoc().getRawEncoding());
1909 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1910 Record.push_back(File.hasLineDirectives());
1911
1912 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001913 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001914 if (Content->OrigEntry) {
1915 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001916 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001917
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001918 // The source location entry is a file. Emit input file ID.
1919 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1920 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001922 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001923
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001924 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001925 if (FDI != FileDeclIDs.end()) {
1926 Record.push_back(FDI->second->FirstDeclIndex);
1927 Record.push_back(FDI->second->DeclIDs.size());
1928 } else {
1929 Record.push_back(0);
1930 Record.push_back(0);
1931 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001932
1933 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1934
Richard Smithaada85c2016-02-06 02:06:43 +00001935 if (Content->BufferOverridden || Content->IsTransient)
1936 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001937 } else {
1938 // The source location entry is a buffer. The blob associated
1939 // with this entry contains the contents of the buffer.
1940
1941 // We add one to the size so that we capture the trailing NULL
1942 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1943 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001944 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001945 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001946 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001947 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001948 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001949 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001950
Douglas Gregor925296b2011-07-19 16:10:42 +00001951 if (strcmp(Name, "<built-in>") == 0) {
1952 PreloadSLocs.push_back(SLocEntryOffsets.size());
1953 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001954 }
Richard Smithaada85c2016-02-06 02:06:43 +00001955
1956 if (EmitBlob) {
1957 // Include the implicit terminating null character in the on-disk buffer
1958 // if we're writing it uncompressed.
1959 const llvm::MemoryBuffer *Buffer =
1960 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1961 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
1962
1963 // Compress the buffer if possible. We expect that almost all PCM
1964 // consumers will not want its contents.
1965 SmallString<0> CompressedBuffer;
1966 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
1967 llvm::zlib::StatusOK) {
1968 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1969 Blob.size() - 1};
1970 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1971 CompressedBuffer);
1972 } else {
1973 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
1974 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1975 }
1976 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001977 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001978 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001979 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +00001980 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1981 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
Argyrios Kyrtzidisa1d943a2011-08-17 00:31:14 +00001982 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1983 : Expansion.getExpansionLocEnd().getRawEncoding());
Douglas Gregor258ae542009-04-27 06:38:32 +00001984
1985 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001986 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001987 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001988 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001989 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001990 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001991 }
1992 }
1993
Douglas Gregor8f45df52009-04-16 22:23:12 +00001994 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001995
1996 if (SLocEntryOffsets.empty())
1997 return;
1998
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001999 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002000 // table is used for lazily loading source-location information.
2001 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002002
2003 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002004 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002005 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002006 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002007 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2008 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002009 {
2010 RecordData::value_type Record[] = {
2011 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2012 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2013 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2014 bytes(SLocEntryOffsets));
2015 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002016 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002017 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002018 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002019
2020 // Write the line table. It depends on remapping working, so it must come
2021 // after the source location offsets.
2022 if (SourceMgr.hasLineTable()) {
2023 LineTableInfo &LineTable = SourceMgr.getLineTable();
2024
2025 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002026
2027 // Emit the needed file names.
2028 llvm::DenseMap<int, int> FilenameMap;
2029 for (const auto &L : LineTable) {
2030 if (L.first.ID < 0)
2031 continue;
2032 for (auto &LE : L.second) {
2033 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2034 FilenameMap.size())).second)
2035 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2036 }
2037 }
2038 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002039
2040 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002041 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002042 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002043 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002044 continue;
2045
2046 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002047 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002048
2049 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002050 Record.push_back(L.second.size());
2051 for (const auto &LE : L.second) {
2052 Record.push_back(LE.FileOffset);
2053 Record.push_back(LE.LineNo);
2054 Record.push_back(FilenameMap[LE.FilenameID]);
2055 Record.push_back((unsigned)LE.FileKind);
2056 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002057 }
2058 }
Richard Smith63078492015-09-01 07:41:55 +00002059
Douglas Gregor925296b2011-07-19 16:10:42 +00002060 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2061 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002062}
2063
Douglas Gregorc5046832009-04-27 18:38:38 +00002064//===----------------------------------------------------------------------===//
2065// Preprocessor Serialization
2066//===----------------------------------------------------------------------===//
2067
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002068static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2069 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002070 if (MacroInfo *MI = MD->getMacroInfo())
2071 if (MI->isBuiltinMacro())
2072 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002073
2074 if (IsModule) {
2075 SourceLocation Loc = MD->getLocation();
2076 if (Loc.isInvalid())
2077 return true;
2078 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2079 return true;
2080 }
2081
2082 return false;
2083}
2084
Chris Lattnereeffaef2009-04-10 17:15:23 +00002085/// \brief Writes the block containing the serialized form of the
2086/// preprocessor.
2087///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002088void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002089 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2090 if (PPRec)
2091 WritePreprocessorDetail(*PPRec);
2092
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002093 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002094 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002095
Chris Lattner0af3ba12009-04-13 01:29:17 +00002096 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2097 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002098 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002099 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002100 }
2101
2102 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002103 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002104
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002105 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002106 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002107 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002108 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002109
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002110 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002111 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002112
Richard Smithee977932015-05-01 21:22:17 +00002113 // Construct the list of identifiers with macro directives that need to be
2114 // serialized.
2115 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2116 for (auto &Id : PP.getIdentifierTable())
2117 if (Id.second->hadMacroDefinition() &&
2118 (!Id.second->isFromAST() ||
2119 Id.second->hasChangedSinceDeserialization()))
2120 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002121 // Sort the set of macro definitions that need to be serialized by the
2122 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002123 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2124 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002125
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002126 // Emit the macro directives as a list and associate the offset with the
2127 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002128 for (const IdentifierInfo *Name : MacroIdentifiers) {
2129 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002130 auto StartOffset = Stream.GetCurrentBitNo();
2131
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002132 // Emit the macro directives in reverse source order.
2133 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002134 // Once we hit an ignored macro, we're done: the rest of the chain
2135 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002136 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002137 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002138
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002139 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002140 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002141 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002142 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002143 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002144 Record.push_back(VisMD->isPublic());
2145 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002146 }
Richard Smithd7329392015-04-21 21:46:32 +00002147
Richard Smithb8b2ed62015-04-23 18:18:26 +00002148 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002149 bool EmittedModuleMacros = false;
Richard Smithb8b2ed62015-04-23 18:18:26 +00002150 if (IsModule) {
2151 auto Leafs = PP.getLeafModuleMacros(Name);
2152 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2153 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2154 while (!Worklist.empty()) {
2155 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002156
Richard Smithb8b2ed62015-04-23 18:18:26 +00002157 // Emit a record indicating this submodule exports this macro.
2158 ModuleMacroRecord.push_back(
2159 getSubmoduleID(Macro->getOwningModule()));
Richard Smithee977932015-05-01 21:22:17 +00002160 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
Richard Smithb8b2ed62015-04-23 18:18:26 +00002161 for (auto *M : Macro->overrides())
2162 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002163
Richard Smithb8b2ed62015-04-23 18:18:26 +00002164 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2165 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002166
Richard Smithb8b2ed62015-04-23 18:18:26 +00002167 // Enqueue overridden macros once we've visited all their ancestors.
2168 for (auto *M : Macro->overrides())
2169 if (++Visits[M] == M->getNumOverridingMacros())
2170 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002171
2172 EmittedModuleMacros = true;
Richard Smithd7329392015-04-21 21:46:32 +00002173 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002174 }
Richard Smithd7329392015-04-21 21:46:32 +00002175
Richard Smithee977932015-05-01 21:22:17 +00002176 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002177 continue;
2178
Richard Smithd7329392015-04-21 21:46:32 +00002179 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002180 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2181 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002182 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002183
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002184 /// \brief Offsets of each of the macros into the bitstream, indexed by
2185 /// the local macro ID
2186 ///
2187 /// For each identifier that is associated with a macro, this map
2188 /// provides the offset into the bitstream where that macro is
2189 /// defined.
2190 std::vector<uint32_t> MacroOffsets;
2191
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002192 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2193 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2194 MacroInfo *MI = MacroInfosToEmit[I].MI;
2195 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002196
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002197 if (ID < FirstMacroID) {
2198 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2199 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002200 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002201
2202 // Record the local offset of this macro.
2203 unsigned Index = ID - FirstMacroID;
2204 if (Index == MacroOffsets.size())
2205 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2206 else {
2207 if (Index > MacroOffsets.size())
2208 MacroOffsets.resize(Index + 1);
2209
2210 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2211 }
2212
2213 AddIdentifierRef(Name, Record);
2214 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2215 AddSourceLocation(MI->getDefinitionLoc(), Record);
2216 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2217 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002218 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002219 unsigned Code;
2220 if (MI->isObjectLike()) {
2221 Code = PP_MACRO_OBJECT_LIKE;
2222 } else {
2223 Code = PP_MACRO_FUNCTION_LIKE;
2224
2225 Record.push_back(MI->isC99Varargs());
2226 Record.push_back(MI->isGNUVarargs());
2227 Record.push_back(MI->hasCommaPasting());
2228 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002229 for (const IdentifierInfo *Arg : MI->args())
2230 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002231 }
2232
2233 // If we have a detailed preprocessing record, record the macro definition
2234 // ID that corresponds to this macro.
2235 if (PPRec)
2236 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2237
2238 Stream.EmitRecord(Code, Record);
2239 Record.clear();
2240
2241 // Emit the tokens array.
2242 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2243 // Note that we know that the preprocessor does not have any annotation
2244 // tokens in it because they are created by the parser, and thus can't
2245 // be in a macro definition.
2246 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002247 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002248 Stream.EmitRecord(PP_TOKEN, Record);
2249 Record.clear();
2250 }
2251 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002252 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002253
Douglas Gregor92a96f52011-02-08 21:58:10 +00002254 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002255
2256 // Write the offsets table for macro IDs.
2257 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002258
Richard Smith13090a22015-04-10 02:02:24 +00002259 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002260 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2262 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2263 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2264
2265 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002266 {
2267 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2268 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2269 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2270 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002271}
2272
2273void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002274 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002275 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002276
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002277 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002278
Douglas Gregor92a96f52011-02-08 21:58:10 +00002279 // Enter the preprocessor block.
2280 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002281
Douglas Gregoraae92242010-03-19 21:51:54 +00002282 // If the preprocessor has a preprocessing record, emit it.
2283 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002284 using namespace llvm;
2285
2286 // Set up the abbreviation for
2287 unsigned InclusionAbbrev = 0;
2288 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002289 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002290 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002291 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2292 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2293 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002294 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002295 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2296 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2297 }
2298
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002299 unsigned FirstPreprocessorEntityID
2300 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2301 + NUM_PREDEF_PP_ENTITY_IDS;
2302 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002303 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002304 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2305 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002306 E != EEnd;
2307 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002308 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002309
Richard Smith66a81862015-05-04 02:25:31 +00002310 PreprocessedEntityOffsets.push_back(
2311 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002312
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002313 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002314 // Record this macro definition's ID.
2315 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002316
Douglas Gregor92a96f52011-02-08 21:58:10 +00002317 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002318 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2319 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002320 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002321
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002322 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002323 Record.push_back(ME->isBuiltinMacro());
2324 if (ME->isBuiltinMacro())
2325 AddIdentifierRef(ME->getName(), Record);
2326 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002327 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002328 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002329 continue;
2330 }
2331
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002332 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002333 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002334 Record.push_back(ID->getFileName().size());
2335 Record.push_back(ID->wasInQuotes());
2336 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002337 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002338 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002339 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002340 // Check that the FileEntry is not null because it was not resolved and
2341 // we create a PCH even with compiler errors.
2342 if (ID->getFile())
2343 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002344 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002345 continue;
2346 }
2347
2348 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2349 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002350 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002351
Douglas Gregoraae92242010-03-19 21:51:54 +00002352 // Write the offsets table for the preprocessing record.
2353 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002354 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2355
Douglas Gregoraae92242010-03-19 21:51:54 +00002356 // Write the offsets table for identifier IDs.
2357 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002358
2359 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002360 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002361 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002362 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002363 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002364
Mehdi Amini57a41912015-09-10 01:46:39 +00002365 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2366 FirstPreprocessorEntityID -
2367 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002368 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002369 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002370 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002371}
2372
Richard Smith386bb072015-08-18 23:42:23 +00002373unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002374 if (!Mod)
2375 return 0;
2376
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002377 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2378 if (Known != SubmoduleIDs.end())
2379 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002380
2381 if (Mod->getTopLevelModule() != WritingModule)
2382 return 0;
2383
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002384 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2385}
2386
Richard Smith386bb072015-08-18 23:42:23 +00002387unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2388 // FIXME: This can easily happen, if we have a reference to a submodule that
2389 // did not result in us loading a module file for that submodule. For
2390 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2391 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2392 assert((ID || !Mod) &&
2393 "asked for module ID for non-local, non-imported module");
2394 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002395}
2396
Douglas Gregor253eefe2011-12-01 00:59:36 +00002397/// \brief Compute the number of modules within the given tree (including the
2398/// given module).
2399static unsigned getNumberOfModules(Module *Mod) {
2400 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002401 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002402 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002403 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002404
2405 return ChildModules + 1;
2406}
2407
Douglas Gregorde3ef502011-11-30 23:21:26 +00002408void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002409 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002410 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002411
2412 // Write the abbreviations needed for the submodules block.
2413 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002414
2415 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor69021972011-11-30 17:33:56 +00002416 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002417 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2422 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2428 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2429
2430 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002431 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002432 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2433 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2434
2435 Abbrev = new BitCodeAbbrev();
2436 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2437 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2438 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002439
2440 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002441 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2443 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2444
2445 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002446 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2447 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2448 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2449
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002450 Abbrev = new BitCodeAbbrev();
2451 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002454 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2455
Douglas Gregor59527662012-10-15 06:28:11 +00002456 Abbrev = new BitCodeAbbrev();
2457 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2459 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2460
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002461 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002462 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2464 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2465
2466 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002467 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2469 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2470
2471 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002472 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2473 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2474 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2475
2476 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002477 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2478 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2479 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2480 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2481
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002482 Abbrev = new BitCodeAbbrev();
2483 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2485 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2486
Douglas Gregorfb912652013-03-20 21:10:35 +00002487 Abbrev = new BitCodeAbbrev();
2488 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2490 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2491 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2492
Douglas Gregor253eefe2011-12-01 00:59:36 +00002493 // Write the submodule metadata block.
Mehdi Amini57a41912015-09-10 01:46:39 +00002494 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2495 FirstSubmoduleID -
2496 NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002497 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2498
Douglas Gregor69021972011-11-30 17:33:56 +00002499 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002500 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002501 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002502 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002503 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002504 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002505 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002506
2507 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002508 if (Mod->Parent) {
2509 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002510 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002511 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002512
2513 // Emit the definition of the block.
2514 {
2515 RecordData::value_type Record[] = {
2516 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2517 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2518 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2519 Mod->ConfigMacrosExhaustive};
2520 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2521 }
2522
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002523 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002524 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002525 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002526 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002527 }
2528
Douglas Gregor69021972011-11-30 17:33:56 +00002529 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002530 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002531 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002532 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2533 UmbrellaHeader.NameAsWritten);
2534 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002535 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2536 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002537 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002538 }
Richard Smith306d8922014-10-22 23:50:56 +00002539
Douglas Gregor69021972011-11-30 17:33:56 +00002540 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002541 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002542 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002543 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002544 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002545 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002546 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2547 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2548 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002549 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002550 Module::HK_PrivateTextual},
2551 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002552 };
2553 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002554 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002555 for (auto &H : Mod->Headers[HL.HeaderKind])
2556 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2557 }
2558
2559 // Emit the top headers.
2560 {
2561 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002562 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002563 for (auto *H : TopHeaders)
2564 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002565 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002566
2567 // Emit the imports.
2568 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002569 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002570 for (auto *I : Mod->Imports)
2571 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002572 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2573 }
2574
Douglas Gregor24bb9232011-12-02 18:58:38 +00002575 // Emit the exports.
2576 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002577 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002578 for (const auto &E : Mod->Exports) {
2579 // FIXME: This may fail; we don't require that all exported modules
2580 // are local or imported.
2581 Record.push_back(getSubmoduleID(E.getPointer()));
2582 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002583 }
2584 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2585 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002586
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002587 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2588 // Might be unnecessary as use declarations are only used to build the
2589 // module itself.
2590
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002591 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002592 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002593 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2594 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002595 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002596 }
2597
Douglas Gregorfb912652013-03-20 21:10:35 +00002598 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002599 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002600 // FIXME: This may fail; we don't require that all conflicting modules
2601 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002602 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2603 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002604 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002605 }
2606
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002607 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002608 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002609 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002610 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002611 }
2612
Douglas Gregor69021972011-11-30 17:33:56 +00002613 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002614 for (auto *M : Mod->submodules())
2615 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002616 }
2617
2618 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002619
Richard Smith23d8d032015-05-14 00:45:20 +00002620 assert((NextSubmoduleID - FirstSubmoduleID ==
2621 getNumberOfModules(WritingModule)) &&
2622 "Wrong # of submodules; found a reference to a non-local, "
2623 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002624}
2625
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002626serialization::SubmoduleID
2627ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002628 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002629 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002630
2631 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002632 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002633 Module *OwningMod
2634 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002635 if (!OwningMod)
2636 return 0;
2637
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002638 // Check whether this submodule is part of our own module.
2639 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002640 return 0;
2641
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002642 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002643}
2644
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002645void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2646 bool isModule) {
2647 // Make sure set diagnostic pragmas don't affect the translation unit that
2648 // imports the module.
2649 // FIXME: Make diagnostic pragma sections work properly with modules.
2650 if (isModule)
2651 return;
2652
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002653 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2654 DiagStateIDMap;
2655 unsigned CurrID = 0;
2656 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002657 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002658 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002659 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2660 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002661 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002662 if (point.Loc.isInvalid())
2663 continue;
2664
2665 Record.push_back(point.Loc.getRawEncoding());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002666 unsigned &DiagStateID = DiagStateIDMap[point.State];
2667 Record.push_back(DiagStateID);
2668
2669 if (DiagStateID == 0) {
2670 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002671 for (const auto &I : *(point.State)) {
2672 if (I.second.isPragma()) {
2673 Record.push_back(I.first);
2674 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002675 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002676 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002677 Record.push_back(-1); // mark the end of the diag/map pairs for this
2678 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002679 }
2680 }
2681
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002682 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002683 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002684}
2685
Richard Smithc2bb8182015-03-24 06:36:48 +00002686void ASTWriter::WriteCXXCtorInitializersOffsets() {
2687 if (CXXCtorInitializersOffsets.empty())
2688 return;
2689
Richard Smithc2bb8182015-03-24 06:36:48 +00002690 // Create a blob abbreviation for the C++ ctor initializer offsets.
2691 using namespace llvm;
2692
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002693 auto *Abbrev = new BitCodeAbbrev();
Richard Smithc2bb8182015-03-24 06:36:48 +00002694 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2697 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2698
2699 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002700 RecordData::value_type Record[] = {CXX_CTOR_INITIALIZERS_OFFSETS,
2701 CXXCtorInitializersOffsets.size()};
Richard Smithc2bb8182015-03-24 06:36:48 +00002702 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002703 bytes(CXXCtorInitializersOffsets));
Richard Smithc2bb8182015-03-24 06:36:48 +00002704}
2705
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002706void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2707 if (CXXBaseSpecifiersOffsets.empty())
2708 return;
2709
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002710 // Create a blob abbreviation for the C++ base specifiers offsets.
2711 using namespace llvm;
2712
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002713 auto *Abbrev = new BitCodeAbbrev();
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002714 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2717 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2718
Douglas Gregorc27b2872011-08-04 00:01:48 +00002719 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002720 RecordData::value_type Record[] = {CXX_BASE_SPECIFIER_OFFSETS,
2721 CXXBaseSpecifiersOffsets.size()};
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002722 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002723 bytes(CXXBaseSpecifiersOffsets));
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002724}
2725
Douglas Gregorc5046832009-04-27 18:38:38 +00002726//===----------------------------------------------------------------------===//
2727// Type Serialization
2728//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002729
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002730/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002731void ASTWriter::WriteType(QualType T) {
Argyrios Kyrtzidisa7fbbb02010-08-20 16:04:04 +00002732 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002733 if (Idx.getIndex() == 0) // we haven't seen this type before.
2734 Idx = TypeIdx(NextTypeID++);
Mike Stump11289f42009-09-09 15:08:12 +00002735
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002736 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002737
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002738 // Record the offset for this type.
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002739 unsigned Index = Idx.getIndex() - FirstTypeID;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002740 if (TypeOffsets.size() == Index)
Douglas Gregor8f45df52009-04-16 22:23:12 +00002741 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002742 else if (TypeOffsets.size() < Index) {
2743 TypeOffsets.resize(Index + 1);
2744 TypeOffsets[Index] = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002745 }
2746
2747 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002748
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002749 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002750 ASTTypeWriter W(*this, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +00002751 W.AbbrevToUse = 0;
John McCall8ccfcb52009-09-24 19:53:00 +00002752
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002753 if (T.hasLocalNonFastQualifiers()) {
2754 Qualifiers Qs = T.getLocalQualifiers();
2755 AddTypeRef(T.getLocalUnqualifiedType(), Record);
John McCall8ccfcb52009-09-24 19:53:00 +00002756 Record.push_back(Qs.getAsOpaqueValue());
Sebastian Redl539c5062010-08-18 23:57:32 +00002757 W.Code = TYPE_EXT_QUAL;
Richard Smith01b2cb42014-07-26 06:37:51 +00002758 W.AbbrevToUse = TypeExtQualAbbrev;
John McCall8ccfcb52009-09-24 19:53:00 +00002759 } else {
2760 switch (T->getTypeClass()) {
2761 // For all of the concrete, non-dependent types, call the
2762 // appropriate visitor function.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002763#define TYPE(Class, Base) \
Mike Stump281d6d72010-01-20 02:03:14 +00002764 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002766#include "clang/AST/TypeNodes.def"
John McCall8ccfcb52009-09-24 19:53:00 +00002767 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002768 }
2769
2770 // Emit the serialized record.
Richard Smith01b2cb42014-07-26 06:37:51 +00002771 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002772
2773 // Flush any expressions that were written as part of this type.
Douglas Gregor8f45df52009-04-16 22:23:12 +00002774 FlushStmts();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002775}
2776
Douglas Gregorc5046832009-04-27 18:38:38 +00002777//===----------------------------------------------------------------------===//
2778// Declaration Serialization
2779//===----------------------------------------------------------------------===//
2780
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002781/// \brief Write the block containing all of the declaration IDs
2782/// lexically declared within the given DeclContext.
2783///
2784/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2785/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002786uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002787 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002788 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002789 return 0;
2790
Douglas Gregor8f45df52009-04-16 22:23:12 +00002791 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002792 SmallVector<uint32_t, 128> KindDeclPairs;
2793 for (const auto *D : DC->decls()) {
2794 KindDeclPairs.push_back(D->getKind());
2795 KindDeclPairs.push_back(GetDeclRef(D));
2796 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002797
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002798 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002799 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002800 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2801 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002802 return Offset;
2803}
2804
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002805void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002806 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002807
2808 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002809 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002810 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002812 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002813 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2814 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002815 {
2816 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2817 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2818 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2819 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002820
2821 // Write the declaration offsets array
2822 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002823 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002824 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002826 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2827 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002828 {
2829 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2830 FirstDeclID - NUM_PREDEF_DECL_IDS};
2831 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2832 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002833}
2834
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002835void ASTWriter::WriteFileDeclIDsMap() {
2836 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002837
Chandler Carruthb306d732015-03-27 00:31:20 +00002838 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2839 FileDeclIDs.begin(), FileDeclIDs.end());
2840 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2841 llvm::less_first());
2842
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002843 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002844 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2845 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2846 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2847 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2848 for (auto &LocDeclEntry : Info.DeclIDs)
2849 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002850 }
2851
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002852 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002853 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2856 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002857 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2858 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002859 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002860}
2861
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002862void ASTWriter::WriteComments() {
2863 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002864 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002865 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002866 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002867 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002868 AddSourceRange(I->getSourceRange(), Record);
2869 Record.push_back(I->getKind());
2870 Record.push_back(I->isTrailingComment());
2871 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002872 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2873 }
2874 Stream.ExitBlock();
2875}
2876
Douglas Gregorc5046832009-04-27 18:38:38 +00002877//===----------------------------------------------------------------------===//
2878// Global Method Pool and Selector Serialization
2879//===----------------------------------------------------------------------===//
2880
Douglas Gregore84a9da2009-04-20 20:36:09 +00002881namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002882// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002883class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002884 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002885
2886public:
2887 typedef Selector key_type;
2888 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002889
Sebastian Redl834bb972010-08-04 17:20:04 +00002890 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002891 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002892 ObjCMethodList Instance, Factory;
2893 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002894 typedef const data_type& data_type_ref;
2895
Justin Bogner25463f12014-04-18 20:27:24 +00002896 typedef unsigned hash_value_type;
2897 typedef unsigned offset_type;
2898
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002899 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002900
Justin Bogner25463f12014-04-18 20:27:24 +00002901 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002902 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
2905 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002906 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002907 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002908 using namespace llvm::support;
2909 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002910 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002911 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002912 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2913 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002914 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002915 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002916 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002917 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002918 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002919 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002920 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002921 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002922 return std::make_pair(KeyLen, DataLen);
2923 }
Mike Stump11289f42009-09-09 15:08:12 +00002924
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002925 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002926 using namespace llvm::support;
2927 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002928 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002929 assert((Start >> 32) == 0 && "Selector key offset too large");
2930 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002931 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002932 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002933 if (N == 0)
2934 N = 1;
2935 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002936 LE.write<uint32_t>(
2937 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002938 }
Mike Stump11289f42009-09-09 15:08:12 +00002939
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002941 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002942 using namespace llvm::support;
2943 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002944 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002945 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002946 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002947 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002948 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002949 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002950 ++NumInstanceMethods;
2951
2952 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002953 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002954 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002955 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002956 ++NumFactoryMethods;
2957
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002958 unsigned InstanceBits = Methods.Instance.getBits();
2959 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002960 unsigned InstanceHasMoreThanOneDeclBit =
2961 Methods.Instance.hasMoreThanOneDecl();
2962 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2963 (InstanceHasMoreThanOneDeclBit << 2) |
2964 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002965 unsigned FactoryBits = Methods.Factory.getBits();
2966 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002967 unsigned FactoryHasMoreThanOneDeclBit =
2968 Methods.Factory.hasMoreThanOneDecl();
2969 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2970 (FactoryHasMoreThanOneDeclBit << 2) |
2971 FactoryBits;
2972 LE.write<uint16_t>(FullInstanceBits);
2973 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002974 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002975 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002976 if (Method->getMethod())
2977 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002978 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002979 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002980 if (Method->getMethod())
2981 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002982
2983 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002984 }
2985};
2986} // end anonymous namespace
2987
Sebastian Redla19a67f2010-08-03 21:58:15 +00002988/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002989///
2990/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00002991/// in an on-disk hash table indexed by the selector. The hash table also
2992/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002993void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002994 using namespace llvm;
2995
Sebastian Redla19a67f2010-08-03 21:58:15 +00002996 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00002997 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00002998 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00002999 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003000 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003001 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003002 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003003 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003004
Sebastian Redla19a67f2010-08-03 21:58:15 +00003005 // Create the on-disk hash table representation. We walk through every
3006 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003007 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003008 for (auto &SelectorAndID : SelectorIDs) {
3009 Selector S = SelectorAndID.first;
3010 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003011 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003012 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003013 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003014 ObjCMethodList(),
3015 ObjCMethodList()
3016 };
3017 if (F != SemaRef.MethodPool.end()) {
3018 Data.Instance = F->second.first;
3019 Data.Factory = F->second.second;
3020 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003021 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003022 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003023 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003024 // Selector already exists. Did it change?
3025 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003026 for (ObjCMethodList *M = &Data.Instance;
3027 !changed && M && M->getMethod(); M = M->getNext()) {
3028 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003029 changed = true;
3030 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003031 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003032 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003033 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003034 changed = true;
3035 }
3036 if (!changed)
3037 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003038 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003039 // A new method pool entry.
3040 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003041 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003042 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003043 }
3044
Douglas Gregorc78d3462009-04-24 21:10:55 +00003045 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003046 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003047 uint32_t BucketOffset;
3048 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003049 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003050 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003051 llvm::raw_svector_ostream Out(MethodPool);
3052 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003053 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003054 BucketOffset = Generator.Emit(Out, Trait);
3055 }
3056
3057 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003058 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003059 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003060 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003061 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003062 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3063 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3064
Douglas Gregor95c13f52009-04-25 17:48:32 +00003065 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003066 {
3067 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3068 NumTableEntries};
3069 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3070 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003071
3072 // Create a blob abbreviation for the selector table offsets.
3073 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003074 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003075 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003076 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003077 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3078 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3079
3080 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003081 {
3082 RecordData::value_type Record[] = {
3083 SELECTOR_OFFSETS, SelectorOffsets.size(),
3084 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3085 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3086 bytes(SelectorOffsets));
3087 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003088 }
3089}
3090
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003091/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003092void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003093 using namespace llvm;
3094 if (SemaRef.ReferencedSelectors.empty())
3095 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003096
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003097 RecordData Record;
Sebastian Redlada023c2010-08-04 20:40:17 +00003098
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003099 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003100 // very tricky to fix, and given that @selector shouldn't really appear in
3101 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003102 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3103 Selector Sel = SelectorAndLocation.first;
3104 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003105 AddSelectorRef(Sel, Record);
3106 AddSourceLocation(Loc, Record);
3107 }
Sebastian Redl539c5062010-08-18 23:57:32 +00003108 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003109}
3110
Douglas Gregorc5046832009-04-27 18:38:38 +00003111//===----------------------------------------------------------------------===//
3112// Identifier Table Serialization
3113//===----------------------------------------------------------------------===//
3114
Richard Smithb3761912015-02-05 23:08:52 +00003115/// Determine the declaration that should be put into the name lookup table to
3116/// represent the given declaration in this module. This is usually D itself,
3117/// but if D was imported and merged into a local declaration, we want the most
3118/// recent local declaration instead. The chosen declaration will be the most
3119/// recent declaration in any module that imports this one.
3120static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3121 NamedDecl *D) {
3122 if (!LangOpts.Modules || !D->isFromASTFile())
3123 return D;
3124
3125 if (Decl *Redecl = D->getPreviousDecl()) {
3126 // For Redeclarable decls, a prior declaration might be local.
3127 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3128 if (!Redecl->isFromASTFile())
3129 return cast<NamedDecl>(Redecl);
Richard Smithfe620d22015-03-05 23:24:12 +00003130 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003131 // local one.
3132 if (D->getOwningModuleID() == 0)
3133 break;
3134 }
3135 } else if (Decl *First = D->getCanonicalDecl()) {
3136 // For Mergeable decls, the first decl might be local.
3137 if (!First->isFromASTFile())
3138 return cast<NamedDecl>(First);
3139 }
3140
3141 // All declarations are imported. Our most recent declaration will also be
3142 // the most recent one in anyone who imports us.
3143 return D;
3144}
3145
Douglas Gregorc78d3462009-04-24 21:10:55 +00003146namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003147class ASTIdentifierTableTrait {
3148 ASTWriter &Writer;
3149 Preprocessor &PP;
3150 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003151 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003152 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003153 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003154
3155 /// \brief Determines whether this is an "interesting" identifier that needs a
3156 /// full IdentifierInfo structure written into the hash table. Notably, this
3157 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3158 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003159 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003160 if (MacroOffset ||
3161 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003162 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003163 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003164 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003165 return true;
3166
3167 return false;
3168 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003169
Douglas Gregore84a9da2009-04-20 20:36:09 +00003170public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003171 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003172 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Sebastian Redl539c5062010-08-18 23:57:32 +00003174 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003175 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003176
Justin Bogner25463f12014-04-18 20:27:24 +00003177 typedef unsigned hash_value_type;
3178 typedef unsigned offset_type;
3179
Richard Smithd7329392015-04-21 21:46:32 +00003180 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003181 IdentifierResolver &IdResolver, bool IsModule,
3182 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003183 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003184 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3185 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003186
Richard Smithd79514e2016-02-05 19:03:40 +00003187 bool needDecls() const { return NeedDecls; }
3188
Justin Bogner25463f12014-04-18 20:27:24 +00003189 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003190 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003191 }
Mike Stump11289f42009-09-09 15:08:12 +00003192
Richard Smith33e0f7e2015-07-22 02:08:40 +00003193 bool isInterestingIdentifier(const IdentifierInfo *II) {
3194 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3195 return isInterestingIdentifier(II, MacroOffset);
3196 }
Richard Smith9c254182015-07-19 21:41:12 +00003197 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3198 return isInterestingIdentifier(II, 0);
3199 }
3200
Mike Stump11289f42009-09-09 15:08:12 +00003201 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003202 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003203 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003204 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003205 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3206 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003207 DataLen += 2; // 2 bytes for builtin ID
3208 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003209 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003210 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003211
Richard Smitha534a312015-07-21 23:54:07 +00003212 if (NeedDecls) {
3213 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3214 DEnd = IdResolver.end();
3215 D != DEnd; ++D)
3216 DataLen += 4;
3217 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003218 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003219 using namespace llvm::support;
3220 endian::Writer<little> LE(Out);
3221
Richard Smithdf8a8312015-03-13 04:05:01 +00003222 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003223 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003224 // We emit the key length after the data length so that every
3225 // string is preceded by a 16-bit length. This matches the PTH
3226 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003227 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003228 return std::make_pair(KeyLen, DataLen);
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003231 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003232 unsigned KeyLen) {
3233 // Record the location of the key data. This is used when generating
3234 // the mapping from persistent IDs to strings.
3235 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003236
3237 // Emit the offset of the key/data length information to the interesting
3238 // identifiers table if necessary.
3239 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3240 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3241
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003242 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003243 }
Mike Stump11289f42009-09-09 15:08:12 +00003244
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003245 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003246 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003247 using namespace llvm::support;
3248 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003249
Richard Smithd7329392015-04-21 21:46:32 +00003250 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3251 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003252 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003253 return;
3254 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003255
Justin Bognere1c147c2014-03-28 22:03:19 +00003256 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003257 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3258 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003259 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003260 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003261 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003262 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003263 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3264 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003265 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003266 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003267 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003268 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003269
Richard Smithd7329392015-04-21 21:46:32 +00003270 if (HadMacroDefinition)
3271 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003272
Richard Smitha534a312015-07-21 23:54:07 +00003273 if (NeedDecls) {
3274 // Emit the declaration IDs in reverse order, because the
3275 // IdentifierResolver provides the declarations as they would be
3276 // visible (e.g., the function "stat" would come before the struct
3277 // "stat"), but the ASTReader adds declarations to the end of the list
3278 // (so we need to see the struct "stat" before the function "stat").
3279 // Only emit declarations that aren't from a chained PCH, though.
3280 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3281 IdResolver.end());
3282 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3283 DEnd = Decls.rend();
3284 D != DEnd; ++D)
3285 LE.write<uint32_t>(
3286 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3287 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003288 }
3289};
3290} // end anonymous namespace
3291
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003292/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003293///
3294/// The identifier table consists of a blob containing string data
3295/// (the actual identifiers themselves) and a separate "offsets" index
3296/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003297void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3298 IdentifierResolver &IdResolver,
3299 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003300 using namespace llvm;
3301
Richard Smith33e0f7e2015-07-22 02:08:40 +00003302 RecordData InterestingIdents;
3303
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003304 // Create and write out the blob that contains the identifier
3305 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003306 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003307 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003308 ASTIdentifierTableTrait Trait(
3309 *this, PP, IdResolver, IsModule,
3310 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregore6648fb2009-04-28 20:33:11 +00003312 // Look for any identifiers that were named while processing the
3313 // headers, but are otherwise not needed. We add these to the hash
3314 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003315 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003316 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003317 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003318 for (const auto &ID : PP.getIdentifierTable())
3319 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003320 // Sort the identifiers lexicographically before getting them references so
3321 // that their order is stable.
3322 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3323 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003324 if (Trait.isInterestingNonMacroIdentifier(II))
3325 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003326
Sebastian Redlff4a2952010-07-23 23:49:55 +00003327 // Create the on-disk hash table representation. We only store offsets
3328 // for identifiers that appear here for the first time.
3329 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003330 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003331 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003332 IdentID ID = IdentIDPair.second;
3333 assert(II && "NULL identifier in identifier table");
Richard Smithd79514e2016-02-05 19:03:40 +00003334 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization() ||
3335 (Trait.needDecls() &&
3336 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003337 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003338 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003339
Douglas Gregore84a9da2009-04-20 20:36:09 +00003340 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003341 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003342 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003343 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003344 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003345 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003346 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003347 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003348 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003349 }
3350
3351 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003352 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003353 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003354 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003355 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003356 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003357
3358 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003359 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003360 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003361 }
3362
3363 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003364 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003365 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3369 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3370
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003371#ifndef NDEBUG
3372 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3373 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3374#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003375
3376 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3377 IdentifierOffsets.size(),
3378 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003379 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003380 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003381
3382 // In C++, write the list of interesting identifiers (those that are
3383 // defined as macros, poisoned, or similar unusual things).
3384 if (!InterestingIdents.empty())
3385 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003386}
3387
Douglas Gregorc5046832009-04-27 18:38:38 +00003388//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003389// DeclContext's Name Lookup Table Serialization
3390//===----------------------------------------------------------------------===//
3391
3392namespace {
3393// Trait used for the on-disk hash table used in the method pool.
3394class ASTDeclContextNameLookupTrait {
3395 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003396 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003397
3398public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003399 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003400 typedef key_type key_type_ref;
3401
Richard Smithd88a7f12015-09-01 20:35:42 +00003402 /// A start and end index into DeclIDs, representing a sequence of decls.
3403 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003404 typedef const data_type& data_type_ref;
3405
Justin Bogner25463f12014-04-18 20:27:24 +00003406 typedef unsigned hash_value_type;
3407 typedef unsigned offset_type;
3408
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003409 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3410
Richard Smithd88a7f12015-09-01 20:35:42 +00003411 template<typename Coll>
3412 data_type getData(const Coll &Decls) {
3413 unsigned Start = DeclIDs.size();
3414 for (NamedDecl *D : Decls) {
3415 DeclIDs.push_back(
3416 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3417 }
3418 return std::make_pair(Start, DeclIDs.size());
3419 }
3420
3421 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3422 unsigned Start = DeclIDs.size();
3423 for (auto ID : FromReader)
3424 DeclIDs.push_back(ID);
3425 return std::make_pair(Start, DeclIDs.size());
3426 }
3427
3428 static bool EqualKey(key_type_ref a, key_type_ref b) {
3429 return a == b;
3430 }
3431
Richard Smitha06c7e62015-08-26 23:55:49 +00003432 hash_value_type ComputeHash(DeclarationNameKey Name) {
3433 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003434 }
3435
Richard Smithd88a7f12015-09-01 20:35:42 +00003436 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3437 assert(Writer.hasChain() &&
3438 "have reference to loaded module file but no chain?");
3439
3440 using namespace llvm::support;
3441 endian::Writer<little>(Out)
3442 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3443 }
3444
Richard Smitha06c7e62015-08-26 23:55:49 +00003445 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3446 DeclarationNameKey Name,
3447 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003448 using namespace llvm::support;
3449 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003450 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003451 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003452 case DeclarationName::Identifier:
3453 case DeclarationName::ObjCZeroArgSelector:
3454 case DeclarationName::ObjCOneArgSelector:
3455 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003456 case DeclarationName::CXXLiteralOperatorName:
3457 KeyLen += 4;
3458 break;
3459 case DeclarationName::CXXOperatorName:
3460 KeyLen += 1;
3461 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003462 case DeclarationName::CXXConstructorName:
3463 case DeclarationName::CXXDestructorName:
3464 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003465 case DeclarationName::CXXUsingDirective:
3466 break;
3467 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003468 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003469
Richard Smithf02662d2015-07-30 03:17:16 +00003470 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003471 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3472 assert(uint16_t(DataLen) == DataLen &&
3473 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003474 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003475
3476 return std::make_pair(KeyLen, DataLen);
3477 }
3478
Richard Smitha06c7e62015-08-26 23:55:49 +00003479 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003480 using namespace llvm::support;
3481 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003482 LE.write<uint8_t>(Name.getKind());
3483 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003484 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003485 case DeclarationName::CXXLiteralOperatorName:
3486 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003487 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003488 case DeclarationName::ObjCZeroArgSelector:
3489 case DeclarationName::ObjCOneArgSelector:
3490 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003491 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003492 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003493 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003494 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003495 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003496 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003497 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003498 case DeclarationName::CXXConstructorName:
3499 case DeclarationName::CXXDestructorName:
3500 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003501 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003502 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003503 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003504
3505 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003506 }
3507
Richard Smitha06c7e62015-08-26 23:55:49 +00003508 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3509 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003510 using namespace llvm::support;
3511 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003512 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003513 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3514 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003515 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3516 }
3517};
3518} // end anonymous namespace
3519
Chandler Carruthe972c362015-03-26 03:11:40 +00003520bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3521 DeclContext *DC) {
3522 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3523}
3524
3525bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3526 DeclContext *DC) {
3527 for (auto *D : Result.getLookupResult())
3528 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3529 return false;
3530
3531 return true;
3532}
3533
Richard Smithd88a7f12015-09-01 20:35:42 +00003534void
Chandler Carruthe972c362015-03-26 03:11:40 +00003535ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003536 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003537 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3538 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003539 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003540
Chandler Carruthe972c362015-03-26 03:11:40 +00003541 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003542 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003543 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3544
3545 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003546 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3547 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003548 ASTDeclContextNameLookupTrait Trait(*this);
3549
Chandler Carruthe972c362015-03-26 03:11:40 +00003550 // The first step is to collect the declaration names which we need to
3551 // serialize into the name lookup table, and to collect them in a stable
3552 // order.
3553 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003554
Chandler Carruthe972c362015-03-26 03:11:40 +00003555 // We also build up small sets of the constructor and conversion function
3556 // names which are visible.
3557 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003558
Chandler Carruthe972c362015-03-26 03:11:40 +00003559 for (auto &Lookup : *DC->buildLookup()) {
3560 auto &Name = Lookup.first;
3561 auto &Result = Lookup.second;
3562
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003563 // If there are no local declarations in our lookup result, we
3564 // don't need to write an entry for the name at all. If we can't
3565 // write out a lookup set without performing more deserialization,
3566 // just skip this entry.
3567 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003568 isLookupResultEntirelyExternal(Result, DC))
3569 continue;
3570
3571 // We also skip empty results. If any of the results could be external and
3572 // the currently available results are empty, then all of the results are
3573 // external and we skip it above. So the only way we get here with an empty
3574 // results is when no results could have been external *and* we have
3575 // external results.
3576 //
3577 // FIXME: While we might want to start emitting on-disk entries for negative
3578 // lookups into a decl context as an optimization, today we *have* to skip
3579 // them because there are names with empty lookup results in decl contexts
3580 // which we can't emit in any stable ordering: we lookup constructors and
3581 // conversion functions in the enclosing namespace scope creating empty
3582 // results for them. This in almost certainly a bug in Clang's name lookup,
3583 // but that is likely to be hard or impossible to fix and so we tolerate it
3584 // here by omitting lookups with empty results.
3585 if (Lookup.second.getLookupResult().empty())
3586 continue;
3587
3588 switch (Lookup.first.getNameKind()) {
3589 default:
3590 Names.push_back(Lookup.first);
3591 break;
3592
Richard Smithcd45dbc2014-04-19 03:48:30 +00003593 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003594 assert(isa<CXXRecordDecl>(DC) &&
3595 "Cannot have a constructor name outside of a class!");
3596 ConstructorNameSet.insert(Name);
3597 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003598
3599 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003600 assert(isa<CXXRecordDecl>(DC) &&
3601 "Cannot have a conversion function name outside of a class!");
3602 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003603 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003604 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003605 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003606
Chandler Carruthe972c362015-03-26 03:11:40 +00003607 // Sort the names into a stable order.
3608 std::sort(Names.begin(), Names.end());
3609
Chandler Carruthffbf7052015-03-26 22:27:09 +00003610 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003611 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003612 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003613
Chandler Carruthffbf7052015-03-26 22:27:09 +00003614 // First we try the easy case by forming the current context's constructor
3615 // name and adding that name first. This is a very useful optimization to
3616 // avoid walking the lexical declarations in many cases, and it also
3617 // handles the only case where a constructor name can come from some other
3618 // lexical context -- when that name is an implicit constructor merged from
3619 // another declaration in the redecl chain. Any non-implicit constructor or
3620 // conversion function which doesn't occur in all the lexical contexts
3621 // would be an ODR violation.
3622 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3623 Context->getCanonicalType(Context->getRecordType(D)));
3624 if (ConstructorNameSet.erase(ImplicitCtorName))
3625 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003626
Chandler Carruthffbf7052015-03-26 22:27:09 +00003627 // If we still have constructors or conversion functions, we walk all the
3628 // names in the decl and add the constructors and conversion functions
3629 // which are visible in the order they lexically occur within the context.
3630 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3631 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3632 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3633 auto Name = ChildND->getDeclName();
3634 switch (Name.getNameKind()) {
3635 default:
3636 continue;
3637
3638 case DeclarationName::CXXConstructorName:
3639 if (ConstructorNameSet.erase(Name))
3640 Names.push_back(Name);
3641 break;
3642
3643 case DeclarationName::CXXConversionFunctionName:
3644 if (ConversionNameSet.erase(Name))
3645 Names.push_back(Name);
3646 break;
3647 }
3648
3649 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3650 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003651 }
3652
Chandler Carruthe972c362015-03-26 03:11:40 +00003653 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3654 "constructors by walking all the "
3655 "lexical members of the context.");
3656 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3657 "conversion functions by walking all "
3658 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003659 }
3660
Chandler Carruthe972c362015-03-26 03:11:40 +00003661 // Next we need to do a lookup with each name into this decl context to fully
3662 // populate any results from external sources. We don't actually use the
3663 // results of these lookups because we only want to use the results after all
3664 // results have been loaded and the pointers into them will be stable.
3665 for (auto &Name : Names)
3666 DC->lookup(Name);
3667
3668 // Now we need to insert the results for each name into the hash table. For
3669 // constructor names and conversion function names, we actually need to merge
3670 // all of the results for them into one list of results each and insert
3671 // those.
3672 SmallVector<NamedDecl *, 8> ConstructorDecls;
3673 SmallVector<NamedDecl *, 8> ConversionDecls;
3674
3675 // Now loop over the names, either inserting them or appending for the two
3676 // special cases.
3677 for (auto &Name : Names) {
3678 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3679
3680 switch (Name.getNameKind()) {
3681 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003682 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003683 break;
3684
3685 case DeclarationName::CXXConstructorName:
3686 ConstructorDecls.append(Result.begin(), Result.end());
3687 break;
3688
3689 case DeclarationName::CXXConversionFunctionName:
3690 ConversionDecls.append(Result.begin(), Result.end());
3691 break;
3692 }
3693 }
3694
3695 // Handle our two special cases if we ended up having any. We arbitrarily use
3696 // the first declaration's name here because the name itself isn't part of
3697 // the key, only the kind of name is used.
3698 if (!ConstructorDecls.empty())
3699 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003700 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003701 if (!ConversionDecls.empty())
3702 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003703 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003704
Richard Smithd88a7f12015-09-01 20:35:42 +00003705 // Create the on-disk hash table. Also emit the existing imported and
3706 // merged table if there is one.
3707 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3708 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003709}
3710
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003711/// \brief Write the block containing all of the declaration IDs
3712/// visible from the given DeclContext.
3713///
3714/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003715/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003716uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3717 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003718 // If we imported a key declaration of this namespace, write the visible
3719 // lookup results as an update record for it rather than including them
3720 // on this declaration. We will only look at key declarations on reload.
3721 if (isa<NamespaceDecl>(DC) && Chain &&
3722 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3723 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003724 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003725 Prev = Prev->getPreviousDecl())
3726 if (!Prev->isFromASTFile())
3727 return 0;
3728
3729 // Note that we need to emit an update record for the primary context.
3730 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3731
3732 // Make sure all visible decls are written. They will be recorded later. We
3733 // do this using a side data structure so we can sort the names into
3734 // a deterministic order.
3735 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3736 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3737 LookupResults;
3738 if (Map) {
3739 LookupResults.reserve(Map->size());
3740 for (auto &Entry : *Map)
3741 LookupResults.push_back(
3742 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3743 }
3744
3745 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3746 for (auto &NameAndResult : LookupResults) {
3747 DeclarationName Name = NameAndResult.first;
3748 DeclContext::lookup_result Result = NameAndResult.second;
3749 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3750 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3751 // We have to work around a name lookup bug here where negative lookup
3752 // results for these names get cached in namespace lookup tables (these
3753 // names should never be looked up in a namespace).
3754 assert(Result.empty() && "Cannot have a constructor or conversion "
3755 "function name in a namespace!");
3756 continue;
3757 }
3758
3759 for (NamedDecl *ND : Result)
3760 if (!ND->isFromASTFile())
3761 GetDeclRef(ND);
3762 }
3763
3764 return 0;
3765 }
3766
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003767 if (DC->getPrimaryContext() != DC)
3768 return 0;
3769
Chandler Carruthe972c362015-03-26 03:11:40 +00003770 // Skip contexts which don't support name lookup.
3771 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003772 return 0;
3773
3774 // If not in C++, we perform name lookup for the translation unit via the
3775 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003776 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003777 return 0;
3778
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003779 // Serialize the contents of the mapping used for lookup. Note that,
3780 // although we have two very different code paths, the serialized
3781 // representation is the same for both cases: a declaration name,
3782 // followed by a size, followed by references to the visible
3783 // declarations that have that name.
3784 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003785 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003786 if (!Map || Map->empty())
3787 return 0;
3788
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003789 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003790 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003791 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003792
3793 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003794 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003795 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003796 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003797 ++NumVisibleDeclContexts;
3798 return Offset;
3799}
3800
Sebastian Redla4071b42010-08-24 00:50:09 +00003801/// \brief Write an UPDATE_VISIBLE block for the given context.
3802///
3803/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3804/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003805/// (in C++), for namespaces, and for classes with forward-declared unscoped
3806/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003807void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003808 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003809 if (!Map || Map->empty())
3810 return;
3811
Sebastian Redla4071b42010-08-24 00:50:09 +00003812 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003813 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003814 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003815
Richard Smith5fc18a92015-07-12 23:43:21 +00003816 // If we're updating a namespace, select a key declaration as the key for the
3817 // update record; those are the only ones that will be checked on reload.
3818 if (isa<NamespaceDecl>(DC))
3819 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3820
Sebastian Redla4071b42010-08-24 00:50:09 +00003821 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003822 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003823 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003824}
3825
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003826/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3827void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003828 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003829 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3830}
3831
3832/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3833void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003834 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003835 return;
3836
3837 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3838 RecordData Record;
3839#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3840#include "clang/Basic/OpenCLExtensions.def"
3841 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3842}
3843
Douglas Gregor404cdde2012-01-27 01:47:08 +00003844void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003845 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003846 RecordData Categories;
3847
3848 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3849 unsigned Size = 0;
3850 unsigned StartIndex = Categories.size();
3851
3852 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3853
3854 // Allocate space for the size.
3855 Categories.push_back(0);
3856
3857 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003858 for (ObjCInterfaceDecl::known_categories_iterator
3859 Cat = Class->known_categories_begin(),
3860 CatEnd = Class->known_categories_end();
3861 Cat != CatEnd; ++Cat, ++Size) {
3862 assert(getDeclID(*Cat) != 0 && "Bogus category");
3863 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003864 }
3865
3866 // Update the size.
3867 Categories[StartIndex] = Size;
3868
3869 // Record this interface -> category map.
3870 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3871 CategoriesMap.push_back(CatInfo);
3872 }
3873
3874 // Sort the categories map by the definition ID, since the reader will be
3875 // performing binary searches on this information.
3876 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3877
3878 // Emit the categories map.
3879 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003880
3881 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003882 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3885 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003886
3887 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3888 Stream.EmitRecordWithBlob(AbbrevID, Record,
3889 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003890 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003891
Douglas Gregor404cdde2012-01-27 01:47:08 +00003892 // Emit the category lists.
3893 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3894}
3895
Richard Smithe40f2ba2013-08-07 21:41:30 +00003896void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3897 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3898
3899 if (LPTMap.empty())
3900 return;
3901
3902 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003903 for (auto LPTMapEntry : LPTMap) {
3904 const FunctionDecl *FD = LPTMapEntry.first;
3905 LateParsedTemplate *LPT = LPTMapEntry.second;
3906 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003907 AddDeclRef(LPT->D, Record);
3908 Record.push_back(LPT->Toks.size());
3909
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003910 for (const auto &Tok : LPT->Toks) {
3911 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003912 }
3913 }
3914 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3915}
3916
Dario Domizioli13a0a382014-05-23 12:13:25 +00003917/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3918void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3919 RecordData Record;
3920 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3921 AddSourceLocation(PragmaLoc, Record);
3922 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3923}
3924
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003925void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3926 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003927 // Enter the extension block.
3928 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3929
3930 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003931 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003932 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3933 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3934 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3935 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3936 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3937 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3938 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3939
3940 // Emit the metadata record.
3941 RecordData Record;
3942 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3943 Record.push_back(EXTENSION_METADATA);
3944 Record.push_back(Metadata.MajorVersion);
3945 Record.push_back(Metadata.MinorVersion);
3946 Record.push_back(Metadata.BlockName.size());
3947 Record.push_back(Metadata.UserInfo.size());
3948 SmallString<64> Buffer;
3949 Buffer += Metadata.BlockName;
3950 Buffer += Metadata.UserInfo;
3951 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3952
3953 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003954 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003955
3956 // Exit the extension block.
3957 Stream.ExitBlock();
3958}
3959
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003960//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003961// General Serialization Routines
3962//===----------------------------------------------------------------------===//
3963
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003964/// \brief Write a record containing the given attributes.
Alexander Kornienko20f6fc62012-07-09 10:04:07 +00003965void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3966 RecordDataImpl &Record) {
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003967 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003968 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003969 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00003970 AddSourceRange(A->getRange(), Record);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003971
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003972#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00003973
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003974 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003975}
3976
John McCallf413f5e2013-05-03 00:10:13 +00003977void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3978 AddSourceLocation(Tok.getLocation(), Record);
3979 Record.push_back(Tok.getLength());
3980
3981 // FIXME: When reading literal tokens, reconstruct the literal pointer
3982 // if it is needed.
3983 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3984 // FIXME: Should translate token kind to a stable encoding.
3985 Record.push_back(Tok.getKind());
3986 // FIXME: Should translate token flags to a stable encoding.
3987 Record.push_back(Tok.getFlags());
3988}
3989
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003990void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003991 Record.push_back(Str.size());
3992 Record.insert(Record.end(), Str.begin(), Str.end());
3993}
3994
Richard Smith7ed1bc92014-12-05 22:42:13 +00003995bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00003996 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00003997
Richard Smith54cc3c22014-12-11 20:50:24 +00003998 bool Changed =
3999 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004000
4001 // Remove a prefix to make the path relative, if relevant.
4002 const char *PathBegin = Path.data();
4003 const char *PathPtr =
4004 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4005 if (PathPtr != PathBegin) {
4006 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4007 Changed = true;
4008 }
4009
4010 return Changed;
4011}
4012
4013void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4014 SmallString<128> FilePath(Path);
4015 PreparePathForOutput(FilePath);
4016 AddString(FilePath, Record);
4017}
4018
Mehdi Amini57a41912015-09-10 01:46:39 +00004019void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004020 StringRef Path) {
4021 SmallString<128> FilePath(Path);
4022 PreparePathForOutput(FilePath);
4023 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4024}
4025
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004026void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4027 RecordDataImpl &Record) {
4028 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004029 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004030 Record.push_back(*Minor + 1);
4031 else
4032 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004033 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004034 Record.push_back(*Subminor + 1);
4035 else
4036 Record.push_back(0);
4037}
4038
Douglas Gregore84a9da2009-04-20 20:36:09 +00004039/// \brief Note that the identifier II occurs at the given offset
4040/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004041void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004042 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004043 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004044 // up earlier in the chain and thus don't need an offset.
4045 if (ID >= FirstIdentID)
4046 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004047}
4048
Douglas Gregor95c13f52009-04-25 17:48:32 +00004049/// \brief Note that the selector Sel occurs at the given offset
4050/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004051void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004052 unsigned ID = SelectorIDs[Sel];
4053 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004054 // Don't record offsets for selectors that are also available in a different
4055 // file.
4056 if (ID < FirstSelectorID)
4057 return;
4058 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004059}
4060
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004061ASTWriter::ASTWriter(
4062 llvm::BitstreamWriter &Stream,
4063 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4064 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004065 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004066 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4067 WritingAST(false), DoneWritingDeclsAndTypes(false),
4068 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4069 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4070 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4071 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4072 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004073 NextSubmoduleID(FirstSubmoduleID),
4074 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4075 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4076 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00004077 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004078 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004079 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004080 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004081 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004082 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4083 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004084 ExprImplicitCastAbbrev(0) {
4085 for (const auto &Ext : Extensions) {
4086 if (auto Writer = Ext->createExtensionWriter(*this))
4087 ModuleFileExtensionWriters.push_back(std::move(Writer));
4088 }
4089}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004090
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004091ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004092 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004093}
4094
Richard Smithb3761912015-02-05 23:08:52 +00004095const LangOptions &ASTWriter::getLangOpts() const {
4096 assert(WritingAST && "can't determine lang opts when not writing AST");
4097 return Context->getLangOpts();
4098}
4099
Richard Smithe75ee0f2015-08-17 07:13:32 +00004100time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4101 return IncludeTimestamps ? E->getModificationTime() : 0;
4102}
4103
Adrian Prantladbd2b12015-09-22 23:26:31 +00004104uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4105 Module *WritingModule, StringRef isysroot,
4106 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004107 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004108
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004109 ASTHasCompilerErrors = hasErrors;
4110
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004111 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004112 Stream.Emit((unsigned)'C', 8);
4113 Stream.Emit((unsigned)'P', 8);
4114 Stream.Emit((unsigned)'C', 8);
4115 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004116
Chris Lattner28fa4e62009-04-26 22:26:21 +00004117 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004118
Douglas Gregoreda8e122011-08-09 15:13:55 +00004119 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004120 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004121 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004122 ASTFileSignature Signature =
4123 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004124 Context = nullptr;
4125 PP = nullptr;
4126 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004127 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004128
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004129 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004130 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004131}
4132
Douglas Gregora94a1542011-07-27 21:45:57 +00004133template<typename Vector>
4134static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4135 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004136 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4137 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004138 Writer.AddDeclRef(*I, Record);
4139 }
4140}
4141
Adrian Prantladbd2b12015-09-22 23:26:31 +00004142uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4143 const std::string &OutputFile,
4144 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004145 using namespace llvm;
4146
Craig Toppera13603a2014-05-22 05:54:18 +00004147 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004148
Douglas Gregorcf68c582011-12-01 22:20:10 +00004149 // Make sure that the AST reader knows to finalize itself.
4150 if (Chain)
4151 Chain->finalizeForWriting();
4152
Sebastian Redl143413f2010-07-12 22:02:52 +00004153 ASTContext &Context = SemaRef.Context;
4154 Preprocessor &PP = SemaRef.PP;
4155
Douglas Gregordab42432011-08-12 00:15:20 +00004156 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004157 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4158 if (D) {
4159 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4160 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004161 }
4162 };
4163 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4164 PREDEF_DECL_TRANSLATION_UNIT_ID);
4165 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4166 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4167 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4168 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4169 PREDEF_DECL_OBJC_PROTOCOL_ID);
4170 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4171 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4172 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4173 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4174 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004175 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004176 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4177 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004178 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004179 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4180 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004181 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4182 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004183 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4184 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004185
Chris Lattner0c797362009-09-08 18:19:27 +00004186 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004187 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004188 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004189 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004190 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004191
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004192 // Build a record containing all of the file scoped decls in this file.
4193 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004194 if (!isModule)
4195 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4196 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004197
Douglas Gregor851443c2011-08-12 01:39:19 +00004198 // Build a record containing all of the delegating constructors we still need
4199 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004200 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004201 if (!isModule)
4202 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004203
Douglas Gregor851443c2011-08-12 01:39:19 +00004204 // Write the set of weak, undeclared identifiers. We always write the
4205 // entire table, since later PCH files in a PCH chain are only interested in
4206 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004207 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004208 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4209 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4210 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4211 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4212 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4213 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4214 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004215 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004216
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004217 // Build a record containing all of the ext_vector declarations.
4218 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004219 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004220
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004221 // Build a record containing all of the VTable uses information.
4222 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004223 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004224 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4225 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4226 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4227 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4228 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004229 }
4230
Nico Weber72889432014-09-06 01:25:55 +00004231 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4232 RecordData UnusedLocalTypedefNameCandidates;
4233 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4234 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4235
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004236 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004237 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004238 for (const auto &I : SemaRef.PendingInstantiations) {
4239 AddDeclRef(I.first, PendingInstantiations);
4240 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004241 }
4242 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4243 "There are local ones at end of translation unit!");
4244
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004245 // Build a record containing some declaration references.
4246 RecordData SemaDeclRefs;
4247 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4248 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4249 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4250 }
4251
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004252 RecordData CUDASpecialDeclRefs;
4253 if (Context.getcudaConfigureCallDecl()) {
4254 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4255 }
4256
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004257 // Build a record containing all of the known namespaces.
4258 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004259 for (const auto &I : SemaRef.KnownNamespaces) {
4260 if (!I.second)
4261 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004262 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004263
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004264 // Build a record of all used, undefined objects that require definitions.
4265 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004266
4267 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004268 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004269 for (const auto &I : Undefined) {
4270 AddDeclRef(I.first, UndefinedButUsed);
4271 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004272 }
4273
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004274 // Build a record containing all delete-expressions that we would like to
4275 // analyze later in AST.
4276 RecordData DeleteExprsToAnalyze;
4277
4278 for (const auto &DeleteExprsInfo :
4279 SemaRef.getMismatchingDeleteExpressions()) {
4280 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4281 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4282 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4283 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4284 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4285 }
4286 }
4287
Douglas Gregor112b9072012-10-18 05:31:06 +00004288 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004289 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004290
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004291 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004292 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004293
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004294 // This is so that older clang versions, before the introduction
4295 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004296 {
4297 RecordData Record = {VERSION_MAJOR};
4298 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4299 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004300
Douglas Gregor851443c2011-08-12 01:39:19 +00004301 // Create a lexical update block containing all of the declarations in the
4302 // translation unit that do not come from other AST files.
4303 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004304 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4305 for (const auto *D : TU->noload_decls()) {
4306 if (!D->isFromASTFile()) {
4307 NewGlobalKindDeclPairs.push_back(D->getKind());
4308 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4309 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004310 }
4311
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004312 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004313 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4314 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4315 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004316 {
4317 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4318 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4319 bytes(NewGlobalKindDeclPairs));
4320 }
4321
Douglas Gregor851443c2011-08-12 01:39:19 +00004322 // And a visible updates block for the translation unit.
4323 Abv = new llvm::BitCodeAbbrev();
4324 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4325 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004326 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4327 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4328 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004329
4330 // If we have any extern "C" names, write out a visible update for them.
4331 if (Context.ExternCContext)
4332 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004333
4334 // If the translation unit has an anonymous namespace, and we don't already
4335 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004336 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004337 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4338 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004339 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004340 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004341 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004342
Richard Smith5652c0f2014-03-21 01:48:23 +00004343 // Add update records for all mangling numbers and static local numbers.
4344 // These aren't really update records, but this is a convenient way of
4345 // tagging this rare extra data onto the declarations.
4346 for (const auto &Number : Context.MangleNumbers)
4347 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004348 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4349 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004350 for (const auto &Number : Context.StaticLocalNumbers)
4351 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004352 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4353 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004354
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004355 // Make sure visible decls, added to DeclContexts previously loaded from
4356 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004357 for (const auto *I : UpdatingVisibleDecls) {
4358 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004359 }
4360
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004361 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004362 // serialization, if we're storing decls with identifiers.
4363 if (!WritingModule || !getLangOpts().CPlusPlus) {
4364 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004365 for (const auto &ID : PP.getIdentifierTable()) {
4366 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004367 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4368 IIs.push_back(II);
4369 }
4370 // Sort the identifiers to visit based on their name.
4371 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4372 for (const IdentifierInfo *II : IIs) {
4373 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4374 DEnd = SemaRef.IdResolver.end();
4375 D != DEnd; ++D) {
4376 GetDeclRef(*D);
4377 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004378 }
4379 }
4380
Douglas Gregor5204bde2011-08-02 16:26:37 +00004381 // Form the record of special types.
4382 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004383 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004384 AddTypeRef(Context.getFILEType(), SpecialTypes);
4385 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4386 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4387 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4388 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004389 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004390 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004391
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004392 if (Chain) {
4393 // Write the mapping information describing our module dependencies and how
4394 // each of those modules were mapped into our own offset/ID space, so that
4395 // the reader can build the appropriate mapping to its own offset/ID space.
4396 // The map consists solely of a blob with the following format:
4397 // *(module-name-len:i16 module-name:len*i8
4398 // source-location-offset:i32
4399 // identifier-id:i32
4400 // preprocessed-entity-id:i32
4401 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004402 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004403 // selector-id:i32
4404 // declaration-id:i32
4405 // c++-base-specifiers-id:i32
4406 // type-id:i32)
4407 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004408 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004409 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4410 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4411 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004412 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004413 {
4414 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004415 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004416 using namespace llvm::support;
4417 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004418 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004419 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004420 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004421
Ben Langmuir785180e2014-10-20 16:27:30 +00004422 // Note: if a base ID was uint max, it would not be possible to load
4423 // another module after it or have more than one entity inside it.
4424 uint32_t None = std::numeric_limits<uint32_t>::max();
4425
4426 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4427 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4428 if (ShouldWrite)
4429 LE.write<uint32_t>(BaseID);
4430 else
4431 LE.write<uint32_t>(None);
4432 };
4433
Ben Langmuirfe971d92014-08-16 04:54:18 +00004434 // These values should be unique within a chain, since they will be read
4435 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004436 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4437 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4438 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4439 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4440 M->NumPreprocessedEntities);
4441 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4442 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4443 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4444 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004445 }
4446 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004447 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004448 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4449 Buffer.data(), Buffer.size());
4450 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004451
Richard Smithb9eab6d2014-03-20 19:44:17 +00004452 RecordData DeclUpdatesOffsetsRecord;
4453
Richard Smith59442b42014-03-20 20:07:19 +00004454 // Keep writing types, declarations, and declaration update records
4455 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004456 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4457 WriteTypeAbbrevs();
4458 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004459 do {
4460 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4461 while (!DeclTypesToEmit.empty()) {
4462 DeclOrType DOT = DeclTypesToEmit.front();
4463 DeclTypesToEmit.pop();
4464 if (DOT.isType())
4465 WriteType(DOT.getType());
4466 else
4467 WriteDecl(Context, DOT.getDecl());
4468 }
4469 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004470 Stream.ExitBlock();
4471
Richard Smithb9eab6d2014-03-20 19:44:17 +00004472 DoneWritingDeclsAndTypes = true;
4473
4474 // These things can only be done once we've written out decls and types.
4475 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004476 if (!DeclUpdatesOffsetsRecord.empty())
4477 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004478 WriteCXXBaseSpecifiersOffsets();
Richard Smithc2bb8182015-03-24 06:36:48 +00004479 WriteCXXCtorInitializersOffsets();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004480 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004481 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004482 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004483 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004484 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004485 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004486 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004487 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004488 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004489 WriteFPPragmaOptions(SemaRef.getFPOptions());
4490 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004491 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004492
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004493 // If we're emitting a module, write out the submodule information.
4494 if (WritingModule)
4495 WriteSubmodules(WritingModule);
4496
Douglas Gregor5204bde2011-08-02 16:26:37 +00004497 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4498
Douglas Gregord4df8652009-04-22 22:02:47 +00004499 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004500 if (!EagerlyDeserializedDecls.empty())
4501 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004502
4503 // Write the record containing tentative definitions.
4504 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004505 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004506
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004507 // Write the record containing unused file scoped decls.
4508 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004509 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004510
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004511 // Write the record containing weak undeclared identifiers.
4512 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004513 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004514 WeakUndeclaredIdentifiers);
4515
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004516 // Write the record containing ext_vector type names.
4517 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004518 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004519
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004520 // Write the record containing VTable uses information.
4521 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004522 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004523
Nico Weber72889432014-09-06 01:25:55 +00004524 // Write the record containing potentially unused local typedefs.
4525 if (!UnusedLocalTypedefNameCandidates.empty())
4526 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4527 UnusedLocalTypedefNameCandidates);
4528
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004529 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004530 if (!PendingInstantiations.empty())
4531 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004532
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004533 // Write the record containing declaration references of Sema.
4534 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004535 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004536
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004537 // Write the record containing CUDA-specific declaration references.
4538 if (!CUDASpecialDeclRefs.empty())
4539 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004540
4541 // Write the delegating constructors.
4542 if (!DelegatingCtorDecls.empty())
4543 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004544
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004545 // Write the known namespaces.
4546 if (!KnownNamespaces.empty())
4547 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004548
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004549 // Write the undefined internal functions and variables, and inline functions.
4550 if (!UndefinedButUsed.empty())
4551 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004552
4553 if (!DeleteExprsToAnalyze.empty())
4554 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4555
Douglas Gregor851443c2011-08-12 01:39:19 +00004556 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004557 for (auto *DC : UpdatedDeclContexts)
4558 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004559
Douglas Gregor959bb062011-12-03 01:15:29 +00004560 if (!WritingModule) {
4561 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004562 struct ModuleInfo {
4563 uint64_t ID;
4564 Module *M;
4565 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4566 };
Richard Smith56be7542014-03-21 00:33:59 +00004567 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004568 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004569 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004570 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4571 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004572 }
Richard Smith56be7542014-03-21 00:33:59 +00004573
4574 if (!Imports.empty()) {
4575 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4576 return A.ID < B.ID;
4577 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004578 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4579 return A.ID == B.ID;
4580 };
Richard Smith56be7542014-03-21 00:33:59 +00004581
4582 // Sort and deduplicate module IDs.
4583 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004584 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004585 Imports.end());
4586
4587 RecordData ImportedModules;
4588 for (const auto &Import : Imports) {
4589 ImportedModules.push_back(Import.ID);
4590 // FIXME: If the module has macros imported then later has declarations
4591 // imported, this location won't be the right one as a location for the
4592 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004593 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004594 }
4595
Douglas Gregor959bb062011-12-03 01:15:29 +00004596 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4597 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004598 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004599
Douglas Gregor851443c2011-08-12 01:39:19 +00004600 WriteDeclReplacementsBlock();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004601 WriteObjCCategories();
Dario Domizioli13a0a382014-05-23 12:13:25 +00004602 if(!WritingModule)
4603 WriteOptimizePragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004604
Douglas Gregor08f01292009-04-17 22:13:46 +00004605 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004606 RecordData::value_type Record[] = {
4607 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004608 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004609 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004610
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004611 // Write the module file extension blocks.
4612 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004613 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004614
Adrian Prantladbd2b12015-09-22 23:26:31 +00004615 return Signature;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004616}
4617
Richard Smithb9eab6d2014-03-20 19:44:17 +00004618void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004619 if (DeclUpdates.empty())
4620 return;
4621
Richard Smith59442b42014-03-20 20:07:19 +00004622 DeclUpdateMap LocalUpdates;
4623 LocalUpdates.swap(DeclUpdates);
4624
Richard Smith6ef42932014-03-20 21:02:00 +00004625 for (auto &DeclUpdate : LocalUpdates) {
4626 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004627
Richard Smithd28ac5b2014-03-22 23:33:22 +00004628 bool HasUpdatedBody = false;
Richard Smith6ef42932014-03-20 21:02:00 +00004629 RecordData Record;
4630 for (auto &Update : DeclUpdate.second) {
4631 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4632
4633 Record.push_back(Kind);
4634 switch (Kind) {
4635 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4636 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4637 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004638 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004639 Record.push_back(GetDeclRef(Update.getDecl()));
4640 break;
4641
Richard Smith4d235792014-08-07 18:53:08 +00004642 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004643 // An updated body is emitted last, so that the reader doesn't need
4644 // to skip over the lazy body to reach statements for other records.
4645 Record.pop_back();
4646 HasUpdatedBody = true;
4647 break;
4648
Richard Smith4d235792014-08-07 18:53:08 +00004649 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4650 AddSourceLocation(Update.getLoc(), Record);
4651 break;
4652
John McCall32791cc2016-01-06 22:34:54 +00004653 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4654 AddStmt(const_cast<Expr*>(
4655 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4656 break;
4657
Richard Smithcd45dbc2014-04-19 03:48:30 +00004658 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4659 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004660 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004661 AddCXXDefinitionData(RD, Record);
4662 Record.push_back(WriteDeclContextLexicalBlock(
4663 *Context, const_cast<CXXRecordDecl *>(RD)));
4664
4665 // This state is sometimes updated by template instantiation, when we
4666 // switch from the specialization referring to the template declaration
4667 // to it referring to the template definition.
4668 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4669 Record.push_back(MSInfo->getTemplateSpecializationKind());
4670 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4671 } else {
4672 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4673 Record.push_back(Spec->getTemplateSpecializationKind());
4674 AddSourceLocation(Spec->getPointOfInstantiation(), Record);
Richard Smithdf352052014-05-22 20:59:29 +00004675
4676 // The instantiation might have been resolved to a partial
4677 // specialization. If so, record which one.
4678 auto From = Spec->getInstantiatedFrom();
4679 if (auto PartialSpec =
4680 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4681 Record.push_back(true);
4682 AddDeclRef(PartialSpec, Record);
4683 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4684 Record);
4685 } else {
4686 Record.push_back(false);
4687 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004688 }
4689 Record.push_back(RD->getTagKind());
4690 AddSourceLocation(RD->getLocation(), Record);
4691 AddSourceLocation(RD->getLocStart(), Record);
4692 AddSourceLocation(RD->getRBraceLoc(), Record);
4693
4694 // Instantiation may change attributes; write them all out afresh.
4695 Record.push_back(D->hasAttrs());
4696 if (Record.back())
Craig Topper8c2a2a02014-08-30 16:55:39 +00004697 WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
4698 D->getAttrs().size()), Record);
Richard Smithcd45dbc2014-04-19 03:48:30 +00004699
4700 // FIXME: Ensure we don't get here for explicit instantiations.
4701 break;
4702 }
4703
Richard Smithf8134002015-03-10 01:41:22 +00004704 case UPD_CXX_RESOLVED_DTOR_DELETE:
4705 AddDeclRef(Update.getDecl(), Record);
4706 break;
4707
Richard Smith564417a2014-03-20 21:47:22 +00004708 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4709 addExceptionSpec(
4710 *this,
4711 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4712 Record);
4713 break;
4714
Richard Smith6ef42932014-03-20 21:02:00 +00004715 case UPD_CXX_DEDUCED_RETURN_TYPE:
4716 Record.push_back(GetOrCreateTypeID(Update.getType()));
4717 break;
4718
4719 case UPD_DECL_MARKED_USED:
4720 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004721
4722 case UPD_MANGLING_NUMBER:
4723 case UPD_STATIC_LOCAL_NUMBER:
4724 Record.push_back(Update.getNumber());
4725 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004726
Alexey Bataev97720002014-11-11 04:05:39 +00004727 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4728 AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
4729 Record);
4730 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004731
4732 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004733 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004734 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004735
4736 case UPD_ADDED_ATTR_TO_RECORD:
4737 WriteAttributes(llvm::makeArrayRef(Update.getAttr()), Record);
4738 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004739 }
4740 }
4741
Richard Smithd28ac5b2014-03-22 23:33:22 +00004742 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004743 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004744 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004745 Record.push_back(Def->isInlined());
4746 AddSourceLocation(Def->getInnerLocStart(), Record);
4747 AddFunctionDefinition(Def, Record);
4748 }
4749
Richard Smithcd45dbc2014-04-19 03:48:30 +00004750 OffsetsRecord.push_back(GetDeclRef(D));
4751 OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4752
Richard Smith6ef42932014-03-20 21:02:00 +00004753 Stream.EmitRecord(DECL_UPDATES, Record);
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004754
Richard Smithc2bb8182015-03-24 06:36:48 +00004755 FlushPendingAfterDecl();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004756 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004757}
4758
Argyrios Kyrtzidis97bfda92010-10-24 17:26:43 +00004759void ASTWriter::WriteDeclReplacementsBlock() {
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004760 if (ReplacedDecls.empty())
4761 return;
4762
4763 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004764 for (const auto &I : ReplacedDecls) {
4765 Record.push_back(I.ID);
4766 Record.push_back(I.Offset);
4767 Record.push_back(I.Loc);
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004768 }
Sebastian Redl539c5062010-08-18 23:57:32 +00004769 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
Sebastian Redle7c1fe62010-08-13 00:28:03 +00004770}
4771
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004772void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004773 Record.push_back(Loc.getRawEncoding());
4774}
4775
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004776void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004777 AddSourceLocation(Range.getBegin(), Record);
4778 AddSourceLocation(Range.getEnd(), Record);
4779}
4780
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004781void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004782 Record.push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004783 const uint64_t *Words = Value.getRawData();
4784 Record.append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004785}
4786
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004787void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00004788 Record.push_back(Value.isUnsigned());
4789 AddAPInt(Value, Record);
4790}
4791
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004792void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00004793 AddAPInt(Value.bitcastToAPInt(), Record);
4794}
4795
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004796void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004797 Record.push_back(getIdentifierRef(II));
4798}
4799
Sebastian Redl539c5062010-08-18 23:57:32 +00004800IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004801 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004802 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004803
Sebastian Redl539c5062010-08-18 23:57:32 +00004804 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004805 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004806 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004807 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004808}
4809
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004810MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004811 // Don't emit builtin macros like __LINE__ to the AST file unless they
4812 // have been redefined by the header (in which case they are not
4813 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004814 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004815 return 0;
4816
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004817 MacroID &ID = MacroIDs[MI];
4818 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004819 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004820 MacroInfoToEmitData Info = { Name, MI, ID };
4821 MacroInfosToEmit.push_back(Info);
4822 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004823 return ID;
4824}
4825
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004826MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004827 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004828 return 0;
4829
4830 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4831 return MacroIDs[MI];
4832}
4833
4834uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004835 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004836}
4837
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004838void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004839 Record.push_back(getSelectorRef(SelRef));
4840}
4841
Sebastian Redl539c5062010-08-18 23:57:32 +00004842SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004843 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004844 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004845 }
4846
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004847 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004848 if (SID == 0 && Chain) {
4849 // This might trigger a ReadSelector callback, which will set the ID for
4850 // this selector.
4851 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004852 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004853 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004854 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004855 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004856 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004857 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004858 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004859}
4860
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004861void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnercba86142010-05-10 00:25:06 +00004862 AddDeclRef(Temp->getDestructor(), Record);
4863}
4864
Richard Smithc2bb8182015-03-24 06:36:48 +00004865void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4866 RecordDataImpl &Record) {
4867 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4868 CXXCtorInitializersToWrite.push_back(
4869 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4870 Record.push_back(NextCXXCtorInitializersID++);
4871}
4872
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004873void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
Richard Smithc2bb8182015-03-24 06:36:48 +00004874 CXXBaseSpecifier const *BasesEnd,
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004875 RecordDataImpl &Record) {
4876 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4877 CXXBaseSpecifiersToWrite.push_back(
4878 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4879 Bases, BasesEnd));
4880 Record.push_back(NextCXXBaseSpecifiersID++);
4881}
4882
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004883void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004884 const TemplateArgumentLocInfo &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004885 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004886 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004887 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004888 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004889 break;
4890 case TemplateArgument::Type:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004891 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
John McCall0ad16662009-10-29 08:12:44 +00004892 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004893 case TemplateArgument::Template:
Douglas Gregor9d802122011-03-02 17:09:35 +00004894 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004895 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004896 break;
4897 case TemplateArgument::TemplateExpansion:
Douglas Gregor9d802122011-03-02 17:09:35 +00004898 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004899 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregoreb29d182011-01-05 17:40:24 +00004900 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004901 break;
John McCall0ad16662009-10-29 08:12:44 +00004902 case TemplateArgument::Null:
4903 case TemplateArgument::Integral:
4904 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004905 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004906 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004907 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004908 break;
4909 }
4910}
4911
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004912void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004913 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004914 AddTemplateArgument(Arg.getArgument(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004915
4916 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4917 bool InfoHasSameExpr
4918 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4919 Record.push_back(InfoHasSameExpr);
4920 if (InfoHasSameExpr)
4921 return; // Avoid storing the same expr twice.
4922 }
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004923 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4924 Record);
4925}
4926
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004927void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4928 RecordDataImpl &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004929 if (!TInfo) {
John McCall8f115c62009-10-16 21:56:05 +00004930 AddTypeRef(QualType(), Record);
4931 return;
4932 }
4933
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004934 AddTypeLoc(TInfo->getTypeLoc(), Record);
4935}
4936
4937void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4938 AddTypeRef(TL.getType(), Record);
4939
John McCall8f115c62009-10-16 21:56:05 +00004940 TypeLocWriter TLW(*this, Record);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004941 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004942 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004943}
4944
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004945void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004946 Record.push_back(GetOrCreateTypeID(T));
4947}
4948
Richard Smith2095ffe2015-03-16 20:11:03 +00004949TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004950 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004951 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4952 if (T.isNull())
4953 return TypeIdx();
4954 assert(!T.getLocalFastQualifiers());
4955
4956 TypeIdx &Idx = TypeIdxs[T];
4957 if (Idx.getIndex() == 0) {
4958 if (DoneWritingDeclsAndTypes) {
4959 assert(0 && "New type seen after serializing all the types to emit!");
4960 return TypeIdx();
4961 }
4962
4963 // We haven't seen this type before. Assign it a new ID and put it
4964 // into the queue of types to emit.
4965 Idx = TypeIdx(NextTypeID++);
4966 DeclTypesToEmit.push(T);
4967 }
4968 return Idx;
4969 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004970}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004971
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004972TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004973 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004974 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4975 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004976 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004977 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004978
Richard Smith2095ffe2015-03-16 20:11:03 +00004979 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4980 assert(I != TypeIdxs.end() && "Type not emitted!");
4981 return I->second;
4982 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004983}
4984
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004985void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004986 Record.push_back(GetDeclRef(D));
4987}
4988
Sebastian Redl539c5062010-08-18 23:57:32 +00004989DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004990 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00004991
4992 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004993 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004994 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00004995
4996 // If D comes from an AST file, its declaration ID is already known and
4997 // fixed.
4998 if (D->isFromASTFile())
4999 return D->getGlobalID();
5000
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005001 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005002 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005003 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005004 if (DoneWritingDeclsAndTypes) {
5005 assert(0 && "New decl seen after serializing all the decls to emit!");
5006 return 0;
5007 }
5008
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005009 // We haven't seen this declaration before. Give it a new ID and
5010 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005011 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005012 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005013 }
5014
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005015 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005016}
5017
Sebastian Redl539c5062010-08-18 23:57:32 +00005018DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005019 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005020 return 0;
5021
Douglas Gregorb3163e52012-01-05 22:33:30 +00005022 // If D comes from an AST file, its declaration ID is already known and
5023 // fixed.
5024 if (D->isFromASTFile())
5025 return D->getGlobalID();
5026
Douglas Gregore84a9da2009-04-20 20:36:09 +00005027 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5028 return DeclIDs[D];
5029}
5030
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005031void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005032 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005033 assert(D);
5034
5035 SourceLocation Loc = D->getLocation();
5036 if (Loc.isInvalid())
5037 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005038
5039 // We only keep track of the file-level declarations of each file.
5040 if (!D->getLexicalDeclContext()->isFileContext())
5041 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005042 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5043 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005044 if (isa<ParmVarDecl>(D))
5045 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005046
5047 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005048 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005049 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005050 FileID FID;
5051 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005052 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005053 if (FID.isInvalid())
5054 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005055 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005056
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005057 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005058 if (!Info)
5059 Info = new DeclIDInFileInfo();
5060
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005061 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005062 LocDeclIDsTy &Decls = Info->DeclIDs;
5063
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005064 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005065 Decls.push_back(LocDecl);
5066 return;
5067 }
5068
Benjamin Kramer45025c02013-08-24 13:22:59 +00005069 LocDeclIDsTy::iterator I =
5070 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005071
5072 Decls.insert(I, LocDecl);
5073}
5074
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005075void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00005076 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005077 Record.push_back(Name.getNameKind());
5078 switch (Name.getNameKind()) {
5079 case DeclarationName::Identifier:
5080 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5081 break;
5082
5083 case DeclarationName::ObjCZeroArgSelector:
5084 case DeclarationName::ObjCOneArgSelector:
5085 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00005086 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005087 break;
5088
5089 case DeclarationName::CXXConstructorName:
5090 case DeclarationName::CXXDestructorName:
5091 case DeclarationName::CXXConversionFunctionName:
5092 AddTypeRef(Name.getCXXNameType(), Record);
5093 break;
5094
5095 case DeclarationName::CXXOperatorName:
5096 Record.push_back(Name.getCXXOverloadedOperator());
5097 break;
5098
Alexis Hunt3d221f22009-11-29 07:34:05 +00005099 case DeclarationName::CXXLiteralOperatorName:
5100 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5101 break;
5102
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005103 case DeclarationName::CXXUsingDirective:
5104 // No extra data to emit
5105 break;
5106 }
5107}
Chris Lattnerca025db2010-05-07 21:43:38 +00005108
Richard Smithd08aeb62014-08-28 01:33:39 +00005109unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5110 assert(needsAnonymousDeclarationNumber(D) &&
5111 "expected an anonymous declaration");
5112
5113 // Number the anonymous declarations within this context, if we've not
5114 // already done so.
5115 auto It = AnonymousDeclarationNumbers.find(D);
5116 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005117 auto *DC = D->getLexicalDeclContext();
5118 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5119 AnonymousDeclarationNumbers[ND] = Number;
5120 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005121
5122 It = AnonymousDeclarationNumbers.find(D);
5123 assert(It != AnonymousDeclarationNumbers.end() &&
5124 "declaration not found within its lexical context");
5125 }
5126
5127 return It->second;
5128}
5129
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005130void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005131 DeclarationName Name, RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005132 switch (Name.getNameKind()) {
5133 case DeclarationName::CXXConstructorName:
5134 case DeclarationName::CXXDestructorName:
5135 case DeclarationName::CXXConversionFunctionName:
5136 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5137 break;
5138
5139 case DeclarationName::CXXOperatorName:
5140 AddSourceLocation(
5141 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5142 Record);
5143 AddSourceLocation(
5144 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5145 Record);
5146 break;
5147
5148 case DeclarationName::CXXLiteralOperatorName:
5149 AddSourceLocation(
5150 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5151 Record);
5152 break;
5153
5154 case DeclarationName::Identifier:
5155 case DeclarationName::ObjCZeroArgSelector:
5156 case DeclarationName::ObjCOneArgSelector:
5157 case DeclarationName::ObjCMultiArgSelector:
5158 case DeclarationName::CXXUsingDirective:
5159 break;
5160 }
5161}
5162
5163void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005164 RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005165 AddDeclarationName(NameInfo.getName(), Record);
5166 AddSourceLocation(NameInfo.getLoc(), Record);
5167 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5168}
5169
5170void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005171 RecordDataImpl &Record) {
Douglas Gregor14454802011-02-25 02:25:35 +00005172 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005173 Record.push_back(Info.NumTemplParamLists);
5174 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5175 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5176}
5177
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005178void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005179 RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005180 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005181 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005182 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005183
5184 // Push each of the NNS's onto a stack for serialization in reverse order.
5185 while (NNS) {
5186 NestedNames.push_back(NNS);
5187 NNS = NNS->getPrefix();
5188 }
5189
5190 Record.push_back(NestedNames.size());
5191 while(!NestedNames.empty()) {
5192 NNS = NestedNames.pop_back_val();
5193 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5194 Record.push_back(Kind);
5195 switch (Kind) {
5196 case NestedNameSpecifier::Identifier:
5197 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5198 break;
5199
5200 case NestedNameSpecifier::Namespace:
5201 AddDeclRef(NNS->getAsNamespace(), Record);
5202 break;
5203
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005204 case NestedNameSpecifier::NamespaceAlias:
5205 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5206 break;
5207
Chris Lattnerca025db2010-05-07 21:43:38 +00005208 case NestedNameSpecifier::TypeSpec:
5209 case NestedNameSpecifier::TypeSpecWithTemplate:
5210 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5211 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5212 break;
5213
5214 case NestedNameSpecifier::Global:
5215 // Don't need to write an associated value.
5216 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005217
5218 case NestedNameSpecifier::Super:
5219 AddDeclRef(NNS->getAsRecordDecl(), Record);
5220 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005221 }
5222 }
5223}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005224
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005225void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5226 RecordDataImpl &Record) {
5227 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005228 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005229 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005230
5231 // Push each of the nested-name-specifiers's onto a stack for
5232 // serialization in reverse order.
5233 while (NNS) {
5234 NestedNames.push_back(NNS);
5235 NNS = NNS.getPrefix();
5236 }
5237
5238 Record.push_back(NestedNames.size());
5239 while(!NestedNames.empty()) {
5240 NNS = NestedNames.pop_back_val();
5241 NestedNameSpecifier::SpecifierKind Kind
5242 = NNS.getNestedNameSpecifier()->getKind();
5243 Record.push_back(Kind);
5244 switch (Kind) {
5245 case NestedNameSpecifier::Identifier:
5246 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5247 AddSourceRange(NNS.getLocalSourceRange(), Record);
5248 break;
5249
5250 case NestedNameSpecifier::Namespace:
5251 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5252 AddSourceRange(NNS.getLocalSourceRange(), Record);
5253 break;
5254
5255 case NestedNameSpecifier::NamespaceAlias:
5256 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5257 AddSourceRange(NNS.getLocalSourceRange(), Record);
5258 break;
5259
5260 case NestedNameSpecifier::TypeSpec:
5261 case NestedNameSpecifier::TypeSpecWithTemplate:
5262 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5263 AddTypeLoc(NNS.getTypeLoc(), Record);
5264 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5265 break;
5266
5267 case NestedNameSpecifier::Global:
5268 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5269 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005270
5271 case NestedNameSpecifier::Super:
5272 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
5273 AddSourceRange(NNS.getLocalSourceRange(), Record);
5274 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005275 }
5276 }
5277}
5278
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005279void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005280 TemplateName::NameKind Kind = Name.getKind();
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005281 Record.push_back(Kind);
5282 switch (Kind) {
5283 case TemplateName::Template:
5284 AddDeclRef(Name.getAsTemplateDecl(), Record);
5285 break;
5286
5287 case TemplateName::OverloadedTemplate: {
5288 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5289 Record.push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005290 for (const auto &I : *OvT)
5291 AddDeclRef(I, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005292 break;
5293 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005294
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005295 case TemplateName::QualifiedTemplate: {
5296 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5297 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5298 Record.push_back(QualT->hasTemplateKeyword());
5299 AddDeclRef(QualT->getTemplateDecl(), Record);
5300 break;
5301 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005302
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005303 case TemplateName::DependentTemplate: {
5304 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5305 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5306 Record.push_back(DepT->isIdentifier());
5307 if (DepT->isIdentifier())
5308 AddIdentifierRef(DepT->getIdentifier(), Record);
5309 else
5310 Record.push_back(DepT->getOperator());
5311 break;
5312 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005313
5314 case TemplateName::SubstTemplateTemplateParm: {
5315 SubstTemplateTemplateParmStorage *subst
5316 = Name.getAsSubstTemplateTemplateParm();
5317 AddDeclRef(subst->getParameter(), Record);
5318 AddTemplateName(subst->getReplacement(), Record);
5319 break;
5320 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005321
5322 case TemplateName::SubstTemplateTemplateParmPack: {
5323 SubstTemplateTemplateParmPackStorage *SubstPack
5324 = Name.getAsSubstTemplateTemplateParmPack();
5325 AddDeclRef(SubstPack->getParameterPack(), Record);
5326 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5327 break;
5328 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005329 }
5330}
5331
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005332void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005333 RecordDataImpl &Record) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005334 Record.push_back(Arg.getKind());
5335 switch (Arg.getKind()) {
5336 case TemplateArgument::Null:
5337 break;
5338 case TemplateArgument::Type:
5339 AddTypeRef(Arg.getAsType(), Record);
5340 break;
5341 case TemplateArgument::Declaration:
5342 AddDeclRef(Arg.getAsDecl(), Record);
David Blaikie952a9b12014-10-17 18:00:12 +00005343 AddTypeRef(Arg.getParamTypeForDecl(), Record);
Eli Friedmanb826a002012-09-26 02:36:12 +00005344 break;
5345 case TemplateArgument::NullPtr:
5346 AddTypeRef(Arg.getNullPtrType(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005347 break;
5348 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005349 AddAPSInt(Arg.getAsIntegral(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005350 AddTypeRef(Arg.getIntegralType(), Record);
5351 break;
5352 case TemplateArgument::Template:
Douglas Gregore1d60df2011-01-14 23:41:42 +00005353 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5354 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005355 case TemplateArgument::TemplateExpansion:
5356 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +00005357 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Douglas Gregore1d60df2011-01-14 23:41:42 +00005358 Record.push_back(*NumExpansions + 1);
5359 else
5360 Record.push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005361 break;
5362 case TemplateArgument::Expression:
5363 AddStmt(Arg.getAsExpr());
5364 break;
5365 case TemplateArgument::Pack:
5366 Record.push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005367 for (const auto &P : Arg.pack_elements())
5368 AddTemplateArgument(P, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005369 break;
5370 }
5371}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005372
5373void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005374ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005375 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005376 assert(TemplateParams && "No TemplateParams!");
5377 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5378 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5379 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5380 Record.push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005381 for (const auto &P : *TemplateParams)
5382 AddDeclRef(P, Record);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005383}
5384
5385/// \brief Emit a template argument list.
5386void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005387ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005388 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005389 assert(TemplateArgs && "No TemplateArgs!");
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005390 Record.push_back(TemplateArgs->size());
5391 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005392 AddTemplateArgument(TemplateArgs->get(i), Record);
5393}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005394
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005395void
5396ASTWriter::AddASTTemplateArgumentListInfo
5397(const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5398 assert(ASTTemplArgList && "No ASTTemplArgList!");
5399 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5400 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5401 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5402 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5403 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5404 AddTemplateArgumentLoc(TemplArgs[i], Record);
5405}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005406
5407void
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005408ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005409 Record.push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005410 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005411 I = Set.begin(), E = Set.end(); I != E; ++I) {
5412 AddDeclRef(I.getDecl(), Record);
5413 Record.push_back(I.getAccess());
5414 }
5415}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005416
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005417void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005418 RecordDataImpl &Record) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005419 Record.push_back(Base.isVirtual());
5420 Record.push_back(Base.isBaseOfClass());
5421 Record.push_back(Base.getAccessSpecifierAsWritten());
Sebastian Redl08905022011-02-05 19:23:19 +00005422 Record.push_back(Base.getInheritConstructors());
Nick Lewycky19b9f952010-07-26 16:56:01 +00005423 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005424 AddSourceRange(Base.getSourceRange(), Record);
Douglas Gregor752a5952011-01-03 22:36:02 +00005425 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5426 : SourceLocation(),
5427 Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005428}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005429
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005430void ASTWriter::FlushCXXBaseSpecifiers() {
5431 RecordData Record;
Richard Smithc2bb8182015-03-24 06:36:48 +00005432 unsigned N = CXXBaseSpecifiersToWrite.size();
5433 for (unsigned I = 0; I != N; ++I) {
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005434 Record.clear();
5435
5436 // Record the offset of this base-specifier set.
Douglas Gregorc27b2872011-08-04 00:01:48 +00005437 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005438 if (Index == CXXBaseSpecifiersOffsets.size())
5439 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5440 else {
5441 if (Index > CXXBaseSpecifiersOffsets.size())
5442 CXXBaseSpecifiersOffsets.resize(Index + 1);
5443 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5444 }
5445
5446 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5447 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5448 Record.push_back(BEnd - B);
5449 for (; B != BEnd; ++B)
5450 AddCXXBaseSpecifier(*B, Record);
5451 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
Douglas Gregord5853042010-10-30 04:28:16 +00005452
5453 // Flush any expressions that were written as part of the base specifiers.
5454 FlushStmts();
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005455 }
5456
Richard Smithc2bb8182015-03-24 06:36:48 +00005457 assert(N == CXXBaseSpecifiersToWrite.size() &&
5458 "added more base specifiers while writing base specifiers");
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005459 CXXBaseSpecifiersToWrite.clear();
5460}
5461
Alexis Hunt1d792652011-01-08 20:30:50 +00005462void ASTWriter::AddCXXCtorInitializers(
5463 const CXXCtorInitializer * const *CtorInitializers,
5464 unsigned NumCtorInitializers,
5465 RecordDataImpl &Record) {
5466 Record.push_back(NumCtorInitializers);
5467 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5468 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005469
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005470 if (Init->isBaseInitializer()) {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005471 Record.push_back(CTOR_INITIALIZER_BASE);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005472 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005473 Record.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005474 } else if (Init->isDelegatingInitializer()) {
5475 Record.push_back(CTOR_INITIALIZER_DELEGATING);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005476 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005477 } else if (Init->isMemberInitializer()){
5478 Record.push_back(CTOR_INITIALIZER_MEMBER);
5479 AddDeclRef(Init->getMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005480 } else {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005481 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5482 AddDeclRef(Init->getIndirectMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005483 }
Francois Pichetd583da02010-12-04 09:14:42 +00005484
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005485 AddSourceLocation(Init->getMemberLocation(), Record);
5486 AddStmt(Init->getInit());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005487 AddSourceLocation(Init->getLParenLoc(), Record);
5488 AddSourceLocation(Init->getRParenLoc(), Record);
5489 Record.push_back(Init->isWritten());
5490 if (Init->isWritten()) {
5491 Record.push_back(Init->getSourceOrder());
5492 } else {
5493 Record.push_back(Init->getNumArrayIndices());
5494 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5495 AddDeclRef(Init->getArrayIndex(i), Record);
5496 }
5497 }
5498}
5499
Richard Smithc2bb8182015-03-24 06:36:48 +00005500void ASTWriter::FlushCXXCtorInitializers() {
5501 RecordData Record;
5502
5503 unsigned N = CXXCtorInitializersToWrite.size();
Daniel Jasperc77b0a12015-03-24 08:06:38 +00005504 (void)N; // Silence unused warning in non-assert builds.
Richard Smithc2bb8182015-03-24 06:36:48 +00005505 for (auto &Init : CXXCtorInitializersToWrite) {
5506 Record.clear();
5507
5508 // Record the offset of this mem-initializer list.
5509 unsigned Index = Init.ID - 1;
5510 if (Index == CXXCtorInitializersOffsets.size())
5511 CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5512 else {
5513 if (Index > CXXCtorInitializersOffsets.size())
5514 CXXCtorInitializersOffsets.resize(Index + 1);
5515 CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5516 }
5517
5518 AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5519 Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5520
5521 // Flush any expressions that were written as part of the initializers.
5522 FlushStmts();
5523 }
5524
5525 assert(N == CXXCtorInitializersToWrite.size() &&
5526 "added more ctor initializers while writing ctor initializers");
5527 CXXCtorInitializersToWrite.clear();
5528}
5529
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005530void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
Richard Smith053f6c62014-05-16 23:01:30 +00005531 auto &Data = D->data();
Douglas Gregor99ae8062012-02-14 17:54:36 +00005532 Record.push_back(Data.IsLambda);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005533 Record.push_back(Data.UserDeclaredConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005534 Record.push_back(Data.UserDeclaredSpecialMembers);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005535 Record.push_back(Data.Aggregate);
5536 Record.push_back(Data.PlainOldData);
5537 Record.push_back(Data.Empty);
5538 Record.push_back(Data.Polymorphic);
5539 Record.push_back(Data.Abstract);
Chandler Carruth583edf82011-04-30 10:07:30 +00005540 Record.push_back(Data.IsStandardLayout);
Chandler Carruthb1963742011-04-30 09:17:45 +00005541 Record.push_back(Data.HasNoNonEmptyBases);
5542 Record.push_back(Data.HasPrivateFields);
5543 Record.push_back(Data.HasProtectedFields);
5544 Record.push_back(Data.HasPublicFields);
Douglas Gregor61226d32011-05-13 01:05:07 +00005545 Record.push_back(Data.HasMutableFields);
Richard Smithab44d5b2013-12-10 08:25:00 +00005546 Record.push_back(Data.HasVariantMembers);
Richard Smith561fb152012-02-25 07:33:38 +00005547 Record.push_back(Data.HasOnlyCMembers);
Richard Smithe2648ba2012-05-07 01:07:30 +00005548 Record.push_back(Data.HasInClassInitializer);
Richard Smith593f9932012-12-08 02:01:17 +00005549 Record.push_back(Data.HasUninitializedReferenceMember);
Nico Weber6a6376b2016-02-19 01:52:46 +00005550 Record.push_back(Data.HasUninitializedFields);
Richard Smith6b02d462012-12-08 08:32:28 +00005551 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5552 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5553 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5554 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5555 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5556 Record.push_back(Data.DefaultedDestructorIsDeleted);
Richard Smith328aae52012-11-30 05:11:39 +00005557 Record.push_back(Data.HasTrivialSpecialMembers);
Richard Smithb45a6f72014-04-17 20:33:01 +00005558 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
Richard Smith328aae52012-11-30 05:11:39 +00005559 Record.push_back(Data.HasIrrelevantDestructor);
Richard Smith111af8d2011-08-10 18:11:37 +00005560 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
Richard Smith561fb152012-02-25 07:33:38 +00005561 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
Richard Smith561fb152012-02-25 07:33:38 +00005562 Record.push_back(Data.HasConstexprDefaultConstructor);
Chandler Carruthe71d0622011-04-24 02:49:34 +00005563 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005564 Record.push_back(Data.ComputedVisibleConversions);
Alexis Huntea6f0322011-05-11 22:34:38 +00005565 Record.push_back(Data.UserProvidedDefaultConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005566 Record.push_back(Data.DeclaredSpecialMembers);
Richard Smith1c33fe82012-11-28 06:23:12 +00005567 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5568 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5569 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5570 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005571 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005572
5573 Record.push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005574 if (Data.NumBases > 0)
5575 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5576 Record);
5577
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005578 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5579 Record.push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005580 if (Data.NumVBases > 0)
5581 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5582 Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005583
Richard Smitha4ba74c2013-08-30 04:46:40 +00005584 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5585 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005586 // Data.Definition is the owning decl, no need to write it.
Richard Smith68ad0e72013-06-26 02:41:25 +00005587 AddDeclRef(D->getFirstFriend(), Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005588
5589 // Add lambda-specific data.
5590 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005591 auto &Lambda = D->getLambdaData();
Douglas Gregor680e9e02012-02-21 19:11:17 +00005592 Record.push_back(Lambda.Dependent);
Faisal Valic1a6dc42013-10-23 16:10:50 +00005593 Record.push_back(Lambda.IsGenericLambda);
5594 Record.push_back(Lambda.CaptureDefault);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005595 Record.push_back(Lambda.NumCaptures);
5596 Record.push_back(Lambda.NumExplicitCaptures);
Douglas Gregor63798542012-02-20 19:44:39 +00005597 Record.push_back(Lambda.ManglingNumber);
Douglas Gregor7fcbd902012-02-21 00:37:24 +00005598 AddDeclRef(Lambda.ContextDecl, Record);
Eli Friedmand564afb2012-09-19 01:18:11 +00005599 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005600 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005601 const LambdaCapture &Capture = Lambda.Captures[I];
Douglas Gregor99ae8062012-02-14 17:54:36 +00005602 AddSourceLocation(Capture.getLocation(), Record);
5603 Record.push_back(Capture.isImplicit());
Richard Smithba71c082013-05-16 06:20:58 +00005604 Record.push_back(Capture.getCaptureKind());
5605 switch (Capture.getCaptureKind()) {
5606 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005607 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005608 break;
5609 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005610 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005611 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005612 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smithba71c082013-05-16 06:20:58 +00005613 AddDeclRef(Var, Record);
5614 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5615 : SourceLocation(),
5616 Record);
5617 break;
5618 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005619 }
5620 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005621}
5622
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005623void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005624 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005625 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005626 assert(FirstDeclID == NextDeclID &&
5627 FirstTypeID == NextTypeID &&
5628 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005629 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005630 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005631 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005632 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005633
Sebastian Redl07a89a82010-07-30 00:29:29 +00005634 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005635
Richard Smith7f330cd2015-03-18 01:42:29 +00005636 // Note, this will get called multiple times, once one the reader starts up
5637 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005638 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5639 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5640 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005641 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005642 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005643 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005644 NextDeclID = FirstDeclID;
5645 NextTypeID = FirstTypeID;
5646 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005647 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005648 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005649 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005650}
5651
Sebastian Redl539c5062010-08-18 23:57:32 +00005652void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005653 // Always keep the highest ID. See \p TypeRead() for more information.
5654 IdentID &StoredID = IdentifierIDs[II];
5655 if (ID > StoredID)
5656 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005657}
5658
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005659void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005660 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005661 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005662 if (ID > StoredID)
5663 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005664}
5665
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005666void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005667 // Always take the highest-numbered type index. This copes with an interesting
5668 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005669 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005670 // keep the higher-numbered entry so that we can properly write it out to
5671 // the AST file.
5672 TypeIdx &StoredIdx = TypeIdxs[T];
5673 if (Idx.getIndex() >= StoredIdx.getIndex())
5674 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005675}
5676
Sebastian Redl539c5062010-08-18 23:57:32 +00005677void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005678 // Always keep the highest ID. See \p TypeRead() for more information.
5679 SelectorID &StoredID = SelectorIDs[S];
5680 if (ID > StoredID)
5681 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005682}
Douglas Gregor91096292010-10-02 19:29:26 +00005683
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005684void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005685 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005686 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005687 MacroDefinitions[MD] = ID;
5688}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005689
Douglas Gregore37a85a2011-12-02 17:30:13 +00005690void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5691 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5692 SubmoduleIDs[Mod] = ID;
5693}
5694
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005695void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005696 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005697 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005698 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005699 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005700 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005701 // A forward reference was mutated into a definition. Rewrite it.
5702 // FIXME: This happens during template instantiation, should we
5703 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005704 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5705 "completed a tag from another module but not by instantiation?");
5706 DeclUpdates[RD].push_back(
5707 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005708 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005709 }
5710}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005711
Richard Smithf983f7f2015-10-13 00:23:25 +00005712static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5713 if (D->isFromASTFile())
5714 return true;
5715
5716 // If we've not loaded any modules, this can't be imported.
5717 if (!Chain || !Chain->getModuleManager().size())
5718 return false;
5719
5720 // The predefined __va_list_tag struct is imported if we imported any decls.
5721 // FIXME: This is a gross hack.
5722 return D == D->getASTContext().getVaListTagDecl();
5723}
5724
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005725void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5726 // TU and namespaces are handled elsewhere.
5727 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5728 return;
5729
Richard Smithf983f7f2015-10-13 00:23:25 +00005730 // We're only interested in cases where a local declaration is added to an
5731 // imported context.
5732 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5733 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005734
Richard Smith0f4e2c42015-08-06 04:23:48 +00005735 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005736 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005737 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005738 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5739 // We're adding a visible declaration to a predefined decl context. Ensure
5740 // that we write out all of its lookup results so we don't get a nasty
5741 // surprise when we try to emit its lookup table.
5742 for (auto *Child : DC->decls())
5743 UpdatingVisibleDecls.push_back(Child);
5744 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005745 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005746}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005747
5748void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5749 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005750
5751 // We're only interested in cases where a local declaration is added to an
5752 // imported context.
5753 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5754 return;
5755
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005756 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005757 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005758
5759 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005760 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005761 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005762 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005763}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005764
Richard Smith564417a2014-03-20 21:47:22 +00005765void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005766 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5767 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005768 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005769 // If we don't already know the exception specification for this redecl
5770 // chain, add an update record for it.
5771 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5772 ->getType()
5773 ->castAs<FunctionProtoType>()
5774 ->getExceptionSpecType()))
5775 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5776 });
Richard Smith564417a2014-03-20 21:47:22 +00005777}
5778
Richard Smith1fa5d642013-05-11 05:45:24 +00005779void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5780 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005781 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005782 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005783 DeclUpdates[D].push_back(
5784 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5785 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005786}
5787
Richard Smithf8134002015-03-10 01:41:22 +00005788void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5789 const FunctionDecl *Delete) {
5790 assert(!WritingAST && "Already writing the AST!");
5791 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005792 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005793 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005794 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5795 });
Richard Smithf8134002015-03-10 01:41:22 +00005796}
5797
Sebastian Redlab238a72011-04-24 16:28:06 +00005798void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005799 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005800 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005801 return; // Declaration not imported from PCH.
5802
Richard Smith4d235792014-08-07 18:53:08 +00005803 // Implicit function decl from a PCH was defined.
5804 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005805}
5806
Richard Smithd28ac5b2014-03-22 23:33:22 +00005807void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5808 assert(!WritingAST && "Already writing the AST!");
5809 if (!D->isFromASTFile())
5810 return;
5811
Richard Smith9e2341d2015-03-23 03:25:59 +00005812 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005813}
5814
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005815void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005816 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005817 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005818 return;
5819
5820 // Since the actual instantiation is delayed, this really means that we need
5821 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005822 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005823 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5824 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005825}
5826
John McCall32791cc2016-01-06 22:34:54 +00005827void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5828 assert(!WritingAST && "Already writing the AST!");
5829 if (!D->isFromASTFile())
5830 return;
5831
5832 DeclUpdates[D].push_back(
5833 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5834}
5835
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005836void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5837 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005838 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005839 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005840 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005841
5842 assert(IFD->getDefinition() && "Category on a class without a definition?");
5843 ObjCClassesWithCategories.insert(
5844 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005845}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005846
Eli Friedman276dd182013-09-05 00:02:25 +00005847void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5848 assert(!WritingAST && "Already writing the AST!");
5849 if (!D->isFromASTFile())
5850 return;
5851
Aaron Ballman4f45b712014-03-21 15:22:56 +00005852 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005853}
Alexey Bataev97720002014-11-11 04:05:39 +00005854
5855void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5856 assert(!WritingAST && "Already writing the AST!");
5857 if (!D->isFromASTFile())
5858 return;
5859
5860 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5861}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005862
Richard Smith4caa4492015-05-15 02:34:32 +00005863void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00005864 assert(!WritingAST && "Already writing the AST!");
5865 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005866 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005867}
Alex Denisovfde64952015-06-26 05:28:36 +00005868
5869void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5870 const RecordDecl *Record) {
5871 assert(!WritingAST && "Already writing the AST!");
5872 if (!Record->isFromASTFile())
5873 return;
5874 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5875}