blob: 30b4a3ebe2ef3d74c9fdfe83e524b87f014b612f [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
Richard Smith290d8012016-04-06 17:06:00 +000085namespace clang {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000086 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000087 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +000088 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
Douglas Gregoref84c4b2009-04-09 22:27:44 +000090 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000091 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000092 /// \brief Abbreviation to use for the record, if any.
93 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000094
Richard Smith290d8012016-04-06 17:06:00 +000095 public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000096 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Richard Smith290d8012016-04-06 17:06:00 +000097 : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
98
99 uint64_t Emit() {
100 return Record.Emit(Code, AbbrevToUse);
101 }
102
103 void Visit(QualType T) {
104 if (T.hasLocalNonFastQualifiers()) {
105 Qualifiers Qs = T.getLocalQualifiers();
106 Record.AddTypeRef(T.getLocalUnqualifiedType());
107 Record.push_back(Qs.getAsOpaqueValue());
108 Code = TYPE_EXT_QUAL;
109 AbbrevToUse = Writer.TypeExtQualAbbrev;
110 } else {
111 switch (T->getTypeClass()) {
112 // For all of the concrete, non-dependent types, call the
113 // appropriate visitor function.
114#define TYPE(Class, Base) \
115 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
116#define ABSTRACT_TYPE(Class, Base)
117#include "clang/AST/TypeNodes.def"
118 }
119 }
120 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000121
122 void VisitArrayType(const ArrayType *T);
123 void VisitFunctionType(const FunctionType *T);
124 void VisitTagType(const TagType *T);
125
126#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
127#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000128#include "clang/AST/TypeNodes.def"
129 };
Richard Smith290d8012016-04-06 17:06:00 +0000130} // end namespace clang
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000132void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000133 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000134}
135
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000136void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000137 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000138 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000139}
140
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000141void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000142 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000143 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000144}
145
Reid Kleckner8a365022013-06-24 17:51:48 +0000146void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000147 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000148 Code = TYPE_DECAYED;
149}
150
Reid Kleckner0503a872013-12-05 01:23:43 +0000151void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000152 Record.AddTypeRef(T->getOriginalType());
153 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000154 Code = TYPE_ADJUSTED;
155}
156
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000157void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000158 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000159 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000163 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000164 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000165 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166}
167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000168void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000169 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000170 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000171}
172
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000173void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000174 Record.AddTypeRef(T->getPointeeType());
175 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000176 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000177}
178
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000179void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000180 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000181 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000182 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000183}
184
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000185void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000186 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000187 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000188 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189}
190
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000191void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000192 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000193 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000194}
195
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000196void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000197 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000198 Record.AddSourceLocation(T->getLBracketLoc());
199 Record.AddSourceLocation(T->getRBracketLoc());
Richard Smith290d8012016-04-06 17:06:00 +0000200 Record.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000201 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000202}
203
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000204void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000205 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000206 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000207 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000208 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000209}
210
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000211void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000212 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000213 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000214}
215
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000216void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000217 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000218 FunctionType::ExtInfo C = T->getExtInfo();
219 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000220 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000221 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000222 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000223 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000224 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000225
226 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
227 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000228}
229
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000230void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000231 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000232 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000233}
234
Richard Smith290d8012016-04-06 17:06:00 +0000235static void addExceptionSpec(const FunctionProtoType *T,
236 ASTRecordWriter &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000237 Record.push_back(T->getExceptionSpecType());
238 if (T->getExceptionSpecType() == EST_Dynamic) {
239 Record.push_back(T->getNumExceptions());
240 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000241 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000242 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smith290d8012016-04-06 17:06:00 +0000243 Record.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000244 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000245 Record.AddDeclRef(T->getExceptionSpecDecl());
246 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000247 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000248 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000249 }
Richard Smith564417a2014-03-20 21:47:22 +0000250}
251
252void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
253 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000254
Richard Smith564417a2014-03-20 21:47:22 +0000255 Record.push_back(T->isVariadic());
256 Record.push_back(T->hasTrailingReturn());
257 Record.push_back(T->getTypeQuals());
258 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Richard Smith290d8012016-04-06 17:06:00 +0000259 addExceptionSpec(T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000260
261 Record.push_back(T->getNumParams());
262 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000263 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000264
John McCall18afab72016-03-01 00:49:02 +0000265 if (T->hasExtParameterInfos()) {
266 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
267 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
268 }
269
Richard Smith01b2cb42014-07-26 06:37:51 +0000270 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000271 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
272 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000273 AbbrevToUse = 0;
274
Sebastian Redl539c5062010-08-18 23:57:32 +0000275 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000276}
277
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000278void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000279 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000280 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000281}
John McCallb96ec562009-12-04 22:46:56 +0000282
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000283void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000284 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000285 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000286 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000287 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000288}
289
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000290void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Richard Smith290d8012016-04-06 17:06:00 +0000291 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000292 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000293}
294
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000295void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000296 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000297 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000298}
299
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000300void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000301 Record.AddTypeRef(T->getUnderlyingType());
Richard Smith290d8012016-04-06 17:06:00 +0000302 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000303 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000304}
305
Alexis Hunte852b102011-05-24 22:41:36 +0000306void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000307 Record.AddTypeRef(T->getBaseType());
308 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000309 Record.push_back(T->getUTTKind());
310 Code = TYPE_UNARY_TRANSFORM;
311}
312
Richard Smith30482bc2011-02-20 03:19:35 +0000313void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000314 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000315 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000316 if (T->getDeducedType().isNull())
317 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000318 Code = TYPE_AUTO;
319}
320
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000321void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000322 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000323 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000324 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000325 "Cannot serialize in the middle of a type definition");
326}
327
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000328void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000329 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000330 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000331}
332
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000333void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000334 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000335 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000336}
337
John McCall81904512011-01-06 01:58:22 +0000338void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000339 Record.AddTypeRef(T->getModifiedType());
340 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000341 Record.push_back(T->getAttrKind());
342 Code = TYPE_ATTRIBUTED;
343}
344
Mike Stump11289f42009-09-09 15:08:12 +0000345void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000346ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000347 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000348 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
349 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000350 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000351}
352
353void
Douglas Gregorada4b792011-01-14 02:55:32 +0000354ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
355 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000356 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
357 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000358 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
359}
360
361void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000362ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000363 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000364 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000365 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000366 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000367 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000368 Record.AddTemplateArgument(ArgI);
369 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
370 : T->isCanonicalUnqualified()
371 ? QualType()
372 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000373 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000374}
375
376void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000377ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000378 VisitArrayType(T);
Richard Smith290d8012016-04-06 17:06:00 +0000379 Record.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000380 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000381 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000382}
383
384void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000385ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000386 const DependentSizedExtVectorType *T) {
387 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000388 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000389}
390
391void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000392ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000393 Record.push_back(T->getDepth());
394 Record.push_back(T->getIndex());
395 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000396 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000397 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000398}
399
400void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000401ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000402 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000403 Record.AddNestedNameSpecifier(T->getQualifier());
404 Record.AddIdentifierRef(T->getIdentifier());
405 Record.AddTypeRef(
406 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000407 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000408}
409
410void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000411ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000412 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000413 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000414 Record.AddNestedNameSpecifier(T->getQualifier());
415 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000416 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000417 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000418 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000419 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000420}
421
Douglas Gregord2fa7662010-12-20 02:24:11 +0000422void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000423 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000424 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000425 Record.push_back(*NumExpansions + 1);
426 else
427 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000428 Code = TYPE_PACK_EXPANSION;
429}
430
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000431void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000432 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000433 Code = TYPE_PAREN;
434}
435
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000436void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000437 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddNestedNameSpecifier(T->getQualifier());
439 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000440 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000441}
442
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000443void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000444 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
445 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000446 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000447}
448
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000449void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000450 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000451 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000452}
453
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000454void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000455 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000456 Record.push_back(T->getTypeArgsAsWritten().size());
457 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000458 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000459 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000460 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000461 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000462 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000463 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000464}
465
Steve Narofffb4330f2009-06-17 22:40:22 +0000466void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000467ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000468 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000469 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000470}
471
Eli Friedman0dfb8892011-10-06 23:00:33 +0000472void
473ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000474 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000475 Code = TYPE_ATOMIC;
476}
477
Xiuli Pan9c14e282016-01-09 12:53:17 +0000478void
479ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000480 Record.AddTypeRef(T->getElementType());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000481 Code = TYPE_PIPE;
482}
483
John McCall8f115c62009-10-16 21:56:05 +0000484namespace {
485
486class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000487 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000488
489public:
Richard Smith290d8012016-04-06 17:06:00 +0000490 TypeLocWriter(ASTRecordWriter &Record)
491 : Record(Record) { }
John McCall8f115c62009-10-16 21:56:05 +0000492
John McCall17001972009-10-18 01:05:36 +0000493#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000494#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000495 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000496#include "clang/AST/TypeLocNodes.def"
497
John McCall17001972009-10-18 01:05:36 +0000498 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
499 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000500};
501
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000502} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000503
John McCall17001972009-10-18 01:05:36 +0000504void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
505 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000506}
John McCall17001972009-10-18 01:05:36 +0000507void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000508 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000509 if (TL.needsExtraLocalData()) {
510 Record.push_back(TL.getWrittenTypeSpec());
511 Record.push_back(TL.getWrittenSignSpec());
512 Record.push_back(TL.getWrittenWidthSpec());
513 Record.push_back(TL.hasModeAttr());
514 }
John McCall8f115c62009-10-16 21:56:05 +0000515}
John McCall17001972009-10-18 01:05:36 +0000516void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000517 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000518}
John McCall17001972009-10-18 01:05:36 +0000519void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000520 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000521}
Reid Kleckner8a365022013-06-24 17:51:48 +0000522void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
523 // nothing to do
524}
Reid Kleckner0503a872013-12-05 01:23:43 +0000525void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
526 // nothing to do
527}
John McCall17001972009-10-18 01:05:36 +0000528void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000529 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000530}
John McCall17001972009-10-18 01:05:36 +0000531void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000532 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000533}
John McCall17001972009-10-18 01:05:36 +0000534void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000535 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000536}
John McCall17001972009-10-18 01:05:36 +0000537void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000538 Record.AddSourceLocation(TL.getStarLoc());
539 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000540}
John McCall17001972009-10-18 01:05:36 +0000541void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000542 Record.AddSourceLocation(TL.getLBracketLoc());
543 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000544 Record.push_back(TL.getSizeExpr() ? 1 : 0);
545 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000546 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000547}
John McCall17001972009-10-18 01:05:36 +0000548void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
549 VisitArrayTypeLoc(TL);
550}
551void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
552 VisitArrayTypeLoc(TL);
553}
554void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
555 VisitArrayTypeLoc(TL);
556}
557void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
558 DependentSizedArrayTypeLoc TL) {
559 VisitArrayTypeLoc(TL);
560}
561void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
562 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000563 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000564}
565void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000566 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000567}
568void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000569 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000570}
571void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000572 Record.AddSourceLocation(TL.getLocalRangeBegin());
573 Record.AddSourceLocation(TL.getLParenLoc());
574 Record.AddSourceLocation(TL.getRParenLoc());
575 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000576 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000577 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000578}
579void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
580 VisitFunctionTypeLoc(TL);
581}
582void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
583 VisitFunctionTypeLoc(TL);
584}
John McCallb96ec562009-12-04 22:46:56 +0000585void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000586 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000587}
John McCall17001972009-10-18 01:05:36 +0000588void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000589 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000590}
591void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000592 Record.AddSourceLocation(TL.getTypeofLoc());
593 Record.AddSourceLocation(TL.getLParenLoc());
594 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000595}
596void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000597 Record.AddSourceLocation(TL.getTypeofLoc());
598 Record.AddSourceLocation(TL.getLParenLoc());
599 Record.AddSourceLocation(TL.getRParenLoc());
600 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000601}
602void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000603 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000604}
Alexis Hunte852b102011-05-24 22:41:36 +0000605void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000606 Record.AddSourceLocation(TL.getKWLoc());
607 Record.AddSourceLocation(TL.getLParenLoc());
608 Record.AddSourceLocation(TL.getRParenLoc());
609 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000610}
Richard Smith30482bc2011-02-20 03:19:35 +0000611void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000612 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000613}
John McCall17001972009-10-18 01:05:36 +0000614void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000615 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000616}
617void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000618 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000619}
John McCall81904512011-01-06 01:58:22 +0000620void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000621 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000622 if (TL.hasAttrOperand()) {
623 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000624 Record.AddSourceLocation(range.getBegin());
625 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000626 }
627 if (TL.hasAttrExprOperand()) {
628 Expr *operand = TL.getAttrExprOperand();
629 Record.push_back(operand ? 1 : 0);
Richard Smith290d8012016-04-06 17:06:00 +0000630 if (operand) Record.AddStmt(operand);
John McCall81904512011-01-06 01:58:22 +0000631 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000632 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000633 }
634}
John McCall17001972009-10-18 01:05:36 +0000635void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000636 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000637}
John McCallcebee162009-10-18 09:09:24 +0000638void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
639 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000640 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000641}
Douglas Gregorada4b792011-01-14 02:55:32 +0000642void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
643 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000644 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000645}
John McCall17001972009-10-18 01:05:36 +0000646void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
647 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000648 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
649 Record.AddSourceLocation(TL.getTemplateNameLoc());
650 Record.AddSourceLocation(TL.getLAngleLoc());
651 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000652 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000653 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
654 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000655}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000656void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000657 Record.AddSourceLocation(TL.getLParenLoc());
658 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000659}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000660void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000661 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
662 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000663}
John McCalle78aac42010-03-10 03:28:59 +0000664void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000665 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000666}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000667void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000668 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
669 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
670 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000671}
John McCallc392f372010-06-11 00:33:02 +0000672void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
673 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000674 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
675 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
676 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
677 Record.AddSourceLocation(TL.getTemplateNameLoc());
678 Record.AddSourceLocation(TL.getLAngleLoc());
679 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000680 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000681 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
682 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000683}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000684void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000685 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000686}
John McCall17001972009-10-18 01:05:36 +0000687void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000688 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000689}
690void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
691 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000692 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
693 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000694 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000695 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
696 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
697 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000698 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000699 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000700}
John McCallfc93cf92009-10-22 22:37:11 +0000701void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000702 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000703}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000704void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000705 Record.AddSourceLocation(TL.getKWLoc());
706 Record.AddSourceLocation(TL.getLParenLoc());
707 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000708}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000709void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000710 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000711}
John McCall8f115c62009-10-16 21:56:05 +0000712
Richard Smith01b2cb42014-07-26 06:37:51 +0000713void ASTWriter::WriteTypeAbbrevs() {
714 using namespace llvm;
715
716 BitCodeAbbrev *Abv;
717
718 // Abbreviation for TYPE_EXT_QUAL
719 Abv = new BitCodeAbbrev();
720 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
721 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
722 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
723 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
724
725 // Abbreviation for TYPE_FUNCTION_PROTO
726 Abv = new BitCodeAbbrev();
727 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
728 // FunctionType
729 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
730 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
731 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
732 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
733 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
734 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
735 // FunctionProtoType
736 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
737 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
738 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
739 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
740 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
741 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
742 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
743 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
744 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
745}
746
Chris Lattner19cea4e2009-04-22 05:57:30 +0000747//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000748// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000749//===----------------------------------------------------------------------===//
750
Chris Lattner28fa4e62009-04-26 22:26:21 +0000751static void EmitBlockID(unsigned ID, const char *Name,
752 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000753 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000754 Record.clear();
755 Record.push_back(ID);
756 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
757
758 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000759 if (!Name || Name[0] == 0)
760 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000761 Record.clear();
762 while (*Name)
763 Record.push_back(*Name++);
764 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
765}
766
767static void EmitRecordID(unsigned ID, const char *Name,
768 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000769 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000770 Record.clear();
771 Record.push_back(ID);
772 while (*Name)
773 Record.push_back(*Name++);
774 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000775}
776
777static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000778 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000779#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000780 RECORD(STMT_STOP);
781 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000782 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000783 RECORD(STMT_NULL);
784 RECORD(STMT_COMPOUND);
785 RECORD(STMT_CASE);
786 RECORD(STMT_DEFAULT);
787 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000788 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000789 RECORD(STMT_IF);
790 RECORD(STMT_SWITCH);
791 RECORD(STMT_WHILE);
792 RECORD(STMT_DO);
793 RECORD(STMT_FOR);
794 RECORD(STMT_GOTO);
795 RECORD(STMT_INDIRECT_GOTO);
796 RECORD(STMT_CONTINUE);
797 RECORD(STMT_BREAK);
798 RECORD(STMT_RETURN);
799 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000800 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000801 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000802 RECORD(EXPR_PREDEFINED);
803 RECORD(EXPR_DECL_REF);
804 RECORD(EXPR_INTEGER_LITERAL);
805 RECORD(EXPR_FLOATING_LITERAL);
806 RECORD(EXPR_IMAGINARY_LITERAL);
807 RECORD(EXPR_STRING_LITERAL);
808 RECORD(EXPR_CHARACTER_LITERAL);
809 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000810 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000811 RECORD(EXPR_UNARY_OPERATOR);
812 RECORD(EXPR_SIZEOF_ALIGN_OF);
813 RECORD(EXPR_ARRAY_SUBSCRIPT);
814 RECORD(EXPR_CALL);
815 RECORD(EXPR_MEMBER);
816 RECORD(EXPR_BINARY_OPERATOR);
817 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
818 RECORD(EXPR_CONDITIONAL_OPERATOR);
819 RECORD(EXPR_IMPLICIT_CAST);
820 RECORD(EXPR_CSTYLE_CAST);
821 RECORD(EXPR_COMPOUND_LITERAL);
822 RECORD(EXPR_EXT_VECTOR_ELEMENT);
823 RECORD(EXPR_INIT_LIST);
824 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000825 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000826 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000827 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000828 RECORD(EXPR_VA_ARG);
829 RECORD(EXPR_ADDR_LABEL);
830 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000831 RECORD(EXPR_CHOOSE);
832 RECORD(EXPR_GNU_NULL);
833 RECORD(EXPR_SHUFFLE_VECTOR);
834 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000835 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000836 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000837 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000838 RECORD(EXPR_OBJC_ARRAY_LITERAL);
839 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000840 RECORD(EXPR_OBJC_ENCODE);
841 RECORD(EXPR_OBJC_SELECTOR_EXPR);
842 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
843 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
844 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
845 RECORD(EXPR_OBJC_KVC_REF_EXPR);
846 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000847 RECORD(STMT_OBJC_FOR_COLLECTION);
848 RECORD(STMT_OBJC_CATCH);
849 RECORD(STMT_OBJC_FINALLY);
850 RECORD(STMT_OBJC_AT_TRY);
851 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
852 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000854 RECORD(STMT_CXX_CATCH);
855 RECORD(STMT_CXX_TRY);
856 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000857 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000858 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000859 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000860 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000861 RECORD(EXPR_CXX_STATIC_CAST);
862 RECORD(EXPR_CXX_DYNAMIC_CAST);
863 RECORD(EXPR_CXX_REINTERPRET_CAST);
864 RECORD(EXPR_CXX_CONST_CAST);
865 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000866 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000867 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000868 RECORD(EXPR_CXX_BOOL_LITERAL);
869 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000870 RECORD(EXPR_CXX_TYPEID_EXPR);
871 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000872 RECORD(EXPR_CXX_THIS);
873 RECORD(EXPR_CXX_THROW);
874 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000875 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000876 RECORD(EXPR_CXX_BIND_TEMPORARY);
877 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
878 RECORD(EXPR_CXX_NEW);
879 RECORD(EXPR_CXX_DELETE);
880 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
881 RECORD(EXPR_EXPR_WITH_CLEANUPS);
882 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
883 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
884 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
885 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
886 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000887 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000888 RECORD(EXPR_CXX_NOEXCEPT);
889 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000890 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
891 RECORD(EXPR_TYPE_TRAIT);
892 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000893 RECORD(EXPR_PACK_EXPANSION);
894 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000895 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000896 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000897 RECORD(EXPR_FUNCTION_PARM_PACK);
898 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000899 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000900 RECORD(EXPR_CXX_UUIDOF_EXPR);
901 RECORD(EXPR_CXX_UUIDOF_TYPE);
902 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000903#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000904}
Mike Stump11289f42009-09-09 15:08:12 +0000905
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000906void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000907 RecordData Record;
908 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000909
Sebastian Redl539c5062010-08-18 23:57:32 +0000910#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
911#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000913 // Control Block.
914 BLOCK(CONTROL_BLOCK);
915 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000916 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000917 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000918 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000919 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000920 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000921 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000922 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000923 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000924 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000925
926 BLOCK(OPTIONS_BLOCK);
927 RECORD(LANGUAGE_OPTIONS);
928 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000929 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000930 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000931 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000932 RECORD(PREPROCESSOR_OPTIONS);
933
Douglas Gregor108cb222012-10-19 00:45:00 +0000934 BLOCK(INPUT_FILES_BLOCK);
935 RECORD(INPUT_FILE);
936
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000937 // AST Top-Level Block.
938 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000939 RECORD(TYPE_OFFSET);
940 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000941 RECORD(IDENTIFIER_OFFSET);
942 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000943 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000944 RECORD(SPECIAL_TYPES);
945 RECORD(STATISTICS);
946 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000947 RECORD(SELECTOR_OFFSETS);
948 RECORD(METHOD_POOL);
949 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000950 RECORD(SOURCE_LOCATION_OFFSETS);
951 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000952 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000953 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000954 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000955 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000956 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000957 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000958 RECORD(SEMA_DECL_REFS);
959 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
960 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000961 RECORD(UPDATE_VISIBLE);
962 RECORD(DECL_UPDATE_OFFSETS);
963 RECORD(DECL_UPDATES);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000964 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000965 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000966 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000967 RECORD(FP_PRAGMA_OPTIONS);
968 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000969 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000970 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000971 RECORD(MODULE_OFFSET_MAP);
972 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000973 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000974 RECORD(FILE_SORTED_DECLS);
975 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000976 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000977 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000978 RECORD(INTERESTING_IDENTIFIERS);
979 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000980 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000981 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000982 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000983 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000984 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000985 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000986
Chris Lattner28fa4e62009-04-26 22:26:21 +0000987 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000988 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000989 RECORD(SM_SLOC_FILE_ENTRY);
990 RECORD(SM_SLOC_BUFFER_ENTRY);
991 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000992 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000993 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner28fa4e62009-04-26 22:26:21 +0000995 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000996 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000997 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000998 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000999 RECORD(PP_MACRO_OBJECT_LIKE);
1000 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001001 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +00001002
Richard Smithfa715652015-08-31 22:43:10 +00001003 // Submodule Block.
1004 BLOCK(SUBMODULE_BLOCK);
1005 RECORD(SUBMODULE_METADATA);
1006 RECORD(SUBMODULE_DEFINITION);
1007 RECORD(SUBMODULE_UMBRELLA_HEADER);
1008 RECORD(SUBMODULE_HEADER);
1009 RECORD(SUBMODULE_TOPHEADER);
1010 RECORD(SUBMODULE_UMBRELLA_DIR);
1011 RECORD(SUBMODULE_IMPORTS);
1012 RECORD(SUBMODULE_EXPORTS);
1013 RECORD(SUBMODULE_REQUIRES);
1014 RECORD(SUBMODULE_EXCLUDED_HEADER);
1015 RECORD(SUBMODULE_LINK_LIBRARY);
1016 RECORD(SUBMODULE_CONFIG_MACRO);
1017 RECORD(SUBMODULE_CONFLICT);
1018 RECORD(SUBMODULE_PRIVATE_HEADER);
1019 RECORD(SUBMODULE_TEXTUAL_HEADER);
1020 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1021
1022 // Comments Block.
1023 BLOCK(COMMENTS_BLOCK);
1024 RECORD(COMMENTS_RAW_COMMENT);
1025
Douglas Gregor12bfa382009-10-17 00:13:19 +00001026 // Decls and Types block.
1027 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001028 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001029 RECORD(TYPE_COMPLEX);
1030 RECORD(TYPE_POINTER);
1031 RECORD(TYPE_BLOCK_POINTER);
1032 RECORD(TYPE_LVALUE_REFERENCE);
1033 RECORD(TYPE_RVALUE_REFERENCE);
1034 RECORD(TYPE_MEMBER_POINTER);
1035 RECORD(TYPE_CONSTANT_ARRAY);
1036 RECORD(TYPE_INCOMPLETE_ARRAY);
1037 RECORD(TYPE_VARIABLE_ARRAY);
1038 RECORD(TYPE_VECTOR);
1039 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001040 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001041 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001042 RECORD(TYPE_TYPEDEF);
1043 RECORD(TYPE_TYPEOF_EXPR);
1044 RECORD(TYPE_TYPEOF);
1045 RECORD(TYPE_RECORD);
1046 RECORD(TYPE_ENUM);
1047 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001048 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001049 RECORD(TYPE_DECLTYPE);
1050 RECORD(TYPE_ELABORATED);
1051 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1052 RECORD(TYPE_UNRESOLVED_USING);
1053 RECORD(TYPE_INJECTED_CLASS_NAME);
1054 RECORD(TYPE_OBJC_OBJECT);
1055 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1056 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1057 RECORD(TYPE_DEPENDENT_NAME);
1058 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1059 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1060 RECORD(TYPE_PAREN);
1061 RECORD(TYPE_PACK_EXPANSION);
1062 RECORD(TYPE_ATTRIBUTED);
1063 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001064 RECORD(TYPE_AUTO);
1065 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001066 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001067 RECORD(TYPE_DECAYED);
1068 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001069 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001070 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001071 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001072 RECORD(DECL_ENUM);
1073 RECORD(DECL_RECORD);
1074 RECORD(DECL_ENUM_CONSTANT);
1075 RECORD(DECL_FUNCTION);
1076 RECORD(DECL_OBJC_METHOD);
1077 RECORD(DECL_OBJC_INTERFACE);
1078 RECORD(DECL_OBJC_PROTOCOL);
1079 RECORD(DECL_OBJC_IVAR);
1080 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001081 RECORD(DECL_OBJC_CATEGORY);
1082 RECORD(DECL_OBJC_CATEGORY_IMPL);
1083 RECORD(DECL_OBJC_IMPLEMENTATION);
1084 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1085 RECORD(DECL_OBJC_PROPERTY);
1086 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001087 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001088 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001089 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001090 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001091 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001092 RECORD(DECL_FILE_SCOPE_ASM);
1093 RECORD(DECL_BLOCK);
1094 RECORD(DECL_CONTEXT_LEXICAL);
1095 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001096 RECORD(DECL_NAMESPACE);
1097 RECORD(DECL_NAMESPACE_ALIAS);
1098 RECORD(DECL_USING);
1099 RECORD(DECL_USING_SHADOW);
1100 RECORD(DECL_USING_DIRECTIVE);
1101 RECORD(DECL_UNRESOLVED_USING_VALUE);
1102 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1103 RECORD(DECL_LINKAGE_SPEC);
1104 RECORD(DECL_CXX_RECORD);
1105 RECORD(DECL_CXX_METHOD);
1106 RECORD(DECL_CXX_CONSTRUCTOR);
1107 RECORD(DECL_CXX_DESTRUCTOR);
1108 RECORD(DECL_CXX_CONVERSION);
1109 RECORD(DECL_ACCESS_SPEC);
1110 RECORD(DECL_FRIEND);
1111 RECORD(DECL_FRIEND_TEMPLATE);
1112 RECORD(DECL_CLASS_TEMPLATE);
1113 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1114 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001115 RECORD(DECL_VAR_TEMPLATE);
1116 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1117 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001118 RECORD(DECL_FUNCTION_TEMPLATE);
1119 RECORD(DECL_TEMPLATE_TYPE_PARM);
1120 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1121 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Richard Smithefc884a2016-04-13 07:41:35 +00001122 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001123 RECORD(DECL_STATIC_ASSERT);
1124 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +00001125 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001126 RECORD(DECL_INDIRECTFIELD);
1127 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +00001128 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1129 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1130 RECORD(DECL_IMPORT);
1131 RECORD(DECL_OMP_THREADPRIVATE);
1132 RECORD(DECL_EMPTY);
1133 RECORD(DECL_OBJC_TYPE_PARAM);
1134 RECORD(DECL_OMP_CAPTUREDEXPR);
1135 RECORD(DECL_PRAGMA_COMMENT);
1136 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1137 RECORD(DECL_OMP_DECLARE_REDUCTION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001138
Douglas Gregor03412ba2011-06-03 02:27:19 +00001139 // Statements and Exprs can occur in the Decls and Types block.
1140 AddStmtsExprs(Stream, Record);
1141
Douglas Gregor92a96f52011-02-08 21:58:10 +00001142 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001143 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001144 RECORD(PPD_MACRO_DEFINITION);
1145 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001146
1147 // Decls and Types block.
1148 BLOCK(EXTENSION_BLOCK);
1149 RECORD(EXTENSION_METADATA);
1150
Chris Lattner28fa4e62009-04-26 22:26:21 +00001151#undef RECORD
1152#undef BLOCK
1153 Stream.ExitBlock();
1154}
1155
Richard Smith54cc3c22014-12-11 20:50:24 +00001156/// \brief Prepares a path for being written to an AST file by converting it
1157/// to an absolute path and removing nested './'s.
1158///
1159/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001160static bool cleanPathForOutput(FileManager &FileMgr,
1161 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001162 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001163 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001164}
1165
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001166/// \brief Adjusts the given filename to only write out the portion of the
1167/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001168///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001169/// \param Filename the file name to adjust.
1170///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001171/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1172/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001173///
1174/// \returns either the original filename (if it needs no adjustment) or the
1175/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001176static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001177adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001178 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001179
Richard Smith7ed1bc92014-12-05 22:42:13 +00001180 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001181 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001182
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001183 // Verify that the filename and the system root have the same prefix.
1184 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001185 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1186 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001187 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001188
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001189 // We hit the end of the filename before we hit the end of the system root.
1190 if (!Filename[Pos])
1191 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001192
Richard Smith7ed1bc92014-12-05 22:42:13 +00001193 // If there's not a path separator at the end of the base directory nor
1194 // immediately after it, then this isn't within the base directory.
1195 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1196 if (!llvm::sys::path::is_separator(BaseDir.back()))
1197 return Filename;
1198 } else {
1199 // If the file name has a '/' at the current position, skip over the '/'.
1200 // We distinguish relative paths from absolute paths by the
1201 // absence of '/' at the beginning of relative paths.
1202 //
1203 // FIXME: This is wrong. We distinguish them by asking if the path is
1204 // absolute, which isn't the same thing. And there might be multiple '/'s
1205 // in a row. Use a better mechanism to indicate whether we have emitted an
1206 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001207 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001210 return Filename + Pos;
1211}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001212
Ben Langmuir487ea142014-10-23 18:05:36 +00001213static ASTFileSignature getSignature() {
1214 while (1) {
1215 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1216 return S;
1217 // Rely on GetRandomNumber to eventually return non-zero...
1218 }
1219}
1220
Douglas Gregor112b9072012-10-18 05:31:06 +00001221/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001222uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1223 ASTContext &Context,
1224 StringRef isysroot,
1225 const std::string &OutputFile) {
1226 ASTFileSignature Signature = 0;
1227
Douglas Gregorbfbde532009-04-10 21:16:55 +00001228 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001229 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001230 RecordData Record;
1231
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001232 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001233 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001234 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1235 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1236 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1237 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1238 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1239 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001240 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001241 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1242 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1243 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001244 assert((!WritingModule || isysroot.empty()) &&
1245 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001246 {
1247 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1248 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1249 !isysroot.empty(), IncludeTimestamps,
1250 ASTHasCompilerErrors};
1251 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1252 getClangFullRepositoryVersion());
1253 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001254 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001255 // For implicit modules we output a signature that we can use to ensure
1256 // duplicate module builds don't collide in the cache as their output order
1257 // is non-deterministic.
1258 // FIXME: Remove this when output is deterministic.
1259 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001260 Signature = getSignature();
1261 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001262 Stream.EmitRecord(SIGNATURE, Record);
1263 }
1264
Richard Smith7ed1bc92014-12-05 22:42:13 +00001265 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001266 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001267 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1268 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1269 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001270 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001271 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1272 }
1273
Richard Smith7ed1bc92014-12-05 22:42:13 +00001274 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001275 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001276 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001277
1278 // If the home of the module is the current working directory, then we
1279 // want to pick up the cwd of the build process loading the module, not
1280 // our cwd, when we load this module.
1281 if (!PP.getHeaderSearchInfo()
1282 .getHeaderSearchOpts()
1283 .ModuleMapFileHomeIsCwd ||
1284 WritingModule->Directory->getName() != StringRef(".")) {
1285 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001286 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001287 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1288 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1289 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1290
Mehdi Amini57a41912015-09-10 01:46:39 +00001291 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001292 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1293 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001294
1295 // Write out all other paths relative to the base directory if possible.
1296 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1297 } else if (!isysroot.empty()) {
1298 // Write out paths relative to the sysroot if possible.
1299 BaseDirectory = isysroot;
1300 }
1301
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001302 // Module map file
1303 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001304 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001305
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001306 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1307
1308 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001309 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001310
1311 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001312 if (auto *AdditionalModMaps =
1313 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001314 Record.push_back(AdditionalModMaps->size());
1315 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001316 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001317 } else {
1318 Record.push_back(0);
1319 }
1320
1321 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001322 }
1323
Douglas Gregor112b9072012-10-18 05:31:06 +00001324 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001325 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001326 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001327 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001328
Richard Smith7f330cd2015-03-18 01:42:29 +00001329 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001330 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001331 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001332 continue;
1333
Richard Smith7f330cd2015-03-18 01:42:29 +00001334 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1335 AddSourceLocation(M->ImportLoc, Record);
1336 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001337 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001338 Record.push_back(M->Signature);
1339 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001340 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001341 Stream.EmitRecord(IMPORTS, Record);
1342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Richard Smith0516b182015-09-08 19:40:14 +00001344 // Write the options block.
1345 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1346
Douglas Gregor112b9072012-10-18 05:31:06 +00001347 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001348 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001349 const LangOptions &LangOpts = Context.getLangOpts();
1350#define LANGOPT(Name, Bits, Default, Description) \
1351 Record.push_back(LangOpts.Name);
1352#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1353 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001354#include "clang/Basic/LangOptions.def"
1355#define SANITIZER(NAME, ID) \
1356 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001357#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001358
Ben Langmuircd98cb72015-06-23 18:20:18 +00001359 Record.push_back(LangOpts.ModuleFeatures.size());
1360 for (StringRef Feature : LangOpts.ModuleFeatures)
1361 AddString(Feature, Record);
1362
Douglas Gregor112b9072012-10-18 05:31:06 +00001363 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1364 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001365
1366 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001367
1368 // Comment options.
1369 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001370 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1371 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001372 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001373 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001374
Samuel Antaoee8fb302016-01-06 13:42:12 +00001375 // OpenMP offloading options.
1376 Record.push_back(LangOpts.OMPTargetTriples.size());
1377 for (auto &T : LangOpts.OMPTargetTriples)
1378 AddString(T.getTriple(), Record);
1379
1380 AddString(LangOpts.OMPHostIRFile, Record);
1381
Douglas Gregor112b9072012-10-18 05:31:06 +00001382 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1383
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001384 // Target options.
1385 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001386 const TargetInfo &Target = Context.getTargetInfo();
1387 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001388 AddString(TargetOpts.Triple, Record);
1389 AddString(TargetOpts.CPU, Record);
1390 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001391 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1392 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1393 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1394 }
1395 Record.push_back(TargetOpts.Features.size());
1396 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1397 AddString(TargetOpts.Features[I], Record);
1398 }
1399 Stream.EmitRecord(TARGET_OPTIONS, Record);
1400
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001401 // Diagnostic options.
1402 Record.clear();
1403 const DiagnosticOptions &DiagOpts
1404 = Context.getDiagnostics().getDiagnosticOptions();
1405#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1406#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1407 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1408#include "clang/Basic/DiagnosticOptions.def"
1409 Record.push_back(DiagOpts.Warnings.size());
1410 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1411 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001412 Record.push_back(DiagOpts.Remarks.size());
1413 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1414 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001415 // Note: we don't serialize the log or serialization file names, because they
1416 // are generally transient files and will almost always be overridden.
1417 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1418
Douglas Gregorc6317db2012-10-24 15:49:58 +00001419 // File system options.
1420 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001421 const FileSystemOptions &FSOpts =
1422 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001423 AddString(FSOpts.WorkingDir, Record);
1424 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1425
Douglas Gregor2d302362012-10-24 16:50:34 +00001426 // Header search options.
1427 Record.clear();
1428 const HeaderSearchOptions &HSOpts
1429 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1430 AddString(HSOpts.Sysroot, Record);
1431
1432 // Include entries.
1433 Record.push_back(HSOpts.UserEntries.size());
1434 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1435 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1436 AddString(Entry.Path, Record);
1437 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001438 Record.push_back(Entry.IsFramework);
1439 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001440 }
1441
1442 // System header prefixes.
1443 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1444 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1445 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1446 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1447 }
1448
1449 AddString(HSOpts.ResourceDir, Record);
1450 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001451 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001452 Record.push_back(HSOpts.DisableModuleHash);
1453 Record.push_back(HSOpts.UseBuiltinIncludes);
1454 Record.push_back(HSOpts.UseStandardSystemIncludes);
1455 Record.push_back(HSOpts.UseStandardCXXIncludes);
1456 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001457 // Write out the specific module cache path that contains the module files.
1458 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001459 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1460
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001461 // Preprocessor options.
1462 Record.clear();
1463 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1464
1465 // Macro definitions.
1466 Record.push_back(PPOpts.Macros.size());
1467 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1468 AddString(PPOpts.Macros[I].first, Record);
1469 Record.push_back(PPOpts.Macros[I].second);
1470 }
1471
1472 // Includes
1473 Record.push_back(PPOpts.Includes.size());
1474 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1475 AddString(PPOpts.Includes[I], Record);
1476
1477 // Macro includes
1478 Record.push_back(PPOpts.MacroIncludes.size());
1479 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1480 AddString(PPOpts.MacroIncludes[I], Record);
1481
Douglas Gregorb6368752012-10-24 23:41:50 +00001482 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001483 // Detailed record is important since it is used for the module cache hash.
1484 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001485 AddString(PPOpts.ImplicitPCHInclude, Record);
1486 AddString(PPOpts.ImplicitPTHInclude, Record);
1487 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1488 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1489
Richard Smith0516b182015-09-08 19:40:14 +00001490 // Leave the options block.
1491 Stream.ExitBlock();
1492
Douglas Gregora3b20262011-05-06 21:43:30 +00001493 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001494 SourceManager &SM = Context.getSourceManager();
1495 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001496 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001497 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1498 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001499 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1500 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1501
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001502 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001503 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001504 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001505 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001506 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001507
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001508 Record.clear();
1509 Record.push_back(SM.getMainFileID().getOpaqueValue());
1510 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1511
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001512 // Original PCH directory
1513 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001514 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001515 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1516 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1517 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1518
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001519 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001520
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001521 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001522 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1523
Mehdi Amini57a41912015-09-10 01:46:39 +00001524 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001525 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1526 }
1527
Douglas Gregor49491f72013-03-15 22:15:07 +00001528 WriteInputFiles(Context.SourceMgr,
1529 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001530 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001531 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001532 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001533}
1534
Douglas Gregor49491f72013-03-15 22:15:07 +00001535namespace {
1536 /// \brief An input file.
1537 struct InputFileEntry {
1538 const FileEntry *File;
1539 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001540 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001541 bool BufferOverridden;
1542 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001543} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001544
1545void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1546 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001547 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001548 using namespace llvm;
1549 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001550
Douglas Gregor72be3902012-10-19 00:38:02 +00001551 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001552 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001553 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001554 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001555 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1556 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001557 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001558 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001559 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1560 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1561
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001562 // Get all ContentCache objects for files, sorted by whether the file is a
1563 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001564 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001565 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1566 // Get this source location entry.
1567 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001568 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001569
1570 // We only care about file entries that were not overridden.
1571 if (!SLoc->isFile())
1572 continue;
1573 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001574 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001575 continue;
1576
Douglas Gregor49491f72013-03-15 22:15:07 +00001577 InputFileEntry Entry;
1578 Entry.File = Cache->OrigEntry;
1579 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001580 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001581 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001582 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001583 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001584 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001585 SortedFiles.push_front(Entry);
1586 }
1587
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001588 unsigned UserFilesNum = 0;
1589 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001590 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001591 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001592 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001593 if (InputFileID != 0)
1594 continue; // already recorded this file.
1595
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001596 // Record this entry's offset.
1597 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001598
1599 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001600
Douglas Gregor49491f72013-03-15 22:15:07 +00001601 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001602 ++UserFilesNum;
1603
Douglas Gregor72be3902012-10-19 00:38:02 +00001604 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001605 // And whether this file was overridden.
1606 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001607 INPUT_FILE,
1608 InputFileOffsets.size(),
1609 (uint64_t)Entry.File->getSize(),
1610 (uint64_t)getTimestampForOutput(Entry.File),
1611 Entry.BufferOverridden,
1612 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001613
Richard Smith7ed1bc92014-12-05 22:42:13 +00001614 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1615 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001616
Douglas Gregor112b9072012-10-18 05:31:06 +00001617 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001618
1619 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001620 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001621 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1622 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001623 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1624 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001625 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1626 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1627
1628 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001629 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1630 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001631 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001632}
1633
Douglas Gregora7f71a92009-04-10 03:52:48 +00001634//===----------------------------------------------------------------------===//
1635// Source Manager Serialization
1636//===----------------------------------------------------------------------===//
1637
1638/// \brief Create an abbreviation for the SLocEntry that refers to a
1639/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001640static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001641 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001642
1643 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001644 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001649 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001654 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001655}
1656
1657/// \brief Create an abbreviation for the SLocEntry that refers to a
1658/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001659static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001660 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001661
1662 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001663 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001669 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001670}
1671
1672/// \brief Create an abbreviation for the SLocEntry that refers to a
1673/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001674static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1675 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001676 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001677
1678 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001679 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1680 : SM_SLOC_BUFFER_BLOB));
1681 if (Compressed)
1682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001684 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001685}
1686
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001687/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1688/// expansion.
1689static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001690 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001691
1692 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001693 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001694 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001699 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001700}
1701
Douglas Gregor09b69892011-02-10 17:09:37 +00001702namespace {
1703 // Trait used for the on-disk hash table of header search information.
1704 class HeaderFileInfoTrait {
1705 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001706 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001707
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001708 // Keep track of the framework names we've used during serialization.
1709 SmallVector<char, 128> FrameworkStringData;
1710 llvm::StringMap<unsigned> FrameworkNameOffset;
1711
Douglas Gregor09b69892011-02-10 17:09:37 +00001712 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001713 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1714 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001715
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001716 struct key_type {
1717 const FileEntry *FE;
1718 const char *Filename;
1719 };
1720 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001721
1722 typedef HeaderFileInfo data_type;
1723 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001724 typedef unsigned hash_value_type;
1725 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001726
Richard Smithe75ee0f2015-08-17 07:13:32 +00001727 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001728 // The hash is based only on size/time of the file, so that the reader can
1729 // match even when symlinking or excess path elements ("foo/../", "../")
1730 // change the form of the name. However, complete path is still the key.
1731 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001732 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001733 }
1734
1735 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001736 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001737 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001738 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001739 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001740 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001741 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001742 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1743 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1744 DataLen += 4;
1745 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001746 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001747 }
1748
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001749 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001750 using namespace llvm::support;
1751 endian::Writer<little> LE(Out);
1752 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001753 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001754 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001755 KeyLen -= 8;
1756 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001757 }
1758
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001759 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001760 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001761 using namespace llvm::support;
1762 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001763 uint64_t Start = Out.tell(); (void)Start;
1764
Richard Smith386bb072015-08-18 23:42:23 +00001765 unsigned char Flags = (Data.isImport << 4)
1766 | (Data.isPragmaOnce << 3)
1767 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001768 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001769 LE.write<uint8_t>(Flags);
1770 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001771
1772 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001773 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001774 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001775 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001776
1777 unsigned Offset = 0;
1778 if (!Data.Framework.empty()) {
1779 // If this header refers into a framework, save the framework name.
1780 llvm::StringMap<unsigned>::iterator Pos
1781 = FrameworkNameOffset.find(Data.Framework);
1782 if (Pos == FrameworkNameOffset.end()) {
1783 Offset = FrameworkStringData.size() + 1;
1784 FrameworkStringData.append(Data.Framework.begin(),
1785 Data.Framework.end());
1786 FrameworkStringData.push_back(0);
1787
1788 FrameworkNameOffset[Data.Framework] = Offset;
1789 } else
1790 Offset = Pos->second;
1791 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001792 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001793
Richard Smith386bb072015-08-18 23:42:23 +00001794 // FIXME: If the header is excluded, we should write out some
1795 // record of that fact.
1796 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1797 if (uint32_t ModID =
1798 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1799 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1800 assert((Value >> 2) == ModID && "overflow in header module info");
1801 LE.write<uint32_t>(Value);
1802 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001803 }
1804
Douglas Gregor09b69892011-02-10 17:09:37 +00001805 assert(Out.tell() - Start == DataLen && "Wrong data length");
1806 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001807
1808 const char *strings_begin() const { return FrameworkStringData.begin(); }
1809 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001810 };
1811} // end anonymous namespace
1812
1813/// \brief Write the header search block for the list of files that
1814///
1815/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001816void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001817 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001818 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1819
1820 if (FilesByUID.size() > HS.header_file_size())
1821 FilesByUID.resize(HS.header_file_size());
1822
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001823 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001824 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001825 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001826 unsigned NumHeaderSearchEntries = 0;
1827 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1828 const FileEntry *File = FilesByUID[UID];
1829 if (!File)
1830 continue;
1831
Richard Smith386bb072015-08-18 23:42:23 +00001832 // Get the file info. This will load info from the external source if
1833 // necessary. Skip emitting this file if we have no information on it
1834 // as a header file (in which case HFI will be null) or if it hasn't
1835 // changed since it was loaded. Also skip it if it's for a modular header
1836 // from a different module; in that case, we rely on the module(s)
1837 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001838 const HeaderFileInfo *HFI =
1839 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1840 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001841 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001842
Richard Smith7ed1bc92014-12-05 22:42:13 +00001843 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001844 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001845 SmallString<128> FilenameTmp(Filename);
1846 if (PreparePathForOutput(FilenameTmp)) {
1847 // If we performed any translation on the file name at all, we need to
1848 // save this string, since the generator will refer to it later.
1849 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001850 SavedStrings.push_back(Filename);
1851 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001852
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001853 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001854 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001855 ++NumHeaderSearchEntries;
1856 }
1857
1858 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001859 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001860 uint32_t BucketOffset;
1861 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001862 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001863 llvm::raw_svector_ostream Out(TableData);
1864 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001865 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001866 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1867 }
1868
1869 // Create a blob abbreviation
1870 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001871
1872 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001873 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1878 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1879
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001880 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001881 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1882 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001883 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001884 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001885
1886 // Free all of the strings we had to duplicate.
1887 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001888 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001889}
1890
Douglas Gregora7f71a92009-04-10 03:52:48 +00001891/// \brief Writes the block containing the serialized form of the
1892/// source manager.
1893///
1894/// TODO: We should probably use an on-disk hash table (stored in a
1895/// blob), indexed based on the file name, so that we only create
1896/// entries for files that we actually need. In the common case (no
1897/// errors), we probably won't have to create file entries for any of
1898/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001899void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001900 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001901 RecordData Record;
1902
Chris Lattner0910e3b2009-04-10 17:16:57 +00001903 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001904 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001905
1906 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001907 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1908 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001909 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1910 unsigned SLocBufferBlobCompressedAbbrv =
1911 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001912 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001913
Douglas Gregor258ae542009-04-27 06:38:32 +00001914 // Write out the source location entry table. We skip the first
1915 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001916 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001917 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001918 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1919 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001920 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001921 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001922 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001923 FileID FID = FileID::get(I);
1924 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001925
Douglas Gregor258ae542009-04-27 06:38:32 +00001926 // Record the offset of this source-location entry.
1927 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1928
1929 // Figure out which record code to use.
1930 unsigned Code;
1931 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001932 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1933 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001934 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001935 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001936 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001937 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001938 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001939 Record.clear();
1940 Record.push_back(Code);
1941
Douglas Gregor925296b2011-07-19 16:10:42 +00001942 // Starting offset of this entry within this module, so skip the dummy.
1943 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001944 if (SLoc->isFile()) {
1945 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001946 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001947 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1948 Record.push_back(File.hasLineDirectives());
1949
1950 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001951 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001952 if (Content->OrigEntry) {
1953 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001954 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001955
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001956 // The source location entry is a file. Emit input file ID.
1957 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1958 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001959
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001960 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001961
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001962 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001963 if (FDI != FileDeclIDs.end()) {
1964 Record.push_back(FDI->second->FirstDeclIndex);
1965 Record.push_back(FDI->second->DeclIDs.size());
1966 } else {
1967 Record.push_back(0);
1968 Record.push_back(0);
1969 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001970
1971 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1972
Richard Smithaada85c2016-02-06 02:06:43 +00001973 if (Content->BufferOverridden || Content->IsTransient)
1974 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001975 } else {
1976 // The source location entry is a buffer. The blob associated
1977 // with this entry contains the contents of the buffer.
1978
1979 // We add one to the size so that we capture the trailing NULL
1980 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1981 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001982 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001983 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001984 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001985 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001986 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001987 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001988
Douglas Gregor925296b2011-07-19 16:10:42 +00001989 if (strcmp(Name, "<built-in>") == 0) {
1990 PreloadSLocs.push_back(SLocEntryOffsets.size());
1991 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001992 }
Richard Smithaada85c2016-02-06 02:06:43 +00001993
1994 if (EmitBlob) {
1995 // Include the implicit terminating null character in the on-disk buffer
1996 // if we're writing it uncompressed.
1997 const llvm::MemoryBuffer *Buffer =
1998 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1999 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2000
2001 // Compress the buffer if possible. We expect that almost all PCM
2002 // consumers will not want its contents.
2003 SmallString<0> CompressedBuffer;
2004 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2005 llvm::zlib::StatusOK) {
2006 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2007 Blob.size() - 1};
2008 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2009 CompressedBuffer);
2010 } else {
2011 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2012 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2013 }
2014 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002015 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002016 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002017 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002018 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2019 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2020 AddSourceLocation(Expansion.isMacroArgExpansion()
2021 ? SourceLocation()
2022 : Expansion.getExpansionLocEnd(),
2023 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002024
2025 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002026 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002027 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002028 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002029 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002030 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002031 }
2032 }
2033
Douglas Gregor8f45df52009-04-16 22:23:12 +00002034 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002035
2036 if (SLocEntryOffsets.empty())
2037 return;
2038
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002039 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002040 // table is used for lazily loading source-location information.
2041 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002042
2043 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002044 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002045 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002047 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2048 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002049 {
2050 RecordData::value_type Record[] = {
2051 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2052 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2053 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2054 bytes(SLocEntryOffsets));
2055 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002056 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002057 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002058 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002059
2060 // Write the line table. It depends on remapping working, so it must come
2061 // after the source location offsets.
2062 if (SourceMgr.hasLineTable()) {
2063 LineTableInfo &LineTable = SourceMgr.getLineTable();
2064
2065 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002066
2067 // Emit the needed file names.
2068 llvm::DenseMap<int, int> FilenameMap;
2069 for (const auto &L : LineTable) {
2070 if (L.first.ID < 0)
2071 continue;
2072 for (auto &LE : L.second) {
2073 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2074 FilenameMap.size())).second)
2075 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2076 }
2077 }
2078 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002079
2080 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002081 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002082 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002083 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002084 continue;
2085
2086 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002087 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002088
2089 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002090 Record.push_back(L.second.size());
2091 for (const auto &LE : L.second) {
2092 Record.push_back(LE.FileOffset);
2093 Record.push_back(LE.LineNo);
2094 Record.push_back(FilenameMap[LE.FilenameID]);
2095 Record.push_back((unsigned)LE.FileKind);
2096 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002097 }
2098 }
Richard Smith63078492015-09-01 07:41:55 +00002099
Douglas Gregor925296b2011-07-19 16:10:42 +00002100 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2101 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002102}
2103
Douglas Gregorc5046832009-04-27 18:38:38 +00002104//===----------------------------------------------------------------------===//
2105// Preprocessor Serialization
2106//===----------------------------------------------------------------------===//
2107
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002108static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2109 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002110 if (MacroInfo *MI = MD->getMacroInfo())
2111 if (MI->isBuiltinMacro())
2112 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002113
2114 if (IsModule) {
2115 SourceLocation Loc = MD->getLocation();
2116 if (Loc.isInvalid())
2117 return true;
2118 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2119 return true;
2120 }
2121
2122 return false;
2123}
2124
Chris Lattnereeffaef2009-04-10 17:15:23 +00002125/// \brief Writes the block containing the serialized form of the
2126/// preprocessor.
2127///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002128void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002129 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2130 if (PPRec)
2131 WritePreprocessorDetail(*PPRec);
2132
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002133 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002134 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002135
Chris Lattner0af3ba12009-04-13 01:29:17 +00002136 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2137 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002138 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002139 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002140 }
2141
2142 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002143 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002144
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002145 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002146 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002147 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002148 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002149
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002150 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002151 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002152
Richard Smithee977932015-05-01 21:22:17 +00002153 // Construct the list of identifiers with macro directives that need to be
2154 // serialized.
2155 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2156 for (auto &Id : PP.getIdentifierTable())
2157 if (Id.second->hadMacroDefinition() &&
2158 (!Id.second->isFromAST() ||
2159 Id.second->hasChangedSinceDeserialization()))
2160 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002161 // Sort the set of macro definitions that need to be serialized by the
2162 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002163 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2164 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002165
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002166 // Emit the macro directives as a list and associate the offset with the
2167 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002168 for (const IdentifierInfo *Name : MacroIdentifiers) {
2169 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002170 auto StartOffset = Stream.GetCurrentBitNo();
2171
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002172 // Emit the macro directives in reverse source order.
2173 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002174 // Once we hit an ignored macro, we're done: the rest of the chain
2175 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002176 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002177 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002178
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002179 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002180 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002181 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002182 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002183 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002184 Record.push_back(VisMD->isPublic());
2185 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002186 }
Richard Smithd7329392015-04-21 21:46:32 +00002187
Richard Smithb8b2ed62015-04-23 18:18:26 +00002188 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002189 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002190 // We write out exported module macros for PCH as well.
2191 auto Leafs = PP.getLeafModuleMacros(Name);
2192 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2193 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2194 while (!Worklist.empty()) {
2195 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002196
Manman Ren33d80292016-05-31 18:19:32 +00002197 // Emit a record indicating this submodule exports this macro.
2198 ModuleMacroRecord.push_back(
2199 getSubmoduleID(Macro->getOwningModule()));
2200 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2201 for (auto *M : Macro->overrides())
2202 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002203
Manman Ren33d80292016-05-31 18:19:32 +00002204 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2205 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002206
Manman Ren33d80292016-05-31 18:19:32 +00002207 // Enqueue overridden macros once we've visited all their ancestors.
2208 for (auto *M : Macro->overrides())
2209 if (++Visits[M] == M->getNumOverridingMacros())
2210 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002211
Manman Ren33d80292016-05-31 18:19:32 +00002212 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002213 }
Richard Smithd7329392015-04-21 21:46:32 +00002214
Richard Smithee977932015-05-01 21:22:17 +00002215 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002216 continue;
2217
Richard Smithd7329392015-04-21 21:46:32 +00002218 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002219 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2220 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002221 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002222
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002223 /// \brief Offsets of each of the macros into the bitstream, indexed by
2224 /// the local macro ID
2225 ///
2226 /// For each identifier that is associated with a macro, this map
2227 /// provides the offset into the bitstream where that macro is
2228 /// defined.
2229 std::vector<uint32_t> MacroOffsets;
2230
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002231 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2232 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2233 MacroInfo *MI = MacroInfosToEmit[I].MI;
2234 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002235
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002236 if (ID < FirstMacroID) {
2237 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2238 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002239 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002240
2241 // Record the local offset of this macro.
2242 unsigned Index = ID - FirstMacroID;
2243 if (Index == MacroOffsets.size())
2244 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2245 else {
2246 if (Index > MacroOffsets.size())
2247 MacroOffsets.resize(Index + 1);
2248
2249 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2250 }
2251
2252 AddIdentifierRef(Name, Record);
2253 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2254 AddSourceLocation(MI->getDefinitionLoc(), Record);
2255 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2256 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002257 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002258 unsigned Code;
2259 if (MI->isObjectLike()) {
2260 Code = PP_MACRO_OBJECT_LIKE;
2261 } else {
2262 Code = PP_MACRO_FUNCTION_LIKE;
2263
2264 Record.push_back(MI->isC99Varargs());
2265 Record.push_back(MI->isGNUVarargs());
2266 Record.push_back(MI->hasCommaPasting());
2267 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002268 for (const IdentifierInfo *Arg : MI->args())
2269 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002270 }
2271
2272 // If we have a detailed preprocessing record, record the macro definition
2273 // ID that corresponds to this macro.
2274 if (PPRec)
2275 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2276
2277 Stream.EmitRecord(Code, Record);
2278 Record.clear();
2279
2280 // Emit the tokens array.
2281 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2282 // Note that we know that the preprocessor does not have any annotation
2283 // tokens in it because they are created by the parser, and thus can't
2284 // be in a macro definition.
2285 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002286 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002287 Stream.EmitRecord(PP_TOKEN, Record);
2288 Record.clear();
2289 }
2290 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002291 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002292
Douglas Gregor92a96f52011-02-08 21:58:10 +00002293 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002294
2295 // Write the offsets table for macro IDs.
2296 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002297
Richard Smith13090a22015-04-10 02:02:24 +00002298 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002299 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2300 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2303
2304 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002305 {
2306 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2307 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2308 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2309 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002310}
2311
2312void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002313 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002314 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002315
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002316 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002317
Douglas Gregor92a96f52011-02-08 21:58:10 +00002318 // Enter the preprocessor block.
2319 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002320
Douglas Gregoraae92242010-03-19 21:51:54 +00002321 // If the preprocessor has a preprocessing record, emit it.
2322 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002323 using namespace llvm;
2324
2325 // Set up the abbreviation for
2326 unsigned InclusionAbbrev = 0;
2327 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002328 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002329 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002330 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2332 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002333 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002334 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2335 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2336 }
2337
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002338 unsigned FirstPreprocessorEntityID
2339 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2340 + NUM_PREDEF_PP_ENTITY_IDS;
2341 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002342 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002343 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2344 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002345 E != EEnd;
2346 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002347 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002348
Richard Smith66a81862015-05-04 02:25:31 +00002349 PreprocessedEntityOffsets.push_back(
2350 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002351
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002352 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002353 // Record this macro definition's ID.
2354 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002355
Douglas Gregor92a96f52011-02-08 21:58:10 +00002356 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002357 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2358 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002359 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002360
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002361 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002362 Record.push_back(ME->isBuiltinMacro());
2363 if (ME->isBuiltinMacro())
2364 AddIdentifierRef(ME->getName(), Record);
2365 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002366 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002367 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002368 continue;
2369 }
2370
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002371 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002372 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002373 Record.push_back(ID->getFileName().size());
2374 Record.push_back(ID->wasInQuotes());
2375 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002376 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002377 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002378 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002379 // Check that the FileEntry is not null because it was not resolved and
2380 // we create a PCH even with compiler errors.
2381 if (ID->getFile())
2382 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002383 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002384 continue;
2385 }
2386
2387 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2388 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002389 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002390
Douglas Gregoraae92242010-03-19 21:51:54 +00002391 // Write the offsets table for the preprocessing record.
2392 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002393 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2394
Douglas Gregoraae92242010-03-19 21:51:54 +00002395 // Write the offsets table for identifier IDs.
2396 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002397
2398 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002399 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002400 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002402 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002403
Mehdi Amini57a41912015-09-10 01:46:39 +00002404 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2405 FirstPreprocessorEntityID -
2406 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002407 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002408 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002409 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002410}
2411
Richard Smith386bb072015-08-18 23:42:23 +00002412unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002413 if (!Mod)
2414 return 0;
2415
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002416 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2417 if (Known != SubmoduleIDs.end())
2418 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002419
2420 if (Mod->getTopLevelModule() != WritingModule)
2421 return 0;
2422
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002423 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2424}
2425
Richard Smith386bb072015-08-18 23:42:23 +00002426unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2427 // FIXME: This can easily happen, if we have a reference to a submodule that
2428 // did not result in us loading a module file for that submodule. For
2429 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2430 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2431 assert((ID || !Mod) &&
2432 "asked for module ID for non-local, non-imported module");
2433 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002434}
2435
Douglas Gregor253eefe2011-12-01 00:59:36 +00002436/// \brief Compute the number of modules within the given tree (including the
2437/// given module).
2438static unsigned getNumberOfModules(Module *Mod) {
2439 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002440 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002441 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002442 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002443
2444 return ChildModules + 1;
2445}
2446
Douglas Gregorde3ef502011-11-30 23:21:26 +00002447void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002448 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002449 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002450
2451 // Write the abbreviations needed for the submodules block.
2452 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002453
2454 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor69021972011-11-30 17:33:56 +00002455 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002464 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002465 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002466 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2467 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2468
2469 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002470 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2472 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2473
2474 Abbrev = new BitCodeAbbrev();
2475 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2476 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2477 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002478
2479 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002480 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2481 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2482 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2483
2484 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002485 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2486 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2487 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2488
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002489 Abbrev = new BitCodeAbbrev();
2490 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002491 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2492 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002493 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2494
Douglas Gregor59527662012-10-15 06:28:11 +00002495 Abbrev = new BitCodeAbbrev();
2496 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2498 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2499
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002500 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002501 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2502 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2503 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2504
2505 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002506 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2508 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2509
2510 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002511 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2513 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2514
2515 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002516 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2517 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2519 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2520
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002521 Abbrev = new BitCodeAbbrev();
2522 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2524 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2525
Douglas Gregorfb912652013-03-20 21:10:35 +00002526 Abbrev = new BitCodeAbbrev();
2527 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2530 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2531
Douglas Gregor253eefe2011-12-01 00:59:36 +00002532 // Write the submodule metadata block.
Mehdi Amini57a41912015-09-10 01:46:39 +00002533 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2534 FirstSubmoduleID -
2535 NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002536 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2537
Douglas Gregor69021972011-11-30 17:33:56 +00002538 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002539 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002540 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002541 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002542 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002543 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002544 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002545
2546 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002547 if (Mod->Parent) {
2548 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002549 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002550 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002551
2552 // Emit the definition of the block.
2553 {
2554 RecordData::value_type Record[] = {
2555 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2556 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2557 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2558 Mod->ConfigMacrosExhaustive};
2559 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2560 }
2561
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002562 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002563 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002564 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002565 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002566 }
2567
Douglas Gregor69021972011-11-30 17:33:56 +00002568 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002569 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002570 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002571 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2572 UmbrellaHeader.NameAsWritten);
2573 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002574 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2575 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002576 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002577 }
Richard Smith306d8922014-10-22 23:50:56 +00002578
Douglas Gregor69021972011-11-30 17:33:56 +00002579 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002580 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002581 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002582 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002583 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002584 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002585 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2586 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2587 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002588 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002589 Module::HK_PrivateTextual},
2590 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002591 };
2592 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002593 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002594 for (auto &H : Mod->Headers[HL.HeaderKind])
2595 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2596 }
2597
2598 // Emit the top headers.
2599 {
2600 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002601 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002602 for (auto *H : TopHeaders)
2603 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002604 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002605
2606 // Emit the imports.
2607 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002608 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002609 for (auto *I : Mod->Imports)
2610 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002611 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2612 }
2613
Douglas Gregor24bb9232011-12-02 18:58:38 +00002614 // Emit the exports.
2615 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002616 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002617 for (const auto &E : Mod->Exports) {
2618 // FIXME: This may fail; we don't require that all exported modules
2619 // are local or imported.
2620 Record.push_back(getSubmoduleID(E.getPointer()));
2621 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002622 }
2623 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2624 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002625
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002626 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2627 // Might be unnecessary as use declarations are only used to build the
2628 // module itself.
2629
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002630 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002631 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002632 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2633 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002634 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002635 }
2636
Douglas Gregorfb912652013-03-20 21:10:35 +00002637 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002638 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002639 // FIXME: This may fail; we don't require that all conflicting modules
2640 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002641 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2642 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002643 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002644 }
2645
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002646 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002647 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002648 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002649 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002650 }
2651
Douglas Gregor69021972011-11-30 17:33:56 +00002652 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002653 for (auto *M : Mod->submodules())
2654 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002655 }
2656
2657 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002658
Richard Smith23d8d032015-05-14 00:45:20 +00002659 assert((NextSubmoduleID - FirstSubmoduleID ==
2660 getNumberOfModules(WritingModule)) &&
2661 "Wrong # of submodules; found a reference to a non-local, "
2662 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002663}
2664
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002665serialization::SubmoduleID
2666ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002667 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002668 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002669
2670 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002671 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002672 Module *OwningMod
2673 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002674 if (!OwningMod)
2675 return 0;
2676
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002677 // Check whether this submodule is part of our own module.
2678 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002679 return 0;
2680
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002681 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002682}
2683
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002684void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2685 bool isModule) {
2686 // Make sure set diagnostic pragmas don't affect the translation unit that
2687 // imports the module.
2688 // FIXME: Make diagnostic pragma sections work properly with modules.
2689 if (isModule)
2690 return;
2691
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002692 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2693 DiagStateIDMap;
2694 unsigned CurrID = 0;
2695 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002696 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002697 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002698 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2699 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002700 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002701 if (point.Loc.isInvalid())
2702 continue;
2703
Richard Smithb22a1d12016-03-27 20:13:24 +00002704 AddSourceLocation(point.Loc, Record);
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002705 unsigned &DiagStateID = DiagStateIDMap[point.State];
2706 Record.push_back(DiagStateID);
2707
2708 if (DiagStateID == 0) {
2709 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002710 for (const auto &I : *(point.State)) {
2711 if (I.second.isPragma()) {
2712 Record.push_back(I.first);
2713 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002714 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002715 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002716 Record.push_back(-1); // mark the end of the diag/map pairs for this
2717 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002718 }
2719 }
2720
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002721 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002722 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002723}
2724
Douglas Gregorc5046832009-04-27 18:38:38 +00002725//===----------------------------------------------------------------------===//
2726// Type Serialization
2727//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002728
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002729/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002730void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002731 TypeIdx &IdxRef = TypeIdxs[T];
2732 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2733 IdxRef = TypeIdx(NextTypeID++);
2734 TypeIdx Idx = IdxRef;
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 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002740 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002741 ASTTypeWriter W(*this, Record);
Richard Smith290d8012016-04-06 17:06:00 +00002742 W.Visit(T);
2743 uint64_t Offset = W.Emit();
John McCall8ccfcb52009-09-24 19:53:00 +00002744
Richard Smith290d8012016-04-06 17:06:00 +00002745 // Record the offset for this type.
2746 unsigned Index = Idx.getIndex() - FirstTypeID;
2747 if (TypeOffsets.size() == Index)
2748 TypeOffsets.push_back(Offset);
2749 else if (TypeOffsets.size() < Index) {
2750 TypeOffsets.resize(Index + 1);
2751 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002752 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002753 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002754 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002755}
2756
Douglas Gregorc5046832009-04-27 18:38:38 +00002757//===----------------------------------------------------------------------===//
2758// Declaration Serialization
2759//===----------------------------------------------------------------------===//
2760
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002761/// \brief Write the block containing all of the declaration IDs
2762/// lexically declared within the given DeclContext.
2763///
2764/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2765/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002766uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002767 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002768 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002769 return 0;
2770
Douglas Gregor8f45df52009-04-16 22:23:12 +00002771 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002772 SmallVector<uint32_t, 128> KindDeclPairs;
2773 for (const auto *D : DC->decls()) {
2774 KindDeclPairs.push_back(D->getKind());
2775 KindDeclPairs.push_back(GetDeclRef(D));
2776 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002777
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002778 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002779 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002780 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2781 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002782 return Offset;
2783}
2784
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002785void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002786 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002787
2788 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002789 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002790 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002791 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002792 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002793 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2794 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002795 {
2796 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2797 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2798 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2799 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002800
2801 // Write the declaration offsets array
2802 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002803 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002805 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002806 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2807 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002808 {
2809 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2810 FirstDeclID - NUM_PREDEF_DECL_IDS};
2811 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2812 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002813}
2814
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002815void ASTWriter::WriteFileDeclIDsMap() {
2816 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002817
Chandler Carruthb306d732015-03-27 00:31:20 +00002818 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2819 FileDeclIDs.begin(), FileDeclIDs.end());
2820 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2821 llvm::less_first());
2822
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002823 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002824 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2825 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2826 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2827 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2828 for (auto &LocDeclEntry : Info.DeclIDs)
2829 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002830 }
2831
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002832 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002833 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2836 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002837 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2838 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002839 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002840}
2841
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002842void ASTWriter::WriteComments() {
2843 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002844 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002845 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002846 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002847 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002848 AddSourceRange(I->getSourceRange(), Record);
2849 Record.push_back(I->getKind());
2850 Record.push_back(I->isTrailingComment());
2851 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002852 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2853 }
2854 Stream.ExitBlock();
2855}
2856
Douglas Gregorc5046832009-04-27 18:38:38 +00002857//===----------------------------------------------------------------------===//
2858// Global Method Pool and Selector Serialization
2859//===----------------------------------------------------------------------===//
2860
Douglas Gregore84a9da2009-04-20 20:36:09 +00002861namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002862// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002863class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002864 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002865
2866public:
2867 typedef Selector key_type;
2868 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002869
Sebastian Redl834bb972010-08-04 17:20:04 +00002870 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002871 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002872 ObjCMethodList Instance, Factory;
2873 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002874 typedef const data_type& data_type_ref;
2875
Justin Bogner25463f12014-04-18 20:27:24 +00002876 typedef unsigned hash_value_type;
2877 typedef unsigned offset_type;
2878
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002879 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002880
Justin Bogner25463f12014-04-18 20:27:24 +00002881 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002882 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002883 }
Mike Stump11289f42009-09-09 15:08:12 +00002884
2885 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002886 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002887 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002888 using namespace llvm::support;
2889 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002890 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002891 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002892 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2893 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002894 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002895 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002896 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002897 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002898 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002899 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002900 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002901 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002902 return std::make_pair(KeyLen, DataLen);
2903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002905 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002906 using namespace llvm::support;
2907 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002908 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002909 assert((Start >> 32) == 0 && "Selector key offset too large");
2910 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002911 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002912 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002913 if (N == 0)
2914 N = 1;
2915 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002916 LE.write<uint32_t>(
2917 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002918 }
Mike Stump11289f42009-09-09 15:08:12 +00002919
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002920 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002921 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002922 using namespace llvm::support;
2923 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002924 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002925 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002926 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002927 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002928 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002929 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002930 ++NumInstanceMethods;
2931
2932 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002933 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002934 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002935 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002936 ++NumFactoryMethods;
2937
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002938 unsigned InstanceBits = Methods.Instance.getBits();
2939 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002940 unsigned InstanceHasMoreThanOneDeclBit =
2941 Methods.Instance.hasMoreThanOneDecl();
2942 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2943 (InstanceHasMoreThanOneDeclBit << 2) |
2944 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002945 unsigned FactoryBits = Methods.Factory.getBits();
2946 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002947 unsigned FactoryHasMoreThanOneDeclBit =
2948 Methods.Factory.hasMoreThanOneDecl();
2949 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2950 (FactoryHasMoreThanOneDeclBit << 2) |
2951 FactoryBits;
2952 LE.write<uint16_t>(FullInstanceBits);
2953 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002954 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002955 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002956 if (Method->getMethod())
2957 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002958 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002959 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002960 if (Method->getMethod())
2961 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002962
2963 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002964 }
2965};
2966} // end anonymous namespace
2967
Sebastian Redla19a67f2010-08-03 21:58:15 +00002968/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002969///
2970/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00002971/// in an on-disk hash table indexed by the selector. The hash table also
2972/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002973void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002974 using namespace llvm;
2975
Sebastian Redla19a67f2010-08-03 21:58:15 +00002976 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00002977 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00002978 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00002979 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00002980 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002981 {
Justin Bognerbb094f02014-04-18 19:57:06 +00002982 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00002983 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002984
Sebastian Redla19a67f2010-08-03 21:58:15 +00002985 // Create the on-disk hash table representation. We walk through every
2986 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00002987 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002988 for (auto &SelectorAndID : SelectorIDs) {
2989 Selector S = SelectorAndID.first;
2990 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00002991 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002992 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002993 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00002994 ObjCMethodList(),
2995 ObjCMethodList()
2996 };
2997 if (F != SemaRef.MethodPool.end()) {
2998 Data.Instance = F->second.first;
2999 Data.Factory = F->second.second;
3000 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003001 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003002 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003003 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003004 // Selector already exists. Did it change?
3005 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003006 for (ObjCMethodList *M = &Data.Instance;
3007 !changed && M && M->getMethod(); M = M->getNext()) {
3008 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003009 changed = true;
3010 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003011 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003012 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003013 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003014 changed = true;
3015 }
3016 if (!changed)
3017 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003018 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003019 // A new method pool entry.
3020 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003021 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003022 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003023 }
3024
Douglas Gregorc78d3462009-04-24 21:10:55 +00003025 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003026 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003027 uint32_t BucketOffset;
3028 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003029 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003030 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003031 llvm::raw_svector_ostream Out(MethodPool);
3032 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003033 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003034 BucketOffset = Generator.Emit(Out, Trait);
3035 }
3036
3037 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003038 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003039 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003040 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003041 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003042 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3043 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3044
Douglas Gregor95c13f52009-04-25 17:48:32 +00003045 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003046 {
3047 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3048 NumTableEntries};
3049 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3050 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003051
3052 // Create a blob abbreviation for the selector table offsets.
3053 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003054 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003055 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003056 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003057 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3058 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3059
3060 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003061 {
3062 RecordData::value_type Record[] = {
3063 SELECTOR_OFFSETS, SelectorOffsets.size(),
3064 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3065 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3066 bytes(SelectorOffsets));
3067 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003068 }
3069}
3070
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003071/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003072void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003073 using namespace llvm;
3074 if (SemaRef.ReferencedSelectors.empty())
3075 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003076
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003077 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003078 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003079
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003080 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003081 // very tricky to fix, and given that @selector shouldn't really appear in
3082 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003083 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3084 Selector Sel = SelectorAndLocation.first;
3085 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003086 Writer.AddSelectorRef(Sel);
3087 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003088 }
Richard Smithe64e7452016-04-18 21:54:58 +00003089 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003090}
3091
Douglas Gregorc5046832009-04-27 18:38:38 +00003092//===----------------------------------------------------------------------===//
3093// Identifier Table Serialization
3094//===----------------------------------------------------------------------===//
3095
Richard Smithb3761912015-02-05 23:08:52 +00003096/// Determine the declaration that should be put into the name lookup table to
3097/// represent the given declaration in this module. This is usually D itself,
3098/// but if D was imported and merged into a local declaration, we want the most
3099/// recent local declaration instead. The chosen declaration will be the most
3100/// recent declaration in any module that imports this one.
3101static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3102 NamedDecl *D) {
3103 if (!LangOpts.Modules || !D->isFromASTFile())
3104 return D;
3105
3106 if (Decl *Redecl = D->getPreviousDecl()) {
3107 // For Redeclarable decls, a prior declaration might be local.
3108 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003109 // If we find a local decl, we're done.
3110 if (!Redecl->isFromASTFile()) {
3111 // Exception: in very rare cases (for injected-class-names), not all
3112 // redeclarations are in the same semantic context. Skip ones in a
3113 // different context. They don't go in this lookup table at all.
3114 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3115 D->getDeclContext()->getRedeclContext()))
3116 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003117 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003118 }
3119
Richard Smithfe620d22015-03-05 23:24:12 +00003120 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003121 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003122 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003123 break;
3124 }
3125 } else if (Decl *First = D->getCanonicalDecl()) {
3126 // For Mergeable decls, the first decl might be local.
3127 if (!First->isFromASTFile())
3128 return cast<NamedDecl>(First);
3129 }
3130
3131 // All declarations are imported. Our most recent declaration will also be
3132 // the most recent one in anyone who imports us.
3133 return D;
3134}
3135
Douglas Gregorc78d3462009-04-24 21:10:55 +00003136namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003137class ASTIdentifierTableTrait {
3138 ASTWriter &Writer;
3139 Preprocessor &PP;
3140 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003141 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003142 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003143 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003144
3145 /// \brief Determines whether this is an "interesting" identifier that needs a
3146 /// full IdentifierInfo structure written into the hash table. Notably, this
3147 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3148 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003149 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003150 if (MacroOffset ||
3151 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003152 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003153 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003154 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003155 return true;
3156
3157 return false;
3158 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003159
Douglas Gregore84a9da2009-04-20 20:36:09 +00003160public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003161 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003162 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003163
Sebastian Redl539c5062010-08-18 23:57:32 +00003164 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003165 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003166
Justin Bogner25463f12014-04-18 20:27:24 +00003167 typedef unsigned hash_value_type;
3168 typedef unsigned offset_type;
3169
Richard Smithd7329392015-04-21 21:46:32 +00003170 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003171 IdentifierResolver &IdResolver, bool IsModule,
3172 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003173 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003174 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3175 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003176
Richard Smithd79514e2016-02-05 19:03:40 +00003177 bool needDecls() const { return NeedDecls; }
3178
Justin Bogner25463f12014-04-18 20:27:24 +00003179 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003180 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
Richard Smith33e0f7e2015-07-22 02:08:40 +00003183 bool isInterestingIdentifier(const IdentifierInfo *II) {
3184 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3185 return isInterestingIdentifier(II, MacroOffset);
3186 }
Richard Smith9c254182015-07-19 21:41:12 +00003187 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3188 return isInterestingIdentifier(II, 0);
3189 }
3190
Mike Stump11289f42009-09-09 15:08:12 +00003191 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003192 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003193 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003194 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003195 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3196 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003197 DataLen += 2; // 2 bytes for builtin ID
3198 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003199 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003200 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003201
Richard Smitha534a312015-07-21 23:54:07 +00003202 if (NeedDecls) {
3203 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3204 DEnd = IdResolver.end();
3205 D != DEnd; ++D)
3206 DataLen += 4;
3207 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003208 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003209 using namespace llvm::support;
3210 endian::Writer<little> LE(Out);
3211
Richard Smithdf8a8312015-03-13 04:05:01 +00003212 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003213 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003214 // We emit the key length after the data length so that every
3215 // string is preceded by a 16-bit length. This matches the PTH
3216 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003217 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003218 return std::make_pair(KeyLen, DataLen);
3219 }
Mike Stump11289f42009-09-09 15:08:12 +00003220
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003221 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003222 unsigned KeyLen) {
3223 // Record the location of the key data. This is used when generating
3224 // the mapping from persistent IDs to strings.
3225 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003226
3227 // Emit the offset of the key/data length information to the interesting
3228 // identifiers table if necessary.
3229 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3230 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3231
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003232 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003233 }
Mike Stump11289f42009-09-09 15:08:12 +00003234
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003235 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003236 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003237 using namespace llvm::support;
3238 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003239
Richard Smithd7329392015-04-21 21:46:32 +00003240 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3241 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003242 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003243 return;
3244 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003245
Justin Bognere1c147c2014-03-28 22:03:19 +00003246 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003247 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3248 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003249 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003250 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003251 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003252 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003253 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3254 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003255 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003256 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003257 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003258 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003259
Richard Smithd7329392015-04-21 21:46:32 +00003260 if (HadMacroDefinition)
3261 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003262
Richard Smitha534a312015-07-21 23:54:07 +00003263 if (NeedDecls) {
3264 // Emit the declaration IDs in reverse order, because the
3265 // IdentifierResolver provides the declarations as they would be
3266 // visible (e.g., the function "stat" would come before the struct
3267 // "stat"), but the ASTReader adds declarations to the end of the list
3268 // (so we need to see the struct "stat" before the function "stat").
3269 // Only emit declarations that aren't from a chained PCH, though.
3270 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3271 IdResolver.end());
3272 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3273 DEnd = Decls.rend();
3274 D != DEnd; ++D)
3275 LE.write<uint32_t>(
3276 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3277 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003278 }
3279};
3280} // end anonymous namespace
3281
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003282/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003283///
3284/// The identifier table consists of a blob containing string data
3285/// (the actual identifiers themselves) and a separate "offsets" index
3286/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003287void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3288 IdentifierResolver &IdResolver,
3289 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003290 using namespace llvm;
3291
Richard Smith33e0f7e2015-07-22 02:08:40 +00003292 RecordData InterestingIdents;
3293
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003294 // Create and write out the blob that contains the identifier
3295 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003296 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003297 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003298 ASTIdentifierTableTrait Trait(
3299 *this, PP, IdResolver, IsModule,
3300 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregore6648fb2009-04-28 20:33:11 +00003302 // Look for any identifiers that were named while processing the
3303 // headers, but are otherwise not needed. We add these to the hash
3304 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003305 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003306 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003307 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003308 for (const auto &ID : PP.getIdentifierTable())
3309 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003310 // Sort the identifiers lexicographically before getting them references so
3311 // that their order is stable.
3312 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3313 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003314 if (Trait.isInterestingNonMacroIdentifier(II))
3315 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003316
Sebastian Redlff4a2952010-07-23 23:49:55 +00003317 // Create the on-disk hash table representation. We only store offsets
3318 // for identifiers that appear here for the first time.
3319 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003320 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003321 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003322 IdentID ID = IdentIDPair.second;
3323 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003324 // Write out identifiers if either the ID is local or the identifier has
3325 // changed since it was loaded.
3326 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3327 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003328 (Trait.needDecls() &&
3329 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003330 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003331 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003332
Douglas Gregore84a9da2009-04-20 20:36:09 +00003333 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003334 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003335 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003336 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003337 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003338 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003339 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003340 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003341 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003342 }
3343
3344 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003345 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003346 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003347 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003348 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003349 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003350
3351 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003352 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003353 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003354 }
3355
3356 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003357 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003358 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003359 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003360 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003361 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3362 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3363
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003364#ifndef NDEBUG
3365 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3366 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3367#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003368
3369 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3370 IdentifierOffsets.size(),
3371 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003372 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003373 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003374
3375 // In C++, write the list of interesting identifiers (those that are
3376 // defined as macros, poisoned, or similar unusual things).
3377 if (!InterestingIdents.empty())
3378 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003379}
3380
Douglas Gregorc5046832009-04-27 18:38:38 +00003381//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003382// DeclContext's Name Lookup Table Serialization
3383//===----------------------------------------------------------------------===//
3384
3385namespace {
3386// Trait used for the on-disk hash table used in the method pool.
3387class ASTDeclContextNameLookupTrait {
3388 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003389 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003390
3391public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003392 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003393 typedef key_type key_type_ref;
3394
Richard Smithd88a7f12015-09-01 20:35:42 +00003395 /// A start and end index into DeclIDs, representing a sequence of decls.
3396 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003397 typedef const data_type& data_type_ref;
3398
Justin Bogner25463f12014-04-18 20:27:24 +00003399 typedef unsigned hash_value_type;
3400 typedef unsigned offset_type;
3401
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003402 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3403
Richard Smithd88a7f12015-09-01 20:35:42 +00003404 template<typename Coll>
3405 data_type getData(const Coll &Decls) {
3406 unsigned Start = DeclIDs.size();
3407 for (NamedDecl *D : Decls) {
3408 DeclIDs.push_back(
3409 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3410 }
3411 return std::make_pair(Start, DeclIDs.size());
3412 }
3413
3414 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3415 unsigned Start = DeclIDs.size();
3416 for (auto ID : FromReader)
3417 DeclIDs.push_back(ID);
3418 return std::make_pair(Start, DeclIDs.size());
3419 }
3420
3421 static bool EqualKey(key_type_ref a, key_type_ref b) {
3422 return a == b;
3423 }
3424
Richard Smitha06c7e62015-08-26 23:55:49 +00003425 hash_value_type ComputeHash(DeclarationNameKey Name) {
3426 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003427 }
3428
Richard Smithd88a7f12015-09-01 20:35:42 +00003429 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3430 assert(Writer.hasChain() &&
3431 "have reference to loaded module file but no chain?");
3432
3433 using namespace llvm::support;
3434 endian::Writer<little>(Out)
3435 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3436 }
3437
Richard Smitha06c7e62015-08-26 23:55:49 +00003438 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3439 DeclarationNameKey Name,
3440 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003441 using namespace llvm::support;
3442 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003443 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003444 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003445 case DeclarationName::Identifier:
3446 case DeclarationName::ObjCZeroArgSelector:
3447 case DeclarationName::ObjCOneArgSelector:
3448 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003449 case DeclarationName::CXXLiteralOperatorName:
3450 KeyLen += 4;
3451 break;
3452 case DeclarationName::CXXOperatorName:
3453 KeyLen += 1;
3454 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003455 case DeclarationName::CXXConstructorName:
3456 case DeclarationName::CXXDestructorName:
3457 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003458 case DeclarationName::CXXUsingDirective:
3459 break;
3460 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003461 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003462
Richard Smithf02662d2015-07-30 03:17:16 +00003463 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003464 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3465 assert(uint16_t(DataLen) == DataLen &&
3466 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003467 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003468
3469 return std::make_pair(KeyLen, DataLen);
3470 }
3471
Richard Smitha06c7e62015-08-26 23:55:49 +00003472 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003473 using namespace llvm::support;
3474 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003475 LE.write<uint8_t>(Name.getKind());
3476 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003477 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003478 case DeclarationName::CXXLiteralOperatorName:
3479 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003480 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003481 case DeclarationName::ObjCZeroArgSelector:
3482 case DeclarationName::ObjCOneArgSelector:
3483 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003484 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003485 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003486 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003487 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003488 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003489 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003490 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003491 case DeclarationName::CXXConstructorName:
3492 case DeclarationName::CXXDestructorName:
3493 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003494 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003495 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003496 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003497
3498 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003499 }
3500
Richard Smitha06c7e62015-08-26 23:55:49 +00003501 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3502 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003503 using namespace llvm::support;
3504 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003505 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003506 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3507 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003508 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3509 }
3510};
3511} // end anonymous namespace
3512
Chandler Carruthe972c362015-03-26 03:11:40 +00003513bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3514 DeclContext *DC) {
3515 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3516}
3517
3518bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3519 DeclContext *DC) {
3520 for (auto *D : Result.getLookupResult())
3521 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3522 return false;
3523
3524 return true;
3525}
3526
Richard Smithd88a7f12015-09-01 20:35:42 +00003527void
Chandler Carruthe972c362015-03-26 03:11:40 +00003528ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003529 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003530 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3531 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003532 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003533
Chandler Carruthe972c362015-03-26 03:11:40 +00003534 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003535 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003536 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3537
3538 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003539 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3540 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003541 ASTDeclContextNameLookupTrait Trait(*this);
3542
Chandler Carruthe972c362015-03-26 03:11:40 +00003543 // The first step is to collect the declaration names which we need to
3544 // serialize into the name lookup table, and to collect them in a stable
3545 // order.
3546 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003547
Chandler Carruthe972c362015-03-26 03:11:40 +00003548 // We also build up small sets of the constructor and conversion function
3549 // names which are visible.
3550 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003551
Chandler Carruthe972c362015-03-26 03:11:40 +00003552 for (auto &Lookup : *DC->buildLookup()) {
3553 auto &Name = Lookup.first;
3554 auto &Result = Lookup.second;
3555
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003556 // If there are no local declarations in our lookup result, we
3557 // don't need to write an entry for the name at all. If we can't
3558 // write out a lookup set without performing more deserialization,
3559 // just skip this entry.
3560 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003561 isLookupResultEntirelyExternal(Result, DC))
3562 continue;
3563
3564 // We also skip empty results. If any of the results could be external and
3565 // the currently available results are empty, then all of the results are
3566 // external and we skip it above. So the only way we get here with an empty
3567 // results is when no results could have been external *and* we have
3568 // external results.
3569 //
3570 // FIXME: While we might want to start emitting on-disk entries for negative
3571 // lookups into a decl context as an optimization, today we *have* to skip
3572 // them because there are names with empty lookup results in decl contexts
3573 // which we can't emit in any stable ordering: we lookup constructors and
3574 // conversion functions in the enclosing namespace scope creating empty
3575 // results for them. This in almost certainly a bug in Clang's name lookup,
3576 // but that is likely to be hard or impossible to fix and so we tolerate it
3577 // here by omitting lookups with empty results.
3578 if (Lookup.second.getLookupResult().empty())
3579 continue;
3580
3581 switch (Lookup.first.getNameKind()) {
3582 default:
3583 Names.push_back(Lookup.first);
3584 break;
3585
Richard Smithcd45dbc2014-04-19 03:48:30 +00003586 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003587 assert(isa<CXXRecordDecl>(DC) &&
3588 "Cannot have a constructor name outside of a class!");
3589 ConstructorNameSet.insert(Name);
3590 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003591
3592 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003593 assert(isa<CXXRecordDecl>(DC) &&
3594 "Cannot have a conversion function name outside of a class!");
3595 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003596 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003597 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003598 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003599
Chandler Carruthe972c362015-03-26 03:11:40 +00003600 // Sort the names into a stable order.
3601 std::sort(Names.begin(), Names.end());
3602
Chandler Carruthffbf7052015-03-26 22:27:09 +00003603 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003604 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003605 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003606
Chandler Carruthffbf7052015-03-26 22:27:09 +00003607 // First we try the easy case by forming the current context's constructor
3608 // name and adding that name first. This is a very useful optimization to
3609 // avoid walking the lexical declarations in many cases, and it also
3610 // handles the only case where a constructor name can come from some other
3611 // lexical context -- when that name is an implicit constructor merged from
3612 // another declaration in the redecl chain. Any non-implicit constructor or
3613 // conversion function which doesn't occur in all the lexical contexts
3614 // would be an ODR violation.
3615 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3616 Context->getCanonicalType(Context->getRecordType(D)));
3617 if (ConstructorNameSet.erase(ImplicitCtorName))
3618 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003619
Chandler Carruthffbf7052015-03-26 22:27:09 +00003620 // If we still have constructors or conversion functions, we walk all the
3621 // names in the decl and add the constructors and conversion functions
3622 // which are visible in the order they lexically occur within the context.
3623 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3624 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3625 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3626 auto Name = ChildND->getDeclName();
3627 switch (Name.getNameKind()) {
3628 default:
3629 continue;
3630
3631 case DeclarationName::CXXConstructorName:
3632 if (ConstructorNameSet.erase(Name))
3633 Names.push_back(Name);
3634 break;
3635
3636 case DeclarationName::CXXConversionFunctionName:
3637 if (ConversionNameSet.erase(Name))
3638 Names.push_back(Name);
3639 break;
3640 }
3641
3642 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3643 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003644 }
3645
Chandler Carruthe972c362015-03-26 03:11:40 +00003646 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3647 "constructors by walking all the "
3648 "lexical members of the context.");
3649 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3650 "conversion functions by walking all "
3651 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003652 }
3653
Chandler Carruthe972c362015-03-26 03:11:40 +00003654 // Next we need to do a lookup with each name into this decl context to fully
3655 // populate any results from external sources. We don't actually use the
3656 // results of these lookups because we only want to use the results after all
3657 // results have been loaded and the pointers into them will be stable.
3658 for (auto &Name : Names)
3659 DC->lookup(Name);
3660
3661 // Now we need to insert the results for each name into the hash table. For
3662 // constructor names and conversion function names, we actually need to merge
3663 // all of the results for them into one list of results each and insert
3664 // those.
3665 SmallVector<NamedDecl *, 8> ConstructorDecls;
3666 SmallVector<NamedDecl *, 8> ConversionDecls;
3667
3668 // Now loop over the names, either inserting them or appending for the two
3669 // special cases.
3670 for (auto &Name : Names) {
3671 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3672
3673 switch (Name.getNameKind()) {
3674 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003675 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003676 break;
3677
3678 case DeclarationName::CXXConstructorName:
3679 ConstructorDecls.append(Result.begin(), Result.end());
3680 break;
3681
3682 case DeclarationName::CXXConversionFunctionName:
3683 ConversionDecls.append(Result.begin(), Result.end());
3684 break;
3685 }
3686 }
3687
3688 // Handle our two special cases if we ended up having any. We arbitrarily use
3689 // the first declaration's name here because the name itself isn't part of
3690 // the key, only the kind of name is used.
3691 if (!ConstructorDecls.empty())
3692 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003693 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003694 if (!ConversionDecls.empty())
3695 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003696 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003697
Richard Smithd88a7f12015-09-01 20:35:42 +00003698 // Create the on-disk hash table. Also emit the existing imported and
3699 // merged table if there is one.
3700 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3701 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003702}
3703
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003704/// \brief Write the block containing all of the declaration IDs
3705/// visible from the given DeclContext.
3706///
3707/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003708/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003709uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3710 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003711 // If we imported a key declaration of this namespace, write the visible
3712 // lookup results as an update record for it rather than including them
3713 // on this declaration. We will only look at key declarations on reload.
3714 if (isa<NamespaceDecl>(DC) && Chain &&
3715 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3716 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003717 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003718 Prev = Prev->getPreviousDecl())
3719 if (!Prev->isFromASTFile())
3720 return 0;
3721
3722 // Note that we need to emit an update record for the primary context.
3723 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3724
3725 // Make sure all visible decls are written. They will be recorded later. We
3726 // do this using a side data structure so we can sort the names into
3727 // a deterministic order.
3728 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3729 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3730 LookupResults;
3731 if (Map) {
3732 LookupResults.reserve(Map->size());
3733 for (auto &Entry : *Map)
3734 LookupResults.push_back(
3735 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3736 }
3737
3738 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3739 for (auto &NameAndResult : LookupResults) {
3740 DeclarationName Name = NameAndResult.first;
3741 DeclContext::lookup_result Result = NameAndResult.second;
3742 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3743 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3744 // We have to work around a name lookup bug here where negative lookup
3745 // results for these names get cached in namespace lookup tables (these
3746 // names should never be looked up in a namespace).
3747 assert(Result.empty() && "Cannot have a constructor or conversion "
3748 "function name in a namespace!");
3749 continue;
3750 }
3751
3752 for (NamedDecl *ND : Result)
3753 if (!ND->isFromASTFile())
3754 GetDeclRef(ND);
3755 }
3756
3757 return 0;
3758 }
3759
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003760 if (DC->getPrimaryContext() != DC)
3761 return 0;
3762
Chandler Carruthe972c362015-03-26 03:11:40 +00003763 // Skip contexts which don't support name lookup.
3764 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003765 return 0;
3766
3767 // If not in C++, we perform name lookup for the translation unit via the
3768 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003769 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003770 return 0;
3771
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003772 // Serialize the contents of the mapping used for lookup. Note that,
3773 // although we have two very different code paths, the serialized
3774 // representation is the same for both cases: a declaration name,
3775 // followed by a size, followed by references to the visible
3776 // declarations that have that name.
3777 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003778 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003779 if (!Map || Map->empty())
3780 return 0;
3781
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003782 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003783 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003784 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003785
3786 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003787 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003788 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003789 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003790 ++NumVisibleDeclContexts;
3791 return Offset;
3792}
3793
Sebastian Redla4071b42010-08-24 00:50:09 +00003794/// \brief Write an UPDATE_VISIBLE block for the given context.
3795///
3796/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3797/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003798/// (in C++), for namespaces, and for classes with forward-declared unscoped
3799/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003800void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003801 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003802 if (!Map || Map->empty())
3803 return;
3804
Sebastian Redla4071b42010-08-24 00:50:09 +00003805 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003806 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003807 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003808
Richard Smith5fc18a92015-07-12 23:43:21 +00003809 // If we're updating a namespace, select a key declaration as the key for the
3810 // update record; those are the only ones that will be checked on reload.
3811 if (isa<NamespaceDecl>(DC))
3812 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3813
Sebastian Redla4071b42010-08-24 00:50:09 +00003814 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003815 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003816 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003817}
3818
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003819/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3820void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003821 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003822 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3823}
3824
3825/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3826void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003827 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003828 return;
3829
3830 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3831 RecordData Record;
3832#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3833#include "clang/Basic/OpenCLExtensions.def"
3834 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3835}
3836
Douglas Gregor404cdde2012-01-27 01:47:08 +00003837void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003838 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003839 RecordData Categories;
3840
3841 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3842 unsigned Size = 0;
3843 unsigned StartIndex = Categories.size();
3844
3845 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3846
3847 // Allocate space for the size.
3848 Categories.push_back(0);
3849
3850 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003851 for (ObjCInterfaceDecl::known_categories_iterator
3852 Cat = Class->known_categories_begin(),
3853 CatEnd = Class->known_categories_end();
3854 Cat != CatEnd; ++Cat, ++Size) {
3855 assert(getDeclID(*Cat) != 0 && "Bogus category");
3856 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003857 }
3858
3859 // Update the size.
3860 Categories[StartIndex] = Size;
3861
3862 // Record this interface -> category map.
3863 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3864 CategoriesMap.push_back(CatInfo);
3865 }
3866
3867 // Sort the categories map by the definition ID, since the reader will be
3868 // performing binary searches on this information.
3869 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3870
3871 // Emit the categories map.
3872 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003873
3874 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003875 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3878 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003879
3880 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3881 Stream.EmitRecordWithBlob(AbbrevID, Record,
3882 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003883 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003884
Douglas Gregor404cdde2012-01-27 01:47:08 +00003885 // Emit the category lists.
3886 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3887}
3888
Richard Smithe40f2ba2013-08-07 21:41:30 +00003889void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3890 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3891
3892 if (LPTMap.empty())
3893 return;
3894
3895 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003896 for (auto LPTMapEntry : LPTMap) {
3897 const FunctionDecl *FD = LPTMapEntry.first;
3898 LateParsedTemplate *LPT = LPTMapEntry.second;
3899 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003900 AddDeclRef(LPT->D, Record);
3901 Record.push_back(LPT->Toks.size());
3902
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003903 for (const auto &Tok : LPT->Toks) {
3904 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003905 }
3906 }
3907 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3908}
3909
Dario Domizioli13a0a382014-05-23 12:13:25 +00003910/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3911void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3912 RecordData Record;
3913 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3914 AddSourceLocation(PragmaLoc, Record);
3915 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3916}
3917
Nico Weber779355f2016-03-02 23:22:00 +00003918/// \brief Write the state of 'pragma ms_struct' at the end of the module.
3919void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3920 RecordData Record;
3921 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3922 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3923}
3924
Nico Weber42932312016-03-03 00:17:35 +00003925/// \brief Write the state of 'pragma pointers_to_members' at the end of the
3926//module.
3927void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3928 RecordData Record;
3929 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3930 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3931 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3932}
3933
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003934void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3935 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003936 // Enter the extension block.
3937 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3938
3939 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003940 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003941 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3942 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3943 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3944 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3945 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3946 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3947 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3948
3949 // Emit the metadata record.
3950 RecordData Record;
3951 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3952 Record.push_back(EXTENSION_METADATA);
3953 Record.push_back(Metadata.MajorVersion);
3954 Record.push_back(Metadata.MinorVersion);
3955 Record.push_back(Metadata.BlockName.size());
3956 Record.push_back(Metadata.UserInfo.size());
3957 SmallString<64> Buffer;
3958 Buffer += Metadata.BlockName;
3959 Buffer += Metadata.UserInfo;
3960 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3961
3962 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003963 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003964
3965 // Exit the extension block.
3966 Stream.ExitBlock();
3967}
3968
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003969//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003970// General Serialization Routines
3971//===----------------------------------------------------------------------===//
3972
Richard Smith69c82bf2016-04-01 22:52:03 +00003973/// \brief Emit the list of attributes to the specified record.
Richard Smith290d8012016-04-06 17:06:00 +00003974void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
3975 auto &Record = *this;
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003976 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003977 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003978 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Richard Smith290d8012016-04-06 17:06:00 +00003979 Record.AddSourceRange(A->getRange());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003980
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003981#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00003982
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003983 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003984}
3985
John McCallf413f5e2013-05-03 00:10:13 +00003986void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3987 AddSourceLocation(Tok.getLocation(), Record);
3988 Record.push_back(Tok.getLength());
3989
3990 // FIXME: When reading literal tokens, reconstruct the literal pointer
3991 // if it is needed.
3992 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3993 // FIXME: Should translate token kind to a stable encoding.
3994 Record.push_back(Tok.getKind());
3995 // FIXME: Should translate token flags to a stable encoding.
3996 Record.push_back(Tok.getFlags());
3997}
3998
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003999void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004000 Record.push_back(Str.size());
4001 Record.insert(Record.end(), Str.begin(), Str.end());
4002}
4003
Richard Smith7ed1bc92014-12-05 22:42:13 +00004004bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004005 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004006
Richard Smith54cc3c22014-12-11 20:50:24 +00004007 bool Changed =
4008 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004009
4010 // Remove a prefix to make the path relative, if relevant.
4011 const char *PathBegin = Path.data();
4012 const char *PathPtr =
4013 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4014 if (PathPtr != PathBegin) {
4015 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4016 Changed = true;
4017 }
4018
4019 return Changed;
4020}
4021
4022void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4023 SmallString<128> FilePath(Path);
4024 PreparePathForOutput(FilePath);
4025 AddString(FilePath, Record);
4026}
4027
Mehdi Amini57a41912015-09-10 01:46:39 +00004028void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004029 StringRef Path) {
4030 SmallString<128> FilePath(Path);
4031 PreparePathForOutput(FilePath);
4032 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4033}
4034
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004035void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4036 RecordDataImpl &Record) {
4037 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004038 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004039 Record.push_back(*Minor + 1);
4040 else
4041 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004042 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004043 Record.push_back(*Subminor + 1);
4044 else
4045 Record.push_back(0);
4046}
4047
Douglas Gregore84a9da2009-04-20 20:36:09 +00004048/// \brief Note that the identifier II occurs at the given offset
4049/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004050void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004051 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004052 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004053 // up earlier in the chain and thus don't need an offset.
4054 if (ID >= FirstIdentID)
4055 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004056}
4057
Douglas Gregor95c13f52009-04-25 17:48:32 +00004058/// \brief Note that the selector Sel occurs at the given offset
4059/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004060void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004061 unsigned ID = SelectorIDs[Sel];
4062 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004063 // Don't record offsets for selectors that are also available in a different
4064 // file.
4065 if (ID < FirstSelectorID)
4066 return;
4067 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004068}
4069
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004070ASTWriter::ASTWriter(
4071 llvm::BitstreamWriter &Stream,
4072 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4073 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004074 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004075 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4076 WritingAST(false), DoneWritingDeclsAndTypes(false),
4077 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4078 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4079 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4080 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4081 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004082 NextSubmoduleID(FirstSubmoduleID),
4083 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
Richard Smith290d8012016-04-06 17:06:00 +00004084 NumStatements(0), NumMacros(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004085 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004086 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004087 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004088 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004089 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004090 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4091 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004092 ExprImplicitCastAbbrev(0) {
4093 for (const auto &Ext : Extensions) {
4094 if (auto Writer = Ext->createExtensionWriter(*this))
4095 ModuleFileExtensionWriters.push_back(std::move(Writer));
4096 }
4097}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004098
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004099ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004100 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004101}
4102
Richard Smithb3761912015-02-05 23:08:52 +00004103const LangOptions &ASTWriter::getLangOpts() const {
4104 assert(WritingAST && "can't determine lang opts when not writing AST");
4105 return Context->getLangOpts();
4106}
4107
Richard Smithe75ee0f2015-08-17 07:13:32 +00004108time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4109 return IncludeTimestamps ? E->getModificationTime() : 0;
4110}
4111
Adrian Prantladbd2b12015-09-22 23:26:31 +00004112uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4113 Module *WritingModule, StringRef isysroot,
4114 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004115 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004116
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004117 ASTHasCompilerErrors = hasErrors;
4118
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004119 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004120 Stream.Emit((unsigned)'C', 8);
4121 Stream.Emit((unsigned)'P', 8);
4122 Stream.Emit((unsigned)'C', 8);
4123 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004124
Chris Lattner28fa4e62009-04-26 22:26:21 +00004125 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004126
Douglas Gregoreda8e122011-08-09 15:13:55 +00004127 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004128 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004129 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004130 ASTFileSignature Signature =
4131 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004132 Context = nullptr;
4133 PP = nullptr;
4134 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004135 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004136
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004137 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004138 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004139}
4140
Douglas Gregora94a1542011-07-27 21:45:57 +00004141template<typename Vector>
4142static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4143 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004144 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4145 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004146 Writer.AddDeclRef(*I, Record);
4147 }
4148}
4149
Adrian Prantladbd2b12015-09-22 23:26:31 +00004150uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4151 const std::string &OutputFile,
4152 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004153 using namespace llvm;
4154
Craig Toppera13603a2014-05-22 05:54:18 +00004155 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004156
Douglas Gregorcf68c582011-12-01 22:20:10 +00004157 // Make sure that the AST reader knows to finalize itself.
4158 if (Chain)
4159 Chain->finalizeForWriting();
4160
Sebastian Redl143413f2010-07-12 22:02:52 +00004161 ASTContext &Context = SemaRef.Context;
4162 Preprocessor &PP = SemaRef.PP;
4163
Douglas Gregordab42432011-08-12 00:15:20 +00004164 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004165 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4166 if (D) {
4167 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4168 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004169 }
4170 };
4171 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4172 PREDEF_DECL_TRANSLATION_UNIT_ID);
4173 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4174 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4175 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4176 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4177 PREDEF_DECL_OBJC_PROTOCOL_ID);
4178 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4179 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4180 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4181 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4182 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004183 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004184 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4185 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004186 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004187 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4188 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004189 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4190 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004191 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4192 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004193
Chris Lattner0c797362009-09-08 18:19:27 +00004194 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004195 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004196 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004197 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004198 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004199
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004200 // Build a record containing all of the file scoped decls in this file.
4201 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004202 if (!isModule)
4203 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4204 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004205
Douglas Gregor851443c2011-08-12 01:39:19 +00004206 // Build a record containing all of the delegating constructors we still need
4207 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004208 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004209 if (!isModule)
4210 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004211
Douglas Gregor851443c2011-08-12 01:39:19 +00004212 // Write the set of weak, undeclared identifiers. We always write the
4213 // entire table, since later PCH files in a PCH chain are only interested in
4214 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004215 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004216 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4217 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4218 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4219 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4220 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4221 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4222 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004223 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004224
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004225 // Build a record containing all of the ext_vector declarations.
4226 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004227 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004228
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004229 // Build a record containing all of the VTable uses information.
4230 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004231 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004232 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4233 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4234 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4235 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4236 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004237 }
4238
Nico Weber72889432014-09-06 01:25:55 +00004239 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4240 RecordData UnusedLocalTypedefNameCandidates;
4241 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4242 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4243
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004244 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004245 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004246 for (const auto &I : SemaRef.PendingInstantiations) {
4247 AddDeclRef(I.first, PendingInstantiations);
4248 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004249 }
4250 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4251 "There are local ones at end of translation unit!");
4252
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004253 // Build a record containing some declaration references.
4254 RecordData SemaDeclRefs;
4255 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4256 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4257 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4258 }
4259
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004260 RecordData CUDASpecialDeclRefs;
4261 if (Context.getcudaConfigureCallDecl()) {
4262 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4263 }
4264
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004265 // Build a record containing all of the known namespaces.
4266 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004267 for (const auto &I : SemaRef.KnownNamespaces) {
4268 if (!I.second)
4269 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004270 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004271
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004272 // Build a record of all used, undefined objects that require definitions.
4273 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004274
4275 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004276 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004277 for (const auto &I : Undefined) {
4278 AddDeclRef(I.first, UndefinedButUsed);
4279 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004280 }
4281
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004282 // Build a record containing all delete-expressions that we would like to
4283 // analyze later in AST.
4284 RecordData DeleteExprsToAnalyze;
4285
4286 for (const auto &DeleteExprsInfo :
4287 SemaRef.getMismatchingDeleteExpressions()) {
4288 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4289 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4290 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4291 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4292 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4293 }
4294 }
4295
Douglas Gregor112b9072012-10-18 05:31:06 +00004296 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004297 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004298
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004299 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004300 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004301
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004302 // This is so that older clang versions, before the introduction
4303 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004304 {
4305 RecordData Record = {VERSION_MAJOR};
4306 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4307 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004308
Douglas Gregor851443c2011-08-12 01:39:19 +00004309 // Create a lexical update block containing all of the declarations in the
4310 // translation unit that do not come from other AST files.
4311 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004312 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4313 for (const auto *D : TU->noload_decls()) {
4314 if (!D->isFromASTFile()) {
4315 NewGlobalKindDeclPairs.push_back(D->getKind());
4316 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4317 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004318 }
4319
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004320 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004321 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4322 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4323 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004324 {
4325 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4326 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4327 bytes(NewGlobalKindDeclPairs));
4328 }
4329
Douglas Gregor851443c2011-08-12 01:39:19 +00004330 // And a visible updates block for the translation unit.
4331 Abv = new llvm::BitCodeAbbrev();
4332 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4333 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004334 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4335 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4336 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004337
4338 // If we have any extern "C" names, write out a visible update for them.
4339 if (Context.ExternCContext)
4340 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004341
4342 // If the translation unit has an anonymous namespace, and we don't already
4343 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004344 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004345 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4346 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004347 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004348 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004349 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004350
Richard Smith5652c0f2014-03-21 01:48:23 +00004351 // Add update records for all mangling numbers and static local numbers.
4352 // These aren't really update records, but this is a convenient way of
4353 // tagging this rare extra data onto the declarations.
4354 for (const auto &Number : Context.MangleNumbers)
4355 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004356 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4357 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004358 for (const auto &Number : Context.StaticLocalNumbers)
4359 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004360 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4361 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004362
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004363 // Make sure visible decls, added to DeclContexts previously loaded from
4364 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004365 for (const auto *I : UpdatingVisibleDecls) {
4366 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004367 }
4368
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004369 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004370 // serialization, if we're storing decls with identifiers.
4371 if (!WritingModule || !getLangOpts().CPlusPlus) {
4372 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004373 for (const auto &ID : PP.getIdentifierTable()) {
4374 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004375 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4376 IIs.push_back(II);
4377 }
4378 // Sort the identifiers to visit based on their name.
4379 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4380 for (const IdentifierInfo *II : IIs) {
4381 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4382 DEnd = SemaRef.IdResolver.end();
4383 D != DEnd; ++D) {
4384 GetDeclRef(*D);
4385 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004386 }
4387 }
4388
Manman Rena0f31a02016-04-29 19:04:05 +00004389 // For method pool in the module, if it contains an entry for a selector,
4390 // the entry should be complete, containing everything introduced by that
4391 // module and all modules it imports. It's possible that the entry is out of
4392 // date, so we need to pull in the new content here.
4393
4394 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4395 // safe, we copy all selectors out.
4396 llvm::SmallVector<Selector, 256> AllSelectors;
4397 for (auto &SelectorAndID : SelectorIDs)
4398 AllSelectors.push_back(SelectorAndID.first);
4399 for (auto &Selector : AllSelectors)
4400 SemaRef.updateOutOfDateSelector(Selector);
4401
Douglas Gregor5204bde2011-08-02 16:26:37 +00004402 // Form the record of special types.
4403 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004404 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004405 AddTypeRef(Context.getFILEType(), SpecialTypes);
4406 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4407 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4408 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4409 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004410 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004411 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004412
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004413 if (Chain) {
4414 // Write the mapping information describing our module dependencies and how
4415 // each of those modules were mapped into our own offset/ID space, so that
4416 // the reader can build the appropriate mapping to its own offset/ID space.
4417 // The map consists solely of a blob with the following format:
4418 // *(module-name-len:i16 module-name:len*i8
4419 // source-location-offset:i32
4420 // identifier-id:i32
4421 // preprocessed-entity-id:i32
4422 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004423 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004424 // selector-id:i32
4425 // declaration-id:i32
4426 // c++-base-specifiers-id:i32
4427 // type-id:i32)
4428 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004429 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004430 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4432 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004433 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004434 {
4435 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004436 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004437 using namespace llvm::support;
4438 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004439 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004440 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004441 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004442
Ben Langmuir785180e2014-10-20 16:27:30 +00004443 // Note: if a base ID was uint max, it would not be possible to load
4444 // another module after it or have more than one entity inside it.
4445 uint32_t None = std::numeric_limits<uint32_t>::max();
4446
4447 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4448 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4449 if (ShouldWrite)
4450 LE.write<uint32_t>(BaseID);
4451 else
4452 LE.write<uint32_t>(None);
4453 };
4454
Ben Langmuirfe971d92014-08-16 04:54:18 +00004455 // These values should be unique within a chain, since they will be read
4456 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004457 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4458 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4459 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4460 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4461 M->NumPreprocessedEntities);
4462 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4463 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4464 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4465 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004466 }
4467 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004468 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004469 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4470 Buffer.data(), Buffer.size());
4471 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004472
Richard Smithb9eab6d2014-03-20 19:44:17 +00004473 RecordData DeclUpdatesOffsetsRecord;
4474
Richard Smith59442b42014-03-20 20:07:19 +00004475 // Keep writing types, declarations, and declaration update records
4476 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004477 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4478 WriteTypeAbbrevs();
4479 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004480 do {
4481 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4482 while (!DeclTypesToEmit.empty()) {
4483 DeclOrType DOT = DeclTypesToEmit.front();
4484 DeclTypesToEmit.pop();
4485 if (DOT.isType())
4486 WriteType(DOT.getType());
4487 else
4488 WriteDecl(Context, DOT.getDecl());
4489 }
4490 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004491 Stream.ExitBlock();
4492
Richard Smithb9eab6d2014-03-20 19:44:17 +00004493 DoneWritingDeclsAndTypes = true;
4494
4495 // These things can only be done once we've written out decls and types.
4496 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004497 if (!DeclUpdatesOffsetsRecord.empty())
4498 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004499 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004500 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004501 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004502 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004503 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004504 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004505 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004506 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004507 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004508 WriteFPPragmaOptions(SemaRef.getFPOptions());
4509 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004510 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004511
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004512 // If we're emitting a module, write out the submodule information.
4513 if (WritingModule)
4514 WriteSubmodules(WritingModule);
4515
Douglas Gregor5204bde2011-08-02 16:26:37 +00004516 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4517
Douglas Gregord4df8652009-04-22 22:02:47 +00004518 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004519 if (!EagerlyDeserializedDecls.empty())
4520 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004521
4522 // Write the record containing tentative definitions.
4523 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004524 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004525
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004526 // Write the record containing unused file scoped decls.
4527 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004528 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004529
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004530 // Write the record containing weak undeclared identifiers.
4531 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004532 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004533 WeakUndeclaredIdentifiers);
4534
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004535 // Write the record containing ext_vector type names.
4536 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004537 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004539 // Write the record containing VTable uses information.
4540 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004541 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004542
Nico Weber72889432014-09-06 01:25:55 +00004543 // Write the record containing potentially unused local typedefs.
4544 if (!UnusedLocalTypedefNameCandidates.empty())
4545 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4546 UnusedLocalTypedefNameCandidates);
4547
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004548 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004549 if (!PendingInstantiations.empty())
4550 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004551
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004552 // Write the record containing declaration references of Sema.
4553 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004554 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004555
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004556 // Write the record containing CUDA-specific declaration references.
4557 if (!CUDASpecialDeclRefs.empty())
4558 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004559
4560 // Write the delegating constructors.
4561 if (!DelegatingCtorDecls.empty())
4562 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004563
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004564 // Write the known namespaces.
4565 if (!KnownNamespaces.empty())
4566 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004567
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004568 // Write the undefined internal functions and variables, and inline functions.
4569 if (!UndefinedButUsed.empty())
4570 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004571
4572 if (!DeleteExprsToAnalyze.empty())
4573 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4574
Douglas Gregor851443c2011-08-12 01:39:19 +00004575 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004576 for (auto *DC : UpdatedDeclContexts)
4577 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004578
Douglas Gregor959bb062011-12-03 01:15:29 +00004579 if (!WritingModule) {
4580 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004581 struct ModuleInfo {
4582 uint64_t ID;
4583 Module *M;
4584 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4585 };
Richard Smith56be7542014-03-21 00:33:59 +00004586 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004587 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004588 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004589 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4590 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004591 }
Richard Smith56be7542014-03-21 00:33:59 +00004592
4593 if (!Imports.empty()) {
4594 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4595 return A.ID < B.ID;
4596 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004597 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4598 return A.ID == B.ID;
4599 };
Richard Smith56be7542014-03-21 00:33:59 +00004600
4601 // Sort and deduplicate module IDs.
4602 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004603 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004604 Imports.end());
4605
4606 RecordData ImportedModules;
4607 for (const auto &Import : Imports) {
4608 ImportedModules.push_back(Import.ID);
4609 // FIXME: If the module has macros imported then later has declarations
4610 // imported, this location won't be the right one as a location for the
4611 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004612 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004613 }
4614
Douglas Gregor959bb062011-12-03 01:15:29 +00004615 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4616 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004617 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004618
Douglas Gregor404cdde2012-01-27 01:47:08 +00004619 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004620 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004621 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004622 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004623 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004624 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00004625
Douglas Gregor08f01292009-04-17 22:13:46 +00004626 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004627 RecordData::value_type Record[] = {
4628 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004629 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004630 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004631
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004632 // Write the module file extension blocks.
4633 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004634 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004635
Adrian Prantladbd2b12015-09-22 23:26:31 +00004636 return Signature;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004637}
4638
Richard Smithb9eab6d2014-03-20 19:44:17 +00004639void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004640 if (DeclUpdates.empty())
4641 return;
4642
Richard Smith59442b42014-03-20 20:07:19 +00004643 DeclUpdateMap LocalUpdates;
4644 LocalUpdates.swap(DeclUpdates);
4645
Richard Smith6ef42932014-03-20 21:02:00 +00004646 for (auto &DeclUpdate : LocalUpdates) {
4647 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004648
Richard Smithd28ac5b2014-03-22 23:33:22 +00004649 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004650 RecordData RecordData;
4651 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004652 for (auto &Update : DeclUpdate.second) {
4653 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4654
Richard Smith69c82bf2016-04-01 22:52:03 +00004655 // An updated body is emitted last, so that the reader doesn't need
4656 // to skip over the lazy body to reach statements for other records.
4657 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4658 HasUpdatedBody = true;
4659 else
4660 Record.push_back(Kind);
4661
Richard Smith6ef42932014-03-20 21:02:00 +00004662 switch (Kind) {
4663 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4664 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4665 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004666 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004667 Record.push_back(GetDeclRef(Update.getDecl()));
4668 break;
4669
Richard Smith4d235792014-08-07 18:53:08 +00004670 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004671 break;
4672
Richard Smith4d235792014-08-07 18:53:08 +00004673 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
Richard Smith69c82bf2016-04-01 22:52:03 +00004674 Record.AddSourceLocation(Update.getLoc());
Richard Smith4d235792014-08-07 18:53:08 +00004675 break;
4676
John McCall32791cc2016-01-06 22:34:54 +00004677 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004678 Record.AddStmt(const_cast<Expr *>(
4679 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004680 break;
4681
Richard Smithcd45dbc2014-04-19 03:48:30 +00004682 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4683 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004684 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00004685 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004686 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004687 *Context, const_cast<CXXRecordDecl *>(RD)));
4688
4689 // This state is sometimes updated by template instantiation, when we
4690 // switch from the specialization referring to the template declaration
4691 // to it referring to the template definition.
4692 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4693 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004694 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004695 } else {
4696 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4697 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004698 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004699
4700 // The instantiation might have been resolved to a partial
4701 // specialization. If so, record which one.
4702 auto From = Spec->getInstantiatedFrom();
4703 if (auto PartialSpec =
4704 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4705 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004706 Record.AddDeclRef(PartialSpec);
4707 Record.AddTemplateArgumentList(
4708 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004709 } else {
4710 Record.push_back(false);
4711 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004712 }
4713 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004714 Record.AddSourceLocation(RD->getLocation());
4715 Record.AddSourceLocation(RD->getLocStart());
4716 Record.AddSourceLocation(RD->getRBraceLoc());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004717
4718 // Instantiation may change attributes; write them all out afresh.
4719 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004720 if (D->hasAttrs())
4721 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004722
4723 // FIXME: Ensure we don't get here for explicit instantiations.
4724 break;
4725 }
4726
Richard Smithf8134002015-03-10 01:41:22 +00004727 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004728 Record.AddDeclRef(Update.getDecl());
Richard Smithf8134002015-03-10 01:41:22 +00004729 break;
4730
Richard Smith564417a2014-03-20 21:47:22 +00004731 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4732 addExceptionSpec(
Richard Smith564417a2014-03-20 21:47:22 +00004733 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4734 Record);
4735 break;
4736
Richard Smith6ef42932014-03-20 21:02:00 +00004737 case UPD_CXX_DEDUCED_RETURN_TYPE:
4738 Record.push_back(GetOrCreateTypeID(Update.getType()));
4739 break;
4740
4741 case UPD_DECL_MARKED_USED:
4742 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004743
4744 case UPD_MANGLING_NUMBER:
4745 case UPD_STATIC_LOCAL_NUMBER:
4746 Record.push_back(Update.getNumber());
4747 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004748
Alexey Bataev97720002014-11-11 04:05:39 +00004749 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004750 Record.AddSourceRange(
4751 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004752 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004753
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004754 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4755 Record.AddSourceRange(
4756 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4757 break;
4758
Richard Smith65ebb4a2015-03-26 04:09:53 +00004759 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004760 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004761 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004762
4763 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004764 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004765 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004766 }
4767 }
4768
Richard Smithd28ac5b2014-03-22 23:33:22 +00004769 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004770 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004771 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004772 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00004773 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00004774 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004775 }
4776
Richard Smithcd45dbc2014-04-19 03:48:30 +00004777 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00004778 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004779 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004780}
4781
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004782void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00004783 uint32_t Raw = Loc.getRawEncoding();
4784 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004785}
4786
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004787void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004788 AddSourceLocation(Range.getBegin(), Record);
4789 AddSourceLocation(Range.getEnd(), Record);
4790}
4791
Richard Smithf144b542016-04-08 21:54:32 +00004792void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4793 Record->push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004794 const uint64_t *Words = Value.getRawData();
Richard Smithf144b542016-04-08 21:54:32 +00004795 Record->append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004796}
4797
Richard Smithf144b542016-04-08 21:54:32 +00004798void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4799 Record->push_back(Value.isUnsigned());
4800 AddAPInt(Value);
Douglas Gregor1daeb692009-04-13 18:14:40 +00004801}
4802
Richard Smithf144b542016-04-08 21:54:32 +00004803void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4804 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00004805}
4806
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004807void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004808 Record.push_back(getIdentifierRef(II));
4809}
4810
Sebastian Redl539c5062010-08-18 23:57:32 +00004811IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004812 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004813 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004814
Sebastian Redl539c5062010-08-18 23:57:32 +00004815 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004816 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004817 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004818 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004819}
4820
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004821MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004822 // Don't emit builtin macros like __LINE__ to the AST file unless they
4823 // have been redefined by the header (in which case they are not
4824 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004825 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004826 return 0;
4827
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004828 MacroID &ID = MacroIDs[MI];
4829 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004830 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004831 MacroInfoToEmitData Info = { Name, MI, ID };
4832 MacroInfosToEmit.push_back(Info);
4833 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004834 return ID;
4835}
4836
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004837MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004838 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004839 return 0;
4840
4841 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4842 return MacroIDs[MI];
4843}
4844
4845uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004846 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004847}
4848
Richard Smithe64e7452016-04-18 21:54:58 +00004849void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
4850 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00004851}
4852
Sebastian Redl539c5062010-08-18 23:57:32 +00004853SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004854 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004855 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004856 }
4857
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004858 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004859 if (SID == 0 && Chain) {
4860 // This might trigger a ReadSelector callback, which will set the ID for
4861 // this selector.
4862 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004863 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004864 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004865 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004866 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004867 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004868 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004869 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004870}
4871
Richard Smithe64e7452016-04-18 21:54:58 +00004872void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
4873 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00004874}
4875
Richard Smith290d8012016-04-06 17:06:00 +00004876void ASTRecordWriter::AddTemplateArgumentLocInfo(
4877 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004878 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004879 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004880 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004881 break;
4882 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00004883 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00004884 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004885 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00004886 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4887 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004888 break;
4889 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00004890 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4891 AddSourceLocation(Arg.getTemplateNameLoc());
4892 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004893 break;
John McCall0ad16662009-10-29 08:12:44 +00004894 case TemplateArgument::Null:
4895 case TemplateArgument::Integral:
4896 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004897 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004898 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004899 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004900 break;
4901 }
4902}
4903
Richard Smith290d8012016-04-06 17:06:00 +00004904void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
4905 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004906
4907 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4908 bool InfoHasSameExpr
4909 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00004910 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004911 if (InfoHasSameExpr)
4912 return; // Avoid storing the same expr twice.
4913 }
Richard Smith290d8012016-04-06 17:06:00 +00004914 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004915}
4916
Richard Smith290d8012016-04-06 17:06:00 +00004917void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00004918 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00004919 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00004920 return;
4921 }
4922
Richard Smith290d8012016-04-06 17:06:00 +00004923 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004924}
4925
Richard Smith290d8012016-04-06 17:06:00 +00004926void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
4927 AddTypeRef(TL.getType());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004928
Richard Smith290d8012016-04-06 17:06:00 +00004929 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004930 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004931 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004932}
4933
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004934void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004935 Record.push_back(GetOrCreateTypeID(T));
4936}
4937
Richard Smith2095ffe2015-03-16 20:11:03 +00004938TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004939 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004940 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4941 if (T.isNull())
4942 return TypeIdx();
4943 assert(!T.getLocalFastQualifiers());
4944
4945 TypeIdx &Idx = TypeIdxs[T];
4946 if (Idx.getIndex() == 0) {
4947 if (DoneWritingDeclsAndTypes) {
4948 assert(0 && "New type seen after serializing all the types to emit!");
4949 return TypeIdx();
4950 }
4951
4952 // We haven't seen this type before. Assign it a new ID and put it
4953 // into the queue of types to emit.
4954 Idx = TypeIdx(NextTypeID++);
4955 DeclTypesToEmit.push(T);
4956 }
4957 return Idx;
4958 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004959}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004960
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004961TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004962 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004963 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4964 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004965 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004966 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004967
Richard Smith2095ffe2015-03-16 20:11:03 +00004968 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4969 assert(I != TypeIdxs.end() && "Type not emitted!");
4970 return I->second;
4971 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004972}
4973
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004974void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004975 Record.push_back(GetDeclRef(D));
4976}
4977
Sebastian Redl539c5062010-08-18 23:57:32 +00004978DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004979 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00004980
4981 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00004982 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004983 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00004984
4985 // If D comes from an AST file, its declaration ID is already known and
4986 // fixed.
4987 if (D->isFromASTFile())
4988 return D->getGlobalID();
4989
Douglas Gregor9b3932c2010-10-05 18:37:06 +00004990 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00004991 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00004992 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004993 if (DoneWritingDeclsAndTypes) {
4994 assert(0 && "New decl seen after serializing all the decls to emit!");
4995 return 0;
4996 }
4997
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004998 // We haven't seen this declaration before. Give it a new ID and
4999 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005000 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005001 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005002 }
5003
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005004 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005005}
5006
Sebastian Redl539c5062010-08-18 23:57:32 +00005007DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005008 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005009 return 0;
5010
Douglas Gregorb3163e52012-01-05 22:33:30 +00005011 // If D comes from an AST file, its declaration ID is already known and
5012 // fixed.
5013 if (D->isFromASTFile())
5014 return D->getGlobalID();
5015
Douglas Gregore84a9da2009-04-20 20:36:09 +00005016 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5017 return DeclIDs[D];
5018}
5019
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005020void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005021 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005022 assert(D);
5023
5024 SourceLocation Loc = D->getLocation();
5025 if (Loc.isInvalid())
5026 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005027
5028 // We only keep track of the file-level declarations of each file.
5029 if (!D->getLexicalDeclContext()->isFileContext())
5030 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005031 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5032 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005033 if (isa<ParmVarDecl>(D))
5034 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005035
5036 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005037 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005038 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005039 FileID FID;
5040 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005041 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005042 if (FID.isInvalid())
5043 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005044 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005045
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005046 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005047 if (!Info)
5048 Info = new DeclIDInFileInfo();
5049
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005050 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005051 LocDeclIDsTy &Decls = Info->DeclIDs;
5052
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005053 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005054 Decls.push_back(LocDecl);
5055 return;
5056 }
5057
Benjamin Kramer45025c02013-08-24 13:22:59 +00005058 LocDeclIDsTy::iterator I =
5059 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005060
5061 Decls.insert(I, LocDecl);
5062}
5063
Richard Smithe64e7452016-04-18 21:54:58 +00005064void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
Chris Lattner258172e2009-04-27 07:35:58 +00005065 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Richard Smithe64e7452016-04-18 21:54:58 +00005066 Record->push_back(Name.getNameKind());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005067 switch (Name.getNameKind()) {
5068 case DeclarationName::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005069 AddIdentifierRef(Name.getAsIdentifierInfo());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005070 break;
5071
5072 case DeclarationName::ObjCZeroArgSelector:
5073 case DeclarationName::ObjCOneArgSelector:
5074 case DeclarationName::ObjCMultiArgSelector:
Richard Smithe64e7452016-04-18 21:54:58 +00005075 AddSelectorRef(Name.getObjCSelector());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005076 break;
5077
5078 case DeclarationName::CXXConstructorName:
5079 case DeclarationName::CXXDestructorName:
5080 case DeclarationName::CXXConversionFunctionName:
Richard Smithe64e7452016-04-18 21:54:58 +00005081 AddTypeRef(Name.getCXXNameType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005082 break;
5083
5084 case DeclarationName::CXXOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005085 Record->push_back(Name.getCXXOverloadedOperator());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005086 break;
5087
Alexis Hunt3d221f22009-11-29 07:34:05 +00005088 case DeclarationName::CXXLiteralOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005089 AddIdentifierRef(Name.getCXXLiteralIdentifier());
Alexis Hunt3d221f22009-11-29 07:34:05 +00005090 break;
5091
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005092 case DeclarationName::CXXUsingDirective:
5093 // No extra data to emit
5094 break;
5095 }
5096}
Chris Lattnerca025db2010-05-07 21:43:38 +00005097
Richard Smithd08aeb62014-08-28 01:33:39 +00005098unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5099 assert(needsAnonymousDeclarationNumber(D) &&
5100 "expected an anonymous declaration");
5101
5102 // Number the anonymous declarations within this context, if we've not
5103 // already done so.
5104 auto It = AnonymousDeclarationNumbers.find(D);
5105 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005106 auto *DC = D->getLexicalDeclContext();
5107 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5108 AnonymousDeclarationNumbers[ND] = Number;
5109 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005110
5111 It = AnonymousDeclarationNumbers.find(D);
5112 assert(It != AnonymousDeclarationNumbers.end() &&
5113 "declaration not found within its lexical context");
5114 }
5115
5116 return It->second;
5117}
5118
Richard Smith290d8012016-04-06 17:06:00 +00005119void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5120 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005121 switch (Name.getNameKind()) {
5122 case DeclarationName::CXXConstructorName:
5123 case DeclarationName::CXXDestructorName:
5124 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005125 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005126 break;
5127
5128 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005129 AddSourceLocation(SourceLocation::getFromRawEncoding(
5130 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005131 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005132 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005133 break;
5134
5135 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005136 AddSourceLocation(SourceLocation::getFromRawEncoding(
5137 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005138 break;
5139
5140 case DeclarationName::Identifier:
5141 case DeclarationName::ObjCZeroArgSelector:
5142 case DeclarationName::ObjCOneArgSelector:
5143 case DeclarationName::ObjCMultiArgSelector:
5144 case DeclarationName::CXXUsingDirective:
5145 break;
5146 }
5147}
5148
Richard Smith290d8012016-04-06 17:06:00 +00005149void ASTRecordWriter::AddDeclarationNameInfo(
5150 const DeclarationNameInfo &NameInfo) {
5151 AddDeclarationName(NameInfo.getName());
5152 AddSourceLocation(NameInfo.getLoc());
5153 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005154}
5155
Richard Smith290d8012016-04-06 17:06:00 +00005156void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5157 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5158 Record->push_back(Info.NumTemplParamLists);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005159 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005160 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005161}
5162
Richard Smithe64e7452016-04-18 21:54:58 +00005163void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005164 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005165 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005166 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005167
5168 // Push each of the NNS's onto a stack for serialization in reverse order.
5169 while (NNS) {
5170 NestedNames.push_back(NNS);
5171 NNS = NNS->getPrefix();
5172 }
5173
Richard Smithe64e7452016-04-18 21:54:58 +00005174 Record->push_back(NestedNames.size());
Chris Lattnerca025db2010-05-07 21:43:38 +00005175 while(!NestedNames.empty()) {
5176 NNS = NestedNames.pop_back_val();
5177 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
Richard Smithe64e7452016-04-18 21:54:58 +00005178 Record->push_back(Kind);
Chris Lattnerca025db2010-05-07 21:43:38 +00005179 switch (Kind) {
5180 case NestedNameSpecifier::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005181 AddIdentifierRef(NNS->getAsIdentifier());
Chris Lattnerca025db2010-05-07 21:43:38 +00005182 break;
5183
5184 case NestedNameSpecifier::Namespace:
Richard Smithe64e7452016-04-18 21:54:58 +00005185 AddDeclRef(NNS->getAsNamespace());
Chris Lattnerca025db2010-05-07 21:43:38 +00005186 break;
5187
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005188 case NestedNameSpecifier::NamespaceAlias:
Richard Smithe64e7452016-04-18 21:54:58 +00005189 AddDeclRef(NNS->getAsNamespaceAlias());
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005190 break;
5191
Chris Lattnerca025db2010-05-07 21:43:38 +00005192 case NestedNameSpecifier::TypeSpec:
5193 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smithe64e7452016-04-18 21:54:58 +00005194 AddTypeRef(QualType(NNS->getAsType(), 0));
5195 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Chris Lattnerca025db2010-05-07 21:43:38 +00005196 break;
5197
5198 case NestedNameSpecifier::Global:
5199 // Don't need to write an associated value.
5200 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005201
5202 case NestedNameSpecifier::Super:
Richard Smithe64e7452016-04-18 21:54:58 +00005203 AddDeclRef(NNS->getAsRecordDecl());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005204 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005205 }
5206 }
5207}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005208
Richard Smith290d8012016-04-06 17:06:00 +00005209void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005210 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005211 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005212 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005213
5214 // Push each of the nested-name-specifiers's onto a stack for
5215 // serialization in reverse order.
5216 while (NNS) {
5217 NestedNames.push_back(NNS);
5218 NNS = NNS.getPrefix();
5219 }
5220
Richard Smith290d8012016-04-06 17:06:00 +00005221 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005222 while(!NestedNames.empty()) {
5223 NNS = NestedNames.pop_back_val();
5224 NestedNameSpecifier::SpecifierKind Kind
5225 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005226 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005227 switch (Kind) {
5228 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005229 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5230 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005231 break;
5232
5233 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005234 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5235 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005236 break;
5237
5238 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005239 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5240 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005241 break;
5242
5243 case NestedNameSpecifier::TypeSpec:
5244 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005245 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5246 AddTypeLoc(NNS.getTypeLoc());
5247 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005248 break;
5249
5250 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005251 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005252 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005253
5254 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005255 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5256 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005257 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005258 }
5259 }
5260}
5261
Richard Smith290d8012016-04-06 17:06:00 +00005262void ASTRecordWriter::AddTemplateName(TemplateName Name) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005263 TemplateName::NameKind Kind = Name.getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005264 Record->push_back(Kind);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005265 switch (Kind) {
5266 case TemplateName::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005267 AddDeclRef(Name.getAsTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005268 break;
5269
5270 case TemplateName::OverloadedTemplate: {
5271 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
Richard Smith290d8012016-04-06 17:06:00 +00005272 Record->push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005273 for (const auto &I : *OvT)
Richard Smith290d8012016-04-06 17:06:00 +00005274 AddDeclRef(I);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005275 break;
5276 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005277
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005278 case TemplateName::QualifiedTemplate: {
5279 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005280 AddNestedNameSpecifier(QualT->getQualifier());
5281 Record->push_back(QualT->hasTemplateKeyword());
5282 AddDeclRef(QualT->getTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005283 break;
5284 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005285
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005286 case TemplateName::DependentTemplate: {
5287 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005288 AddNestedNameSpecifier(DepT->getQualifier());
5289 Record->push_back(DepT->isIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005290 if (DepT->isIdentifier())
Richard Smith290d8012016-04-06 17:06:00 +00005291 AddIdentifierRef(DepT->getIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005292 else
Richard Smith290d8012016-04-06 17:06:00 +00005293 Record->push_back(DepT->getOperator());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005294 break;
5295 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005296
5297 case TemplateName::SubstTemplateTemplateParm: {
5298 SubstTemplateTemplateParmStorage *subst
5299 = Name.getAsSubstTemplateTemplateParm();
Richard Smith290d8012016-04-06 17:06:00 +00005300 AddDeclRef(subst->getParameter());
5301 AddTemplateName(subst->getReplacement());
John McCalld9dfe3a2011-06-30 08:33:18 +00005302 break;
5303 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005304
5305 case TemplateName::SubstTemplateTemplateParmPack: {
5306 SubstTemplateTemplateParmPackStorage *SubstPack
5307 = Name.getAsSubstTemplateTemplateParmPack();
Richard Smith290d8012016-04-06 17:06:00 +00005308 AddDeclRef(SubstPack->getParameterPack());
5309 AddTemplateArgument(SubstPack->getArgumentPack());
Douglas Gregor5590be02011-01-15 06:45:20 +00005310 break;
5311 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005312 }
5313}
5314
Richard Smith290d8012016-04-06 17:06:00 +00005315void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5316 Record->push_back(Arg.getKind());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005317 switch (Arg.getKind()) {
5318 case TemplateArgument::Null:
5319 break;
5320 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005321 AddTypeRef(Arg.getAsType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005322 break;
5323 case TemplateArgument::Declaration:
Richard Smith290d8012016-04-06 17:06:00 +00005324 AddDeclRef(Arg.getAsDecl());
5325 AddTypeRef(Arg.getParamTypeForDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00005326 break;
5327 case TemplateArgument::NullPtr:
Richard Smith290d8012016-04-06 17:06:00 +00005328 AddTypeRef(Arg.getNullPtrType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005329 break;
5330 case TemplateArgument::Integral:
Richard Smith290d8012016-04-06 17:06:00 +00005331 AddAPSInt(Arg.getAsIntegral());
5332 AddTypeRef(Arg.getIntegralType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005333 break;
5334 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005335 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
Douglas Gregore1d60df2011-01-14 23:41:42 +00005336 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005337 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005338 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
David Blaikie05785d12013-02-20 22:23:23 +00005339 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Richard Smith290d8012016-04-06 17:06:00 +00005340 Record->push_back(*NumExpansions + 1);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005341 else
Richard Smith290d8012016-04-06 17:06:00 +00005342 Record->push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005343 break;
5344 case TemplateArgument::Expression:
5345 AddStmt(Arg.getAsExpr());
5346 break;
5347 case TemplateArgument::Pack:
Richard Smith290d8012016-04-06 17:06:00 +00005348 Record->push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005349 for (const auto &P : Arg.pack_elements())
Richard Smith290d8012016-04-06 17:06:00 +00005350 AddTemplateArgument(P);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005351 break;
5352 }
5353}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005354
Richard Smithe64e7452016-04-18 21:54:58 +00005355void ASTRecordWriter::AddTemplateParameterList(
5356 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005357 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005358 AddSourceLocation(TemplateParams->getTemplateLoc());
5359 AddSourceLocation(TemplateParams->getLAngleLoc());
5360 AddSourceLocation(TemplateParams->getRAngleLoc());
5361 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005362 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005363 AddDeclRef(P);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005364}
5365
5366/// \brief Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005367void ASTRecordWriter::AddTemplateArgumentList(
5368 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005369 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005370 Record->push_back(TemplateArgs->size());
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005371 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005372 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005373}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005374
Richard Smith290d8012016-04-06 17:06:00 +00005375void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5376 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005377 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005378 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5379 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5380 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005381 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5382 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005383 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005384}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005385
Richard Smithe64e7452016-04-18 21:54:58 +00005386void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5387 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005388 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005389 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005390 AddDeclRef(I.getDecl());
5391 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005392 }
5393}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005394
Richard Smith290d8012016-04-06 17:06:00 +00005395// FIXME: Move this out of the main ASTRecordWriter interface.
5396void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5397 Record->push_back(Base.isVirtual());
5398 Record->push_back(Base.isBaseOfClass());
5399 Record->push_back(Base.getAccessSpecifierAsWritten());
5400 Record->push_back(Base.getInheritConstructors());
5401 AddTypeSourceInfo(Base.getTypeSourceInfo());
5402 AddSourceRange(Base.getSourceRange());
Douglas Gregor752a5952011-01-03 22:36:02 +00005403 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005404 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005405}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005406
Richard Smith645d2cf2016-04-14 00:29:55 +00005407static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5408 ArrayRef<CXXBaseSpecifier> Bases) {
5409 ASTWriter::RecordData Record;
5410 ASTRecordWriter Writer(W, Record);
5411 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005412
Richard Smith645d2cf2016-04-14 00:29:55 +00005413 for (auto &Base : Bases)
5414 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005415
Richard Smith645d2cf2016-04-14 00:29:55 +00005416 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005417}
5418
Richard Smith290d8012016-04-06 17:06:00 +00005419// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005420void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5421 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5422}
5423
Richard Smithaa165cf2016-04-13 21:57:08 +00005424static uint64_t
5425EmitCXXCtorInitializers(ASTWriter &W,
5426 ArrayRef<CXXCtorInitializer *> CtorInits) {
5427 ASTWriter::RecordData Record;
5428 ASTRecordWriter Writer(W, Record);
5429 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005430
Richard Smithaa165cf2016-04-13 21:57:08 +00005431 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005432 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005433 Writer.push_back(CTOR_INITIALIZER_BASE);
5434 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5435 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005436 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005437 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5438 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005439 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005440 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5441 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005442 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005443 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5444 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005445 }
Francois Pichetd583da02010-12-04 09:14:42 +00005446
Richard Smithaa165cf2016-04-13 21:57:08 +00005447 Writer.AddSourceLocation(Init->getMemberLocation());
5448 Writer.AddStmt(Init->getInit());
5449 Writer.AddSourceLocation(Init->getLParenLoc());
5450 Writer.AddSourceLocation(Init->getRParenLoc());
5451 Writer.push_back(Init->isWritten());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005452 if (Init->isWritten()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005453 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005454 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005455 Writer.push_back(Init->getNumArrayIndices());
5456 for (auto *VD : Init->getArrayIndices())
5457 Writer.AddDeclRef(VD);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005458 }
5459 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005460
5461 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005462}
5463
Richard Smithaa165cf2016-04-13 21:57:08 +00005464// FIXME: Move this out of the main ASTRecordWriter interface.
5465void ASTRecordWriter::AddCXXCtorInitializers(
5466 ArrayRef<CXXCtorInitializer *> CtorInits) {
5467 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005468}
5469
Richard Smith290d8012016-04-06 17:06:00 +00005470void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005471 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005472 Record->push_back(Data.IsLambda);
5473 Record->push_back(Data.UserDeclaredConstructor);
5474 Record->push_back(Data.UserDeclaredSpecialMembers);
5475 Record->push_back(Data.Aggregate);
5476 Record->push_back(Data.PlainOldData);
5477 Record->push_back(Data.Empty);
5478 Record->push_back(Data.Polymorphic);
5479 Record->push_back(Data.Abstract);
5480 Record->push_back(Data.IsStandardLayout);
5481 Record->push_back(Data.HasNoNonEmptyBases);
5482 Record->push_back(Data.HasPrivateFields);
5483 Record->push_back(Data.HasProtectedFields);
5484 Record->push_back(Data.HasPublicFields);
5485 Record->push_back(Data.HasMutableFields);
5486 Record->push_back(Data.HasVariantMembers);
5487 Record->push_back(Data.HasOnlyCMembers);
5488 Record->push_back(Data.HasInClassInitializer);
5489 Record->push_back(Data.HasUninitializedReferenceMember);
5490 Record->push_back(Data.HasUninitializedFields);
Richard Smith12e79312016-05-13 06:47:56 +00005491 Record->push_back(Data.HasInheritedConstructor);
5492 Record->push_back(Data.HasInheritedAssignment);
Richard Smith290d8012016-04-06 17:06:00 +00005493 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5494 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5495 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5496 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5497 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5498 Record->push_back(Data.DefaultedDestructorIsDeleted);
5499 Record->push_back(Data.HasTrivialSpecialMembers);
5500 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5501 Record->push_back(Data.HasIrrelevantDestructor);
5502 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5503 Record->push_back(Data.HasDefaultedDefaultConstructor);
5504 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5505 Record->push_back(Data.HasConstexprDefaultConstructor);
5506 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5507 Record->push_back(Data.ComputedVisibleConversions);
5508 Record->push_back(Data.UserProvidedDefaultConstructor);
5509 Record->push_back(Data.DeclaredSpecialMembers);
5510 Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5511 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5512 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5513 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005514 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005515
Richard Smith290d8012016-04-06 17:06:00 +00005516 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005517 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005518 AddCXXBaseSpecifiers(Data.bases());
5519
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005520 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005521 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005522 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005523 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005524
Richard Smith290d8012016-04-06 17:06:00 +00005525 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5526 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005527 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005528 AddDeclRef(D->getFirstFriend());
Douglas Gregor99ae8062012-02-14 17:54:36 +00005529
5530 // Add lambda-specific data.
5531 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005532 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005533 Record->push_back(Lambda.Dependent);
5534 Record->push_back(Lambda.IsGenericLambda);
5535 Record->push_back(Lambda.CaptureDefault);
5536 Record->push_back(Lambda.NumCaptures);
5537 Record->push_back(Lambda.NumExplicitCaptures);
5538 Record->push_back(Lambda.ManglingNumber);
5539 AddDeclRef(Lambda.ContextDecl);
5540 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005541 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005542 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005543 AddSourceLocation(Capture.getLocation());
5544 Record->push_back(Capture.isImplicit());
5545 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005546 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005547 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005548 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005549 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005550 break;
5551 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005552 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005553 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005554 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005555 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005556 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005557 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005558 break;
5559 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005560 }
5561 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005562}
5563
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005564void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005565 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005566 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005567 assert(FirstDeclID == NextDeclID &&
5568 FirstTypeID == NextTypeID &&
5569 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005570 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005571 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005572 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005573 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005574
Sebastian Redl07a89a82010-07-30 00:29:29 +00005575 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005576
Richard Smith7f330cd2015-03-18 01:42:29 +00005577 // Note, this will get called multiple times, once one the reader starts up
5578 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005579 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5580 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5581 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005582 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005583 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005584 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005585 NextDeclID = FirstDeclID;
5586 NextTypeID = FirstTypeID;
5587 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005588 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005589 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005590 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005591}
5592
Sebastian Redl539c5062010-08-18 23:57:32 +00005593void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005594 // Always keep the highest ID. See \p TypeRead() for more information.
5595 IdentID &StoredID = IdentifierIDs[II];
5596 if (ID > StoredID)
5597 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005598}
5599
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005600void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005601 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005602 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005603 if (ID > StoredID)
5604 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005605}
5606
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005607void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005608 // Always take the highest-numbered type index. This copes with an interesting
5609 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005610 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005611 // keep the higher-numbered entry so that we can properly write it out to
5612 // the AST file.
5613 TypeIdx &StoredIdx = TypeIdxs[T];
5614 if (Idx.getIndex() >= StoredIdx.getIndex())
5615 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005616}
5617
Sebastian Redl539c5062010-08-18 23:57:32 +00005618void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005619 // Always keep the highest ID. See \p TypeRead() for more information.
5620 SelectorID &StoredID = SelectorIDs[S];
5621 if (ID > StoredID)
5622 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005623}
Douglas Gregor91096292010-10-02 19:29:26 +00005624
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005625void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005626 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005627 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005628 MacroDefinitions[MD] = ID;
5629}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005630
Douglas Gregore37a85a2011-12-02 17:30:13 +00005631void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5632 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5633 SubmoduleIDs[Mod] = ID;
5634}
5635
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005636void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005637 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005638 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005639 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005640 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005641 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005642 // A forward reference was mutated into a definition. Rewrite it.
5643 // FIXME: This happens during template instantiation, should we
5644 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005645 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5646 "completed a tag from another module but not by instantiation?");
5647 DeclUpdates[RD].push_back(
5648 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005649 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005650 }
5651}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005652
Richard Smithf983f7f2015-10-13 00:23:25 +00005653static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5654 if (D->isFromASTFile())
5655 return true;
5656
Richard Smithf983f7f2015-10-13 00:23:25 +00005657 // The predefined __va_list_tag struct is imported if we imported any decls.
5658 // FIXME: This is a gross hack.
5659 return D == D->getASTContext().getVaListTagDecl();
5660}
5661
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005662void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005663 assert(DC->isLookupContext() &&
5664 "Should not add lookup results to non-lookup contexts!");
5665
Vassil Vassilev632eac32016-03-16 11:17:04 +00005666 // TU is handled elsewhere.
5667 if (isa<TranslationUnitDecl>(DC))
5668 return;
5669
5670 // Namespaces are handled elsewhere, except for template instantiations of
5671 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5672 // local instantiations are added to an imported context. Only happens when
5673 // adding ADL lookup candidates, for example templated friends.
5674 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5675 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005676 return;
5677
Richard Smithf983f7f2015-10-13 00:23:25 +00005678 // We're only interested in cases where a local declaration is added to an
5679 // imported context.
5680 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5681 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005682
Richard Smith0f4e2c42015-08-06 04:23:48 +00005683 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005684 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005685 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005686 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5687 // We're adding a visible declaration to a predefined decl context. Ensure
5688 // that we write out all of its lookup results so we don't get a nasty
5689 // surprise when we try to emit its lookup table.
5690 for (auto *Child : DC->decls())
5691 UpdatingVisibleDecls.push_back(Child);
5692 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005693 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005694}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005695
5696void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5697 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005698
5699 // We're only interested in cases where a local declaration is added to an
5700 // imported context.
5701 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5702 return;
5703
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005704 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005705 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005706
5707 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005708 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005709 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005710 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005711}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005712
Richard Smith564417a2014-03-20 21:47:22 +00005713void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005714 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5715 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005716 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005717 // If we don't already know the exception specification for this redecl
5718 // chain, add an update record for it.
5719 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5720 ->getType()
5721 ->castAs<FunctionProtoType>()
5722 ->getExceptionSpecType()))
5723 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5724 });
Richard Smith564417a2014-03-20 21:47:22 +00005725}
5726
Richard Smith1fa5d642013-05-11 05:45:24 +00005727void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5728 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005729 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005730 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005731 DeclUpdates[D].push_back(
5732 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5733 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005734}
5735
Richard Smithf8134002015-03-10 01:41:22 +00005736void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5737 const FunctionDecl *Delete) {
5738 assert(!WritingAST && "Already writing the AST!");
5739 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005740 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005741 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005742 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5743 });
Richard Smithf8134002015-03-10 01:41:22 +00005744}
5745
Sebastian Redlab238a72011-04-24 16:28:06 +00005746void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005747 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005748 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005749 return; // Declaration not imported from PCH.
5750
Richard Smith4d235792014-08-07 18:53:08 +00005751 // Implicit function decl from a PCH was defined.
5752 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005753}
5754
Richard Smithd28ac5b2014-03-22 23:33:22 +00005755void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5756 assert(!WritingAST && "Already writing the AST!");
5757 if (!D->isFromASTFile())
5758 return;
5759
Richard Smith9e2341d2015-03-23 03:25:59 +00005760 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005761}
5762
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005763void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005764 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005765 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005766 return;
5767
5768 // Since the actual instantiation is delayed, this really means that we need
5769 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005770 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005771 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5772 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005773}
5774
John McCall32791cc2016-01-06 22:34:54 +00005775void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5776 assert(!WritingAST && "Already writing the AST!");
5777 if (!D->isFromASTFile())
5778 return;
5779
5780 DeclUpdates[D].push_back(
5781 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5782}
5783
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005784void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5785 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005786 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005787 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005788 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005789
5790 assert(IFD->getDefinition() && "Category on a class without a definition?");
5791 ObjCClassesWithCategories.insert(
5792 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005793}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005794
Eli Friedman276dd182013-09-05 00:02:25 +00005795void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5796 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00005797
5798 // If there is *any* declaration of the entity that's not from an AST file,
5799 // we can skip writing the update record. We make sure that isUsed() triggers
5800 // completion of the redeclaration chain of the entity.
5801 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5802 if (IsLocalDecl(Prev))
5803 return;
Eli Friedman276dd182013-09-05 00:02:25 +00005804
Aaron Ballman4f45b712014-03-21 15:22:56 +00005805 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005806}
Alexey Bataev97720002014-11-11 04:05:39 +00005807
5808void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5809 assert(!WritingAST && "Already writing the AST!");
5810 if (!D->isFromASTFile())
5811 return;
5812
5813 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5814}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005815
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005816void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5817 const Attr *Attr) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005818 assert(!WritingAST && "Already writing the AST!");
5819 if (!D->isFromASTFile())
5820 return;
5821
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005822 DeclUpdates[D].push_back(
5823 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005824}
5825
Richard Smith4caa4492015-05-15 02:34:32 +00005826void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00005827 assert(!WritingAST && "Already writing the AST!");
5828 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005829 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005830}
Alex Denisovfde64952015-06-26 05:28:36 +00005831
5832void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5833 const RecordDecl *Record) {
5834 assert(!WritingAST && "Already writing the AST!");
5835 if (!Record->isFromASTFile())
5836 return;
5837 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5838}