blob: 8c5863e28ae6a4ad240d2d62c63024e7ed49e4df [file] [log] [blame]
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
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"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000015#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000016#include "ASTReaderInternals.h"
17#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTUnresolvedSet.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000020#include "clang/AST/Attr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Decl.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000022#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/AST/DeclCXX.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000024#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000025#include "clang/AST/DeclFriend.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000026#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000028#include "clang/AST/DeclarationName.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000029#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000030#include "clang/AST/ExprCXX.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000031#include "clang/AST/LambdaCapture.h"
32#include "clang/AST/NestedNameSpecifier.h"
33#include "clang/AST/RawCommentList.h"
34#include "clang/AST/TemplateName.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000036#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000037#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000038#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000039#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000041#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000042#include "clang/Basic/LLVM.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000043#include "clang/Basic/Lambda.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000044#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000045#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/Module.h"
47#include "clang/Basic/ObjCRuntime.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000048#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/SourceLocation.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000050#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000051#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000052#include "clang/Basic/Specifiers.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000053#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000054#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000055#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000056#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Lex/HeaderSearch.h"
58#include "clang/Lex/HeaderSearchOptions.h"
59#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Lex/ModuleMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Lex/PreprocessingRecord.h"
62#include "clang/Lex/Preprocessor.h"
63#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000064#include "clang/Lex/Token.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000065#include "clang/Sema/IdentifierResolver.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000067#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include "clang/Sema/Weak.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000069#include "clang/Serialization/ASTReader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000070#include "clang/Serialization/Module.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000071#include "clang/Serialization/ModuleFileExtension.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000072#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000073#include "llvm/ADT/APFloat.h"
74#include "llvm/ADT/APInt.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000075#include "llvm/ADT/APSInt.h"
76#include "llvm/ADT/ArrayRef.h"
77#include "llvm/ADT/DenseMap.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000078#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000079#include "llvm/ADT/Optional.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000080#include "llvm/ADT/PointerIntPair.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000081#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000082#include "llvm/ADT/SmallSet.h"
83#include "llvm/ADT/SmallString.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000084#include "llvm/ADT/SmallVector.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000085#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000086#include "llvm/ADT/StringMap.h"
87#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include "llvm/Bitcode/BitCodes.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089#include "llvm/Bitcode/BitstreamWriter.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000090#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +000091#include "llvm/Support/Compression.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000092#include "llvm/Support/Endian.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000093#include "llvm/Support/EndianStream.h"
George Rimarc39f5492017-01-17 15:45:31 +000094#include "llvm/Support/Error.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000095#include "llvm/Support/ErrorHandling.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000096#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000097#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000098#include "llvm/Support/Path.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000099#include "llvm/Support/SHA1.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000100#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000101#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include <cassert>
103#include <cstdint>
104#include <cstdlib>
105#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000106#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000107#include <deque>
108#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000109#include <memory>
110#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000111#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000112#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000113#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000114
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000115using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000116using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000117
Sebastian Redl3df5a082010-07-30 17:03:48 +0000118template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000119static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 if (v.empty()) return StringRef();
121 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000122 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000123}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000124
125template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000126static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000128 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000129}
130
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131//===----------------------------------------------------------------------===//
132// Type serialization
133//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000134
Richard Smith290d8012016-04-06 17:06:00 +0000135namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000136
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000137 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000138 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +0000139 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000140
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000141 /// \brief Type code that corresponds to the record generated.
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000142 TypeCode Code = static_cast<TypeCode>(0);
143
Richard Smith01b2cb42014-07-26 06:37:51 +0000144 /// \brief Abbreviation to use for the record, if any.
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000145 unsigned AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000146
Richard Smith290d8012016-04-06 17:06:00 +0000147 public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000148 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000149 : Writer(Writer), Record(Writer, Record) {}
Richard Smith290d8012016-04-06 17:06:00 +0000150
151 uint64_t Emit() {
152 return Record.Emit(Code, AbbrevToUse);
153 }
154
155 void Visit(QualType T) {
156 if (T.hasLocalNonFastQualifiers()) {
157 Qualifiers Qs = T.getLocalQualifiers();
158 Record.AddTypeRef(T.getLocalUnqualifiedType());
159 Record.push_back(Qs.getAsOpaqueValue());
160 Code = TYPE_EXT_QUAL;
161 AbbrevToUse = Writer.TypeExtQualAbbrev;
162 } else {
163 switch (T->getTypeClass()) {
164 // For all of the concrete, non-dependent types, call the
165 // appropriate visitor function.
166#define TYPE(Class, Base) \
167 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
168#define ABSTRACT_TYPE(Class, Base)
169#include "clang/AST/TypeNodes.def"
170 }
171 }
172 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000173
174 void VisitArrayType(const ArrayType *T);
175 void VisitFunctionType(const FunctionType *T);
176 void VisitTagType(const TagType *T);
177
178#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
179#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000180#include "clang/AST/TypeNodes.def"
181 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000182
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000183} // namespace clang
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000184
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000185void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000186 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000187}
188
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000189void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000190 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000191 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000192}
193
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000194void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000195 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000196 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000197}
198
Reid Kleckner8a365022013-06-24 17:51:48 +0000199void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000200 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000201 Code = TYPE_DECAYED;
202}
203
Reid Kleckner0503a872013-12-05 01:23:43 +0000204void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000205 Record.AddTypeRef(T->getOriginalType());
206 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000207 Code = TYPE_ADJUSTED;
208}
209
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000210void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000211 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000212 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000213}
214
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000215void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000216 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000217 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000218 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000219}
220
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000221void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000222 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000223 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000224}
225
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000226void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000227 Record.AddTypeRef(T->getPointeeType());
228 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000229 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000230}
231
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000232void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000233 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000234 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000235 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000236}
237
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000238void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000239 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000241 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000242}
243
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000244void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000245 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000246 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000247}
248
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000249void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000250 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000251 Record.AddSourceLocation(T->getLBracketLoc());
252 Record.AddSourceLocation(T->getRBracketLoc());
Richard Smith290d8012016-04-06 17:06:00 +0000253 Record.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000254 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255}
256
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000257void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000258 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000259 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000260 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000261 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000262}
263
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000264void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000265 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000266 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000267}
268
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000269void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000270 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000271 FunctionType::ExtInfo C = T->getExtInfo();
272 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000273 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000274 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000275 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000276 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000277 Record.push_back(C.getProducesResult());
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000278 Record.push_back(C.getNoCallerSavedRegs());
Richard Smith01b2cb42014-07-26 06:37:51 +0000279
280 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
281 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000282}
283
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000284void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000285 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000286 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287}
288
Richard Smith290d8012016-04-06 17:06:00 +0000289static void addExceptionSpec(const FunctionProtoType *T,
290 ASTRecordWriter &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000291 Record.push_back(T->getExceptionSpecType());
292 if (T->getExceptionSpecType() == EST_Dynamic) {
293 Record.push_back(T->getNumExceptions());
294 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000295 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000296 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smith290d8012016-04-06 17:06:00 +0000297 Record.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000298 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000299 Record.AddDeclRef(T->getExceptionSpecDecl());
300 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000301 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000302 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000303 }
Richard Smith564417a2014-03-20 21:47:22 +0000304}
305
306void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
307 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000308
Richard Smith564417a2014-03-20 21:47:22 +0000309 Record.push_back(T->isVariadic());
310 Record.push_back(T->hasTrailingReturn());
311 Record.push_back(T->getTypeQuals());
312 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Richard Smith290d8012016-04-06 17:06:00 +0000313 addExceptionSpec(T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000314
315 Record.push_back(T->getNumParams());
316 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000317 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000318
John McCall18afab72016-03-01 00:49:02 +0000319 if (T->hasExtParameterInfos()) {
320 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
321 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
322 }
323
Richard Smith01b2cb42014-07-26 06:37:51 +0000324 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000325 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
326 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000327 AbbrevToUse = 0;
328
Sebastian Redl539c5062010-08-18 23:57:32 +0000329 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000330}
331
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000332void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000334 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000335}
John McCallb96ec562009-12-04 22:46:56 +0000336
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000337void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000338 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000339 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000340 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000341 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342}
343
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000344void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Richard Smith290d8012016-04-06 17:06:00 +0000345 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000346 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000347}
348
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000349void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000350 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000351 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000352}
353
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000354void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000355 Record.AddTypeRef(T->getUnderlyingType());
Richard Smith290d8012016-04-06 17:06:00 +0000356 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000357 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000358}
359
Alexis Hunte852b102011-05-24 22:41:36 +0000360void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000361 Record.AddTypeRef(T->getBaseType());
362 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000363 Record.push_back(T->getUTTKind());
364 Code = TYPE_UNARY_TRANSFORM;
365}
366
Richard Smith30482bc2011-02-20 03:19:35 +0000367void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000368 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000369 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000370 if (T->getDeducedType().isNull())
371 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000372 Code = TYPE_AUTO;
373}
374
Richard Smith600b5262017-01-26 20:40:47 +0000375void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
376 const DeducedTemplateSpecializationType *T) {
377 Record.AddTemplateName(T->getTemplateName());
378 Record.AddTypeRef(T->getDeducedType());
379 if (T->getDeducedType().isNull())
380 Record.push_back(T->isDependentType());
381 Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
382}
383
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000384void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000385 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000386 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000387 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000388 "Cannot serialize in the middle of a type definition");
389}
390
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000391void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000392 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000393 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000394}
395
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000396void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000397 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000398 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000399}
400
John McCall81904512011-01-06 01:58:22 +0000401void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000402 Record.AddTypeRef(T->getModifiedType());
403 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000404 Record.push_back(T->getAttrKind());
405 Code = TYPE_ATTRIBUTED;
406}
407
Mike Stump11289f42009-09-09 15:08:12 +0000408void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000409ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000410 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000411 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
412 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000413 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000414}
415
416void
Douglas Gregorada4b792011-01-14 02:55:32 +0000417ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
418 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000419 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
420 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000421 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
422}
423
424void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000425ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000426 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000427 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000428 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000429 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000430 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000431 Record.AddTemplateArgument(ArgI);
432 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
433 : T->isCanonicalUnqualified()
434 ? QualType()
435 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000436 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000437}
438
439void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000440ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000441 VisitArrayType(T);
Richard Smith290d8012016-04-06 17:06:00 +0000442 Record.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000444 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000445}
446
447void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000448ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000449 const DependentSizedExtVectorType *T) {
Alex Lorenz00aee432017-03-22 10:04:48 +0000450 Record.AddTypeRef(T->getElementType());
451 Record.AddStmt(T->getSizeExpr());
452 Record.AddSourceLocation(T->getAttributeLoc());
453 Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000454}
455
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000456void
457ASTTypeWriter::VisitDependentAddressSpaceType(
458 const DependentAddressSpaceType *T) {
459 Record.AddTypeRef(T->getPointeeType());
460 Record.AddStmt(T->getAddrSpaceExpr());
461 Record.AddSourceLocation(T->getAttributeLoc());
462 Code = TYPE_DEPENDENT_ADDRESS_SPACE;
463}
464
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000465void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000466ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000467 Record.push_back(T->getDepth());
468 Record.push_back(T->getIndex());
469 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000470 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000471 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000472}
473
474void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000475ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000476 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000477 Record.AddNestedNameSpecifier(T->getQualifier());
478 Record.AddIdentifierRef(T->getIdentifier());
479 Record.AddTypeRef(
480 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000481 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000482}
483
484void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000485ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000486 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000487 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000488 Record.AddNestedNameSpecifier(T->getQualifier());
489 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000490 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000491 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000492 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000493 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000494}
495
Douglas Gregord2fa7662010-12-20 02:24:11 +0000496void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000497 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000498 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000499 Record.push_back(*NumExpansions + 1);
500 else
501 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000502 Code = TYPE_PACK_EXPANSION;
503}
504
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000505void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000506 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000507 Code = TYPE_PAREN;
508}
509
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000510void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000511 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000512 Record.AddNestedNameSpecifier(T->getQualifier());
513 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000514 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000515}
516
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000517void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000518 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
519 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000520 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000521}
522
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000523void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000524 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000525 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000526}
527
Manman Rene6be26c2016-09-13 17:25:08 +0000528void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
529 Record.AddDeclRef(T->getDecl());
530 Record.push_back(T->getNumProtocols());
531 for (const auto *I : T->quals())
532 Record.AddDeclRef(I);
533 Code = TYPE_OBJC_TYPE_PARAM;
534}
535
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000536void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000537 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000538 Record.push_back(T->getTypeArgsAsWritten().size());
539 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000540 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000541 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000542 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000543 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000544 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000545 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000546}
547
Steve Narofffb4330f2009-06-17 22:40:22 +0000548void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000549ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000550 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000551 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000552}
553
Eli Friedman0dfb8892011-10-06 23:00:33 +0000554void
555ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000556 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000557 Code = TYPE_ATOMIC;
558}
559
Xiuli Pan9c14e282016-01-09 12:53:17 +0000560void
561ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000562 Record.AddTypeRef(T->getElementType());
Joey Goulye3c85de2016-12-01 11:30:49 +0000563 Record.push_back(T->isReadOnly());
564 Code = TYPE_PIPE;
Xiuli Pan9c14e282016-01-09 12:53:17 +0000565}
566
John McCall8f115c62009-10-16 21:56:05 +0000567namespace {
568
569class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000570 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000571
572public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000573 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000574
John McCall17001972009-10-18 01:05:36 +0000575#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000576#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000577 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000578#include "clang/AST/TypeLocNodes.def"
579
John McCall17001972009-10-18 01:05:36 +0000580 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
581 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000582};
583
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000584} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000585
John McCall17001972009-10-18 01:05:36 +0000586void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
587 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000588}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000589
John McCall17001972009-10-18 01:05:36 +0000590void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000591 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000592 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000593 Record.push_back(TL.getWrittenTypeSpec());
594 Record.push_back(TL.getWrittenSignSpec());
595 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000596 Record.push_back(TL.hasModeAttr());
597 }
John McCall8f115c62009-10-16 21:56:05 +0000598}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000599
John McCall17001972009-10-18 01:05:36 +0000600void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000601 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000602}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000603
John McCall17001972009-10-18 01:05:36 +0000604void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000605 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000606}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000607
Reid Kleckner8a365022013-06-24 17:51:48 +0000608void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
609 // nothing to do
610}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000611
Reid Kleckner0503a872013-12-05 01:23:43 +0000612void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
613 // nothing to do
614}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000615
John McCall17001972009-10-18 01:05:36 +0000616void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000617 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000618}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000619
John McCall17001972009-10-18 01:05:36 +0000620void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000621 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000622}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000623
John McCall17001972009-10-18 01:05:36 +0000624void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000625 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000626}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000627
John McCall17001972009-10-18 01:05:36 +0000628void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000629 Record.AddSourceLocation(TL.getStarLoc());
630 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000631}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000632
John McCall17001972009-10-18 01:05:36 +0000633void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000634 Record.AddSourceLocation(TL.getLBracketLoc());
635 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000636 Record.push_back(TL.getSizeExpr() ? 1 : 0);
637 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000638 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000639}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000640
John McCall17001972009-10-18 01:05:36 +0000641void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
642 VisitArrayTypeLoc(TL);
643}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000644
John McCall17001972009-10-18 01:05:36 +0000645void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
646 VisitArrayTypeLoc(TL);
647}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000648
John McCall17001972009-10-18 01:05:36 +0000649void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
650 VisitArrayTypeLoc(TL);
651}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000652
John McCall17001972009-10-18 01:05:36 +0000653void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
654 DependentSizedArrayTypeLoc TL) {
655 VisitArrayTypeLoc(TL);
656}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000657
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000658void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
659 DependentAddressSpaceTypeLoc TL) {
660 Record.AddSourceLocation(TL.getAttrNameLoc());
661 SourceRange range = TL.getAttrOperandParensRange();
662 Record.AddSourceLocation(range.getBegin());
663 Record.AddSourceLocation(range.getEnd());
664 Record.AddStmt(TL.getAttrExprOperand());
665}
666
John McCall17001972009-10-18 01:05:36 +0000667void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
668 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000669 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000670}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000671
John McCall17001972009-10-18 01:05:36 +0000672void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000673 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000674}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000675
John McCall17001972009-10-18 01:05:36 +0000676void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000677 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000678}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000679
John McCall17001972009-10-18 01:05:36 +0000680void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000681 Record.AddSourceLocation(TL.getLocalRangeBegin());
682 Record.AddSourceLocation(TL.getLParenLoc());
683 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000684 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000685 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000686 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000687 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000688}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000689
John McCall17001972009-10-18 01:05:36 +0000690void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
691 VisitFunctionTypeLoc(TL);
692}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000693
John McCall17001972009-10-18 01:05:36 +0000694void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
695 VisitFunctionTypeLoc(TL);
696}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000697
John McCallb96ec562009-12-04 22:46:56 +0000698void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000699 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000700}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000701
John McCall17001972009-10-18 01:05:36 +0000702void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000703 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000704}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000705
Manman Rene6be26c2016-09-13 17:25:08 +0000706void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
707 if (TL.getNumProtocols()) {
708 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
709 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
710 }
711 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
712 Record.AddSourceLocation(TL.getProtocolLoc(i));
713}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000714
John McCall17001972009-10-18 01:05:36 +0000715void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000716 Record.AddSourceLocation(TL.getTypeofLoc());
717 Record.AddSourceLocation(TL.getLParenLoc());
718 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000719}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000720
John McCall17001972009-10-18 01:05:36 +0000721void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000722 Record.AddSourceLocation(TL.getTypeofLoc());
723 Record.AddSourceLocation(TL.getLParenLoc());
724 Record.AddSourceLocation(TL.getRParenLoc());
725 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000726}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000727
John McCall17001972009-10-18 01:05:36 +0000728void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000729 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000730}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000731
Alexis Hunte852b102011-05-24 22:41:36 +0000732void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000733 Record.AddSourceLocation(TL.getKWLoc());
734 Record.AddSourceLocation(TL.getLParenLoc());
735 Record.AddSourceLocation(TL.getRParenLoc());
736 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000737}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000738
Richard Smith30482bc2011-02-20 03:19:35 +0000739void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000740 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000741}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000742
Richard Smith600b5262017-01-26 20:40:47 +0000743void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
744 DeducedTemplateSpecializationTypeLoc TL) {
745 Record.AddSourceLocation(TL.getTemplateNameLoc());
746}
747
John McCall17001972009-10-18 01:05:36 +0000748void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000749 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000750}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000751
John McCall17001972009-10-18 01:05:36 +0000752void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000753 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000754}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000755
John McCall81904512011-01-06 01:58:22 +0000756void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000757 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000758 if (TL.hasAttrOperand()) {
759 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000760 Record.AddSourceLocation(range.getBegin());
761 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000762 }
763 if (TL.hasAttrExprOperand()) {
764 Expr *operand = TL.getAttrExprOperand();
765 Record.push_back(operand ? 1 : 0);
Richard Smith290d8012016-04-06 17:06:00 +0000766 if (operand) Record.AddStmt(operand);
John McCall81904512011-01-06 01:58:22 +0000767 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000768 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000769 }
770}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000771
John McCall17001972009-10-18 01:05:36 +0000772void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000773 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000774}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000775
John McCallcebee162009-10-18 09:09:24 +0000776void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
777 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000778 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000779}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000780
Douglas Gregorada4b792011-01-14 02:55:32 +0000781void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
782 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000783 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000784}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000785
John McCall17001972009-10-18 01:05:36 +0000786void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
787 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000788 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
789 Record.AddSourceLocation(TL.getTemplateNameLoc());
790 Record.AddSourceLocation(TL.getLAngleLoc());
791 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000792 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000793 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
794 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000795}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000796
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000797void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000798 Record.AddSourceLocation(TL.getLParenLoc());
799 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000800}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000801
Abramo Bagnara6150c882010-05-11 21:36:43 +0000802void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000803 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
804 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000805}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000806
John McCalle78aac42010-03-10 03:28:59 +0000807void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000808 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000809}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000810
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000811void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000812 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
813 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
814 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000815}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000816
John McCallc392f372010-06-11 00:33:02 +0000817void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
818 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000819 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
820 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
821 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
822 Record.AddSourceLocation(TL.getTemplateNameLoc());
823 Record.AddSourceLocation(TL.getLAngleLoc());
824 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000825 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000826 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
827 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000828}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000829
Douglas Gregord2fa7662010-12-20 02:24:11 +0000830void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000831 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000832}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000833
John McCall17001972009-10-18 01:05:36 +0000834void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000835 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000836}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000837
John McCall8b07ec22010-05-15 11:32:37 +0000838void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
839 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000840 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
841 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000842 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000843 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
844 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
845 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000846 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000847 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000848}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000849
John McCallfc93cf92009-10-22 22:37:11 +0000850void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000851 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000852}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000853
Eli Friedman0dfb8892011-10-06 23:00:33 +0000854void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000855 Record.AddSourceLocation(TL.getKWLoc());
856 Record.AddSourceLocation(TL.getLParenLoc());
857 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000858}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000859
Xiuli Pan9c14e282016-01-09 12:53:17 +0000860void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000861 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000862}
John McCall8f115c62009-10-16 21:56:05 +0000863
Richard Smith01b2cb42014-07-26 06:37:51 +0000864void ASTWriter::WriteTypeAbbrevs() {
865 using namespace llvm;
866
David Blaikieb44f0bf2017-01-04 22:36:43 +0000867 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000868
869 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000870 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000871 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
872 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
873 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000874 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000875
876 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000877 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000878 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
879 // FunctionType
880 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
881 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
882 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
883 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
884 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
885 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000886 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Richard Smith01b2cb42014-07-26 06:37:51 +0000887 // FunctionProtoType
888 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
889 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
890 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
891 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
892 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
893 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
894 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
895 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000896 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000897}
898
Chris Lattner19cea4e2009-04-22 05:57:30 +0000899//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000900// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000901//===----------------------------------------------------------------------===//
902
Chris Lattner28fa4e62009-04-26 22:26:21 +0000903static void EmitBlockID(unsigned ID, const char *Name,
904 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000905 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000906 Record.clear();
907 Record.push_back(ID);
908 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
909
910 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000911 if (!Name || Name[0] == 0)
912 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000913 Record.clear();
914 while (*Name)
915 Record.push_back(*Name++);
916 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
917}
918
919static void EmitRecordID(unsigned ID, const char *Name,
920 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000921 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000922 Record.clear();
923 Record.push_back(ID);
924 while (*Name)
925 Record.push_back(*Name++);
926 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000927}
928
929static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000930 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000931#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000932 RECORD(STMT_STOP);
933 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000934 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000935 RECORD(STMT_NULL);
936 RECORD(STMT_COMPOUND);
937 RECORD(STMT_CASE);
938 RECORD(STMT_DEFAULT);
939 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000940 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000941 RECORD(STMT_IF);
942 RECORD(STMT_SWITCH);
943 RECORD(STMT_WHILE);
944 RECORD(STMT_DO);
945 RECORD(STMT_FOR);
946 RECORD(STMT_GOTO);
947 RECORD(STMT_INDIRECT_GOTO);
948 RECORD(STMT_CONTINUE);
949 RECORD(STMT_BREAK);
950 RECORD(STMT_RETURN);
951 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000952 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000953 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000954 RECORD(EXPR_PREDEFINED);
955 RECORD(EXPR_DECL_REF);
956 RECORD(EXPR_INTEGER_LITERAL);
957 RECORD(EXPR_FLOATING_LITERAL);
958 RECORD(EXPR_IMAGINARY_LITERAL);
959 RECORD(EXPR_STRING_LITERAL);
960 RECORD(EXPR_CHARACTER_LITERAL);
961 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000962 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000963 RECORD(EXPR_UNARY_OPERATOR);
964 RECORD(EXPR_SIZEOF_ALIGN_OF);
965 RECORD(EXPR_ARRAY_SUBSCRIPT);
966 RECORD(EXPR_CALL);
967 RECORD(EXPR_MEMBER);
968 RECORD(EXPR_BINARY_OPERATOR);
969 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
970 RECORD(EXPR_CONDITIONAL_OPERATOR);
971 RECORD(EXPR_IMPLICIT_CAST);
972 RECORD(EXPR_CSTYLE_CAST);
973 RECORD(EXPR_COMPOUND_LITERAL);
974 RECORD(EXPR_EXT_VECTOR_ELEMENT);
975 RECORD(EXPR_INIT_LIST);
976 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000977 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000978 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000979 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000980 RECORD(EXPR_VA_ARG);
981 RECORD(EXPR_ADDR_LABEL);
982 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000983 RECORD(EXPR_CHOOSE);
984 RECORD(EXPR_GNU_NULL);
985 RECORD(EXPR_SHUFFLE_VECTOR);
986 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000987 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000988 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000989 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000990 RECORD(EXPR_OBJC_ARRAY_LITERAL);
991 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000992 RECORD(EXPR_OBJC_ENCODE);
993 RECORD(EXPR_OBJC_SELECTOR_EXPR);
994 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
995 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
996 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
997 RECORD(EXPR_OBJC_KVC_REF_EXPR);
998 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000999 RECORD(STMT_OBJC_FOR_COLLECTION);
1000 RECORD(STMT_OBJC_CATCH);
1001 RECORD(STMT_OBJC_FINALLY);
1002 RECORD(STMT_OBJC_AT_TRY);
1003 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
1004 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001005 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +00001006 RECORD(STMT_CXX_CATCH);
1007 RECORD(STMT_CXX_TRY);
1008 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001009 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001010 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001011 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001012 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001013 RECORD(EXPR_CXX_STATIC_CAST);
1014 RECORD(EXPR_CXX_DYNAMIC_CAST);
1015 RECORD(EXPR_CXX_REINTERPRET_CAST);
1016 RECORD(EXPR_CXX_CONST_CAST);
1017 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +00001018 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +00001019 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001020 RECORD(EXPR_CXX_BOOL_LITERAL);
1021 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001022 RECORD(EXPR_CXX_TYPEID_EXPR);
1023 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001024 RECORD(EXPR_CXX_THIS);
1025 RECORD(EXPR_CXX_THROW);
1026 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +00001027 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001028 RECORD(EXPR_CXX_BIND_TEMPORARY);
1029 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
1030 RECORD(EXPR_CXX_NEW);
1031 RECORD(EXPR_CXX_DELETE);
1032 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
1033 RECORD(EXPR_EXPR_WITH_CLEANUPS);
1034 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
1035 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
1036 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
1037 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
1038 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +00001039 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001040 RECORD(EXPR_CXX_NOEXCEPT);
1041 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +00001042 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1043 RECORD(EXPR_TYPE_TRAIT);
1044 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001045 RECORD(EXPR_PACK_EXPANSION);
1046 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +00001047 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001048 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +00001049 RECORD(EXPR_FUNCTION_PARM_PACK);
1050 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +00001051 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +00001052 RECORD(EXPR_CXX_UUIDOF_EXPR);
1053 RECORD(EXPR_CXX_UUIDOF_TYPE);
1054 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +00001055#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +00001056}
Mike Stump11289f42009-09-09 15:08:12 +00001057
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001058void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +00001059 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +00001060 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +00001061
Sebastian Redl539c5062010-08-18 23:57:32 +00001062#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1063#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001065 // Control Block.
1066 BLOCK(CONTROL_BLOCK);
1067 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001068 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +00001069 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001070 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001071 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +00001072 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001073 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001074 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001075 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +00001076
1077 BLOCK(OPTIONS_BLOCK);
1078 RECORD(LANGUAGE_OPTIONS);
1079 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +00001080 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +00001081 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001082 RECORD(PREPROCESSOR_OPTIONS);
1083
Douglas Gregor108cb222012-10-19 00:45:00 +00001084 BLOCK(INPUT_FILES_BLOCK);
1085 RECORD(INPUT_FILE);
1086
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001087 // AST Top-Level Block.
1088 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001089 RECORD(TYPE_OFFSET);
1090 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001091 RECORD(IDENTIFIER_OFFSET);
1092 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +00001093 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +00001094 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001095 RECORD(SPECIAL_TYPES);
1096 RECORD(STATISTICS);
1097 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001098 RECORD(SELECTOR_OFFSETS);
1099 RECORD(METHOD_POOL);
1100 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +00001101 RECORD(SOURCE_LOCATION_OFFSETS);
1102 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001103 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +00001104 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00001105 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +00001106 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00001107 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001108 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001109 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001110 RECORD(SEMA_DECL_REFS);
1111 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1112 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001113 RECORD(UPDATE_VISIBLE);
1114 RECORD(DECL_UPDATE_OFFSETS);
1115 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00001116 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +00001117 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00001118 RECORD(FP_PRAGMA_OPTIONS);
1119 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +00001120 RECORD(OPENCL_EXTENSION_TYPES);
1121 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +00001122 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001123 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +00001124 RECORD(MODULE_OFFSET_MAP);
1125 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +00001126 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +00001127 RECORD(FILE_SORTED_DECLS);
1128 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +00001129 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00001130 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +00001131 RECORD(INTERESTING_IDENTIFIERS);
1132 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +00001133 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +00001134 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +00001135 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +00001136 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +00001137 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +00001138 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +00001139 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00001140 RECORD(PP_CONDITIONAL_STACK);
Douglas Gregor358cd442012-01-15 16:58:34 +00001141
Chris Lattner28fa4e62009-04-26 22:26:21 +00001142 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +00001143 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001144 RECORD(SM_SLOC_FILE_ENTRY);
1145 RECORD(SM_SLOC_BUFFER_ENTRY);
1146 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +00001147 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001148 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +00001149
Chris Lattner28fa4e62009-04-26 22:26:21 +00001150 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +00001151 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +00001152 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001153 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +00001154 RECORD(PP_MACRO_OBJECT_LIKE);
1155 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001156 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +00001157
Richard Smithfa715652015-08-31 22:43:10 +00001158 // Submodule Block.
1159 BLOCK(SUBMODULE_BLOCK);
1160 RECORD(SUBMODULE_METADATA);
1161 RECORD(SUBMODULE_DEFINITION);
1162 RECORD(SUBMODULE_UMBRELLA_HEADER);
1163 RECORD(SUBMODULE_HEADER);
1164 RECORD(SUBMODULE_TOPHEADER);
1165 RECORD(SUBMODULE_UMBRELLA_DIR);
1166 RECORD(SUBMODULE_IMPORTS);
1167 RECORD(SUBMODULE_EXPORTS);
1168 RECORD(SUBMODULE_REQUIRES);
1169 RECORD(SUBMODULE_EXCLUDED_HEADER);
1170 RECORD(SUBMODULE_LINK_LIBRARY);
1171 RECORD(SUBMODULE_CONFIG_MACRO);
1172 RECORD(SUBMODULE_CONFLICT);
1173 RECORD(SUBMODULE_PRIVATE_HEADER);
1174 RECORD(SUBMODULE_TEXTUAL_HEADER);
1175 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +00001176 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00001177 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +00001178
1179 // Comments Block.
1180 BLOCK(COMMENTS_BLOCK);
1181 RECORD(COMMENTS_RAW_COMMENT);
1182
Douglas Gregor12bfa382009-10-17 00:13:19 +00001183 // Decls and Types block.
1184 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001185 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001186 RECORD(TYPE_COMPLEX);
1187 RECORD(TYPE_POINTER);
1188 RECORD(TYPE_BLOCK_POINTER);
1189 RECORD(TYPE_LVALUE_REFERENCE);
1190 RECORD(TYPE_RVALUE_REFERENCE);
1191 RECORD(TYPE_MEMBER_POINTER);
1192 RECORD(TYPE_CONSTANT_ARRAY);
1193 RECORD(TYPE_INCOMPLETE_ARRAY);
1194 RECORD(TYPE_VARIABLE_ARRAY);
1195 RECORD(TYPE_VECTOR);
1196 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001197 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001198 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001199 RECORD(TYPE_TYPEDEF);
1200 RECORD(TYPE_TYPEOF_EXPR);
1201 RECORD(TYPE_TYPEOF);
1202 RECORD(TYPE_RECORD);
1203 RECORD(TYPE_ENUM);
1204 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001205 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001206 RECORD(TYPE_DECLTYPE);
1207 RECORD(TYPE_ELABORATED);
1208 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1209 RECORD(TYPE_UNRESOLVED_USING);
1210 RECORD(TYPE_INJECTED_CLASS_NAME);
1211 RECORD(TYPE_OBJC_OBJECT);
1212 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1213 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1214 RECORD(TYPE_DEPENDENT_NAME);
1215 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1216 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1217 RECORD(TYPE_PAREN);
1218 RECORD(TYPE_PACK_EXPANSION);
1219 RECORD(TYPE_ATTRIBUTED);
1220 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001221 RECORD(TYPE_AUTO);
1222 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001223 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001224 RECORD(TYPE_DECAYED);
1225 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +00001226 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001227 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001228 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001229 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001230 RECORD(DECL_ENUM);
1231 RECORD(DECL_RECORD);
1232 RECORD(DECL_ENUM_CONSTANT);
1233 RECORD(DECL_FUNCTION);
1234 RECORD(DECL_OBJC_METHOD);
1235 RECORD(DECL_OBJC_INTERFACE);
1236 RECORD(DECL_OBJC_PROTOCOL);
1237 RECORD(DECL_OBJC_IVAR);
1238 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001239 RECORD(DECL_OBJC_CATEGORY);
1240 RECORD(DECL_OBJC_CATEGORY_IMPL);
1241 RECORD(DECL_OBJC_IMPLEMENTATION);
1242 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1243 RECORD(DECL_OBJC_PROPERTY);
1244 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001245 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001246 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001247 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001248 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001249 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001250 RECORD(DECL_FILE_SCOPE_ASM);
1251 RECORD(DECL_BLOCK);
1252 RECORD(DECL_CONTEXT_LEXICAL);
1253 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001254 RECORD(DECL_NAMESPACE);
1255 RECORD(DECL_NAMESPACE_ALIAS);
1256 RECORD(DECL_USING);
1257 RECORD(DECL_USING_SHADOW);
1258 RECORD(DECL_USING_DIRECTIVE);
1259 RECORD(DECL_UNRESOLVED_USING_VALUE);
1260 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1261 RECORD(DECL_LINKAGE_SPEC);
1262 RECORD(DECL_CXX_RECORD);
1263 RECORD(DECL_CXX_METHOD);
1264 RECORD(DECL_CXX_CONSTRUCTOR);
Richard Smith5179eb72016-06-28 19:03:57 +00001265 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001266 RECORD(DECL_CXX_DESTRUCTOR);
1267 RECORD(DECL_CXX_CONVERSION);
1268 RECORD(DECL_ACCESS_SPEC);
1269 RECORD(DECL_FRIEND);
1270 RECORD(DECL_FRIEND_TEMPLATE);
1271 RECORD(DECL_CLASS_TEMPLATE);
1272 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1273 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001274 RECORD(DECL_VAR_TEMPLATE);
1275 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1276 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001277 RECORD(DECL_FUNCTION_TEMPLATE);
1278 RECORD(DECL_TEMPLATE_TYPE_PARM);
1279 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1280 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Richard Smithefc884a2016-04-13 07:41:35 +00001281 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001282 RECORD(DECL_STATIC_ASSERT);
1283 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +00001284 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001285 RECORD(DECL_INDIRECTFIELD);
1286 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +00001287 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1288 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1289 RECORD(DECL_IMPORT);
1290 RECORD(DECL_OMP_THREADPRIVATE);
1291 RECORD(DECL_EMPTY);
1292 RECORD(DECL_OBJC_TYPE_PARAM);
1293 RECORD(DECL_OMP_CAPTUREDEXPR);
1294 RECORD(DECL_PRAGMA_COMMENT);
1295 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1296 RECORD(DECL_OMP_DECLARE_REDUCTION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001297
Douglas Gregor03412ba2011-06-03 02:27:19 +00001298 // Statements and Exprs can occur in the Decls and Types block.
1299 AddStmtsExprs(Stream, Record);
1300
Douglas Gregor92a96f52011-02-08 21:58:10 +00001301 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001302 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001303 RECORD(PPD_MACRO_DEFINITION);
1304 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001305
1306 // Decls and Types block.
1307 BLOCK(EXTENSION_BLOCK);
1308 RECORD(EXTENSION_METADATA);
1309
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001310 BLOCK(UNHASHED_CONTROL_BLOCK);
1311 RECORD(SIGNATURE);
1312 RECORD(DIAGNOSTIC_OPTIONS);
1313 RECORD(DIAG_PRAGMA_MAPPINGS);
1314
Chris Lattner28fa4e62009-04-26 22:26:21 +00001315#undef RECORD
1316#undef BLOCK
1317 Stream.ExitBlock();
1318}
1319
Richard Smith54cc3c22014-12-11 20:50:24 +00001320/// \brief Prepares a path for being written to an AST file by converting it
1321/// to an absolute path and removing nested './'s.
1322///
1323/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001324static bool cleanPathForOutput(FileManager &FileMgr,
1325 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001326 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001327 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001328}
1329
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001330/// \brief Adjusts the given filename to only write out the portion of the
1331/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001332///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001333/// \param Filename the file name to adjust.
1334///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001335/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1336/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001337///
1338/// \returns either the original filename (if it needs no adjustment) or the
1339/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001340static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001341adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001342 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001343
Richard Smith7ed1bc92014-12-05 22:42:13 +00001344 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001345 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001347 // Verify that the filename and the system root have the same prefix.
1348 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001349 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1350 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001351 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001352
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001353 // We hit the end of the filename before we hit the end of the system root.
1354 if (!Filename[Pos])
1355 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Richard Smith7ed1bc92014-12-05 22:42:13 +00001357 // If there's not a path separator at the end of the base directory nor
1358 // immediately after it, then this isn't within the base directory.
1359 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1360 if (!llvm::sys::path::is_separator(BaseDir.back()))
1361 return Filename;
1362 } else {
1363 // If the file name has a '/' at the current position, skip over the '/'.
1364 // We distinguish relative paths from absolute paths by the
1365 // absence of '/' at the beginning of relative paths.
1366 //
1367 // FIXME: This is wrong. We distinguish them by asking if the path is
1368 // absolute, which isn't the same thing. And there might be multiple '/'s
1369 // in a row. Use a better mechanism to indicate whether we have emitted an
1370 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001371 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001374 return Filename + Pos;
1375}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001376
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001377ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1378 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1379 llvm::SHA1 Hasher;
1380 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1381 auto Hash = Hasher.result();
1382
1383 // Convert to an array [5*i32].
1384 ASTFileSignature Signature;
1385 auto LShift = [&](unsigned char Val, unsigned Shift) {
1386 return (uint32_t)Val << Shift;
1387 };
1388 for (int I = 0; I != 5; ++I)
1389 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1390 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1391
1392 return Signature;
1393}
1394
1395ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1396 ASTContext &Context) {
1397 // Flush first to prepare the PCM hash (signature).
1398 Stream.FlushToWord();
1399 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1400
1401 // Enter the block and prepare to write records.
1402 RecordData Record;
1403 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1404
1405 // For implicit modules, write the hash of the PCM as its signature.
1406 ASTFileSignature Signature;
1407 if (WritingModule &&
1408 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1409 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1410 Record.append(Signature.begin(), Signature.end());
1411 Stream.EmitRecord(SIGNATURE, Record);
1412 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001413 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001414
1415 // Diagnostic options.
1416 const auto &Diags = Context.getDiagnostics();
1417 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1418#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1419#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1420 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1421#include "clang/Basic/DiagnosticOptions.def"
1422 Record.push_back(DiagOpts.Warnings.size());
1423 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1424 AddString(DiagOpts.Warnings[I], Record);
1425 Record.push_back(DiagOpts.Remarks.size());
1426 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1427 AddString(DiagOpts.Remarks[I], Record);
1428 // Note: we don't serialize the log or serialization file names, because they
1429 // are generally transient files and will almost always be overridden.
1430 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1431
1432 // Write out the diagnostic/pragma mappings.
1433 WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1434
1435 // Leave the options block.
1436 Stream.ExitBlock();
1437 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001438}
1439
Douglas Gregor112b9072012-10-18 05:31:06 +00001440/// \brief Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001441void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1442 StringRef isysroot,
1443 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001444 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001445
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001446 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001447 RecordData Record;
1448
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001449 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001450 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001451 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1452 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1453 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1454 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1455 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1456 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001457 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001458 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1459 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001460 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001461 assert((!WritingModule || isysroot.empty()) &&
1462 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001463 {
1464 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1465 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1466 !isysroot.empty(), IncludeTimestamps,
1467 ASTHasCompilerErrors};
1468 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1469 getClangFullRepositoryVersion());
1470 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001471
Richard Smith8b706102017-05-31 20:56:55 +00001472 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001473 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001474 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001475 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1476 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001477 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001478 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001479 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1480 }
1481
Richard Smith7ed1bc92014-12-05 22:42:13 +00001482 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001483 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001484 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001485
1486 // If the home of the module is the current working directory, then we
1487 // want to pick up the cwd of the build process loading the module, not
1488 // our cwd, when we load this module.
1489 if (!PP.getHeaderSearchInfo()
1490 .getHeaderSearchOpts()
1491 .ModuleMapFileHomeIsCwd ||
1492 WritingModule->Directory->getName() != StringRef(".")) {
1493 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001494 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001495 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1496 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001497 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001498
Mehdi Amini57a41912015-09-10 01:46:39 +00001499 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001500 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1501 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001502
1503 // Write out all other paths relative to the base directory if possible.
1504 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1505 } else if (!isysroot.empty()) {
1506 // Write out paths relative to the sysroot if possible.
1507 BaseDirectory = isysroot;
1508 }
1509
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001510 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001511 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001512 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001513
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001514 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001515 AddPath(WritingModule->PresumedModuleMapFile.empty()
1516 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1517 : StringRef(WritingModule->PresumedModuleMapFile),
1518 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001519
1520 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001521 if (auto *AdditionalModMaps =
1522 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001523 Record.push_back(AdditionalModMaps->size());
1524 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001526 } else {
1527 Record.push_back(0);
1528 }
1529
1530 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001531 }
1532
Douglas Gregor112b9072012-10-18 05:31:06 +00001533 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001534 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001535 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001536 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001537
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001538 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001539 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001540 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001541 continue;
1542
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001543 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1544 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001545
1546 // If we have calculated signature, there is no need to store
1547 // the size or timestamp.
1548 Record.push_back(M.Signature ? 0 : M.File->getSize());
1549 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1550
1551 for (auto I : M.Signature)
1552 Record.push_back(I);
1553
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001554 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001555 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001556 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001557 Stream.EmitRecord(IMPORTS, Record);
1558 }
Mike Stump11289f42009-09-09 15:08:12 +00001559
Richard Smith0516b182015-09-08 19:40:14 +00001560 // Write the options block.
1561 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1562
Douglas Gregor112b9072012-10-18 05:31:06 +00001563 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001564 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001565 const LangOptions &LangOpts = Context.getLangOpts();
1566#define LANGOPT(Name, Bits, Default, Description) \
1567 Record.push_back(LangOpts.Name);
1568#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1569 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001570#include "clang/Basic/LangOptions.def"
1571#define SANITIZER(NAME, ID) \
1572 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001573#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001574
Ben Langmuircd98cb72015-06-23 18:20:18 +00001575 Record.push_back(LangOpts.ModuleFeatures.size());
1576 for (StringRef Feature : LangOpts.ModuleFeatures)
1577 AddString(Feature, Record);
1578
Douglas Gregor112b9072012-10-18 05:31:06 +00001579 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1580 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001581
1582 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001583
1584 // Comment options.
1585 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001586 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1587 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001588 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001589 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001590
Samuel Antaoee8fb302016-01-06 13:42:12 +00001591 // OpenMP offloading options.
1592 Record.push_back(LangOpts.OMPTargetTriples.size());
1593 for (auto &T : LangOpts.OMPTargetTriples)
1594 AddString(T.getTriple(), Record);
1595
1596 AddString(LangOpts.OMPHostIRFile, Record);
1597
Douglas Gregor112b9072012-10-18 05:31:06 +00001598 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1599
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001600 // Target options.
1601 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001602 const TargetInfo &Target = Context.getTargetInfo();
1603 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001604 AddString(TargetOpts.Triple, Record);
1605 AddString(TargetOpts.CPU, Record);
1606 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001607 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1608 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1609 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1610 }
1611 Record.push_back(TargetOpts.Features.size());
1612 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1613 AddString(TargetOpts.Features[I], Record);
1614 }
1615 Stream.EmitRecord(TARGET_OPTIONS, Record);
1616
Douglas Gregorc6317db2012-10-24 15:49:58 +00001617 // File system options.
1618 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001619 const FileSystemOptions &FSOpts =
1620 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001621 AddString(FSOpts.WorkingDir, Record);
1622 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1623
Douglas Gregor2d302362012-10-24 16:50:34 +00001624 // Header search options.
1625 Record.clear();
1626 const HeaderSearchOptions &HSOpts
1627 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1628 AddString(HSOpts.Sysroot, Record);
1629
1630 // Include entries.
1631 Record.push_back(HSOpts.UserEntries.size());
1632 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1633 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1634 AddString(Entry.Path, Record);
1635 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001636 Record.push_back(Entry.IsFramework);
1637 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001638 }
1639
1640 // System header prefixes.
1641 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1642 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1643 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1644 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1645 }
1646
1647 AddString(HSOpts.ResourceDir, Record);
1648 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001649 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001650 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001651 Record.push_back(HSOpts.ImplicitModuleMaps);
1652 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001653 Record.push_back(HSOpts.UseBuiltinIncludes);
1654 Record.push_back(HSOpts.UseStandardSystemIncludes);
1655 Record.push_back(HSOpts.UseStandardCXXIncludes);
1656 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001657 // Write out the specific module cache path that contains the module files.
1658 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001659 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1660
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001661 // Preprocessor options.
1662 Record.clear();
1663 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1664
1665 // Macro definitions.
1666 Record.push_back(PPOpts.Macros.size());
1667 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1668 AddString(PPOpts.Macros[I].first, Record);
1669 Record.push_back(PPOpts.Macros[I].second);
1670 }
1671
1672 // Includes
1673 Record.push_back(PPOpts.Includes.size());
1674 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1675 AddString(PPOpts.Includes[I], Record);
1676
1677 // Macro includes
1678 Record.push_back(PPOpts.MacroIncludes.size());
1679 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1680 AddString(PPOpts.MacroIncludes[I], Record);
1681
Douglas Gregorb6368752012-10-24 23:41:50 +00001682 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001683 // Detailed record is important since it is used for the module cache hash.
1684 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001685 AddString(PPOpts.ImplicitPCHInclude, Record);
1686 AddString(PPOpts.ImplicitPTHInclude, Record);
1687 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1688 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1689
Richard Smith0516b182015-09-08 19:40:14 +00001690 // Leave the options block.
1691 Stream.ExitBlock();
1692
Douglas Gregora3b20262011-05-06 21:43:30 +00001693 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001694 SourceManager &SM = Context.getSourceManager();
1695 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001696 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001697 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1698 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001699 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001700 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001701
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001702 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001703 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001704 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001705 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001706 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001707
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001708 Record.clear();
1709 Record.push_back(SM.getMainFileID().getOpaqueValue());
1710 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1711
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001712 // Original PCH directory
1713 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001714 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001715 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001717 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001718
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001719 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001720
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001721 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001722 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1723
Mehdi Amini57a41912015-09-10 01:46:39 +00001724 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001725 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1726 }
1727
Douglas Gregor49491f72013-03-15 22:15:07 +00001728 WriteInputFiles(Context.SourceMgr,
1729 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001730 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001731 Stream.ExitBlock();
1732}
1733
Douglas Gregor49491f72013-03-15 22:15:07 +00001734namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001735
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001736/// \brief An input file.
1737struct InputFileEntry {
1738 const FileEntry *File;
1739 bool IsSystemFile;
1740 bool IsTransient;
1741 bool BufferOverridden;
1742 bool IsTopLevelModuleMap;
1743};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001744
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001745} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001746
1747void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1748 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001749 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001750 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001751
Douglas Gregor72be3902012-10-19 00:38:02 +00001752 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001753
Douglas Gregor72be3902012-10-19 00:38:02 +00001754 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001755 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001756 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001757 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001758 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1759 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001760 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001761 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001762 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001763 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001764 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001765
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001766 // Get all ContentCache objects for files, sorted by whether the file is a
1767 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001768 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001769 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1770 // Get this source location entry.
1771 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001772 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001773
1774 // We only care about file entries that were not overridden.
1775 if (!SLoc->isFile())
1776 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001777 const SrcMgr::FileInfo &File = SLoc->getFile();
1778 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001779 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001780 continue;
1781
Douglas Gregor49491f72013-03-15 22:15:07 +00001782 InputFileEntry Entry;
1783 Entry.File = Cache->OrigEntry;
1784 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001785 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001786 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001787 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1788 File.getIncludeLoc().isInvalid();
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001789 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001790 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001791 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001792 SortedFiles.push_front(Entry);
1793 }
1794
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001795 unsigned UserFilesNum = 0;
1796 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001797 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001798 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001799 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001800 if (InputFileID != 0)
1801 continue; // already recorded this file.
1802
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001803 // Record this entry's offset.
1804 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001805
1806 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001807
Douglas Gregor49491f72013-03-15 22:15:07 +00001808 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001809 ++UserFilesNum;
1810
Douglas Gregor72be3902012-10-19 00:38:02 +00001811 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001812 // And whether this file was overridden.
1813 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001814 INPUT_FILE,
1815 InputFileOffsets.size(),
1816 (uint64_t)Entry.File->getSize(),
1817 (uint64_t)getTimestampForOutput(Entry.File),
1818 Entry.BufferOverridden,
Richard Smithf3f84612017-06-29 02:19:42 +00001819 Entry.IsTransient,
1820 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001821
Richard Smith7ed1bc92014-12-05 22:42:13 +00001822 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1823 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001824
Douglas Gregor112b9072012-10-18 05:31:06 +00001825 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001826
1827 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001828 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001829 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1830 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001831 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1832 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001833 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001834 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001835
1836 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001837 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1838 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001839 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001840}
1841
Douglas Gregora7f71a92009-04-10 03:52:48 +00001842//===----------------------------------------------------------------------===//
1843// Source Manager Serialization
1844//===----------------------------------------------------------------------===//
1845
1846/// \brief Create an abbreviation for the SLocEntry that refers to a
1847/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001848static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001849 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001850
David Blaikieb44f0bf2017-01-04 22:36:43 +00001851 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001852 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001856 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001857 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001858 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1861 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001862 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001863}
1864
1865/// \brief Create an abbreviation for the SLocEntry that refers to a
1866/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001867static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001868 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001869
David Blaikieb44f0bf2017-01-04 22:36:43 +00001870 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001871 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001877 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001878}
1879
1880/// \brief Create an abbreviation for the SLocEntry that refers to a
1881/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001882static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1883 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001884 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001885
David Blaikieb44f0bf2017-01-04 22:36:43 +00001886 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001887 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1888 : SM_SLOC_BUFFER_BLOB));
1889 if (Compressed)
1890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001891 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001892 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001893}
1894
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001895/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1896/// expansion.
1897static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001898 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001899
David Blaikieb44f0bf2017-01-04 22:36:43 +00001900 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001901 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1905 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001906 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001907 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001908}
1909
Douglas Gregor09b69892011-02-10 17:09:37 +00001910namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001911
Douglas Gregor09b69892011-02-10 17:09:37 +00001912 // Trait used for the on-disk hash table of header search information.
1913 class HeaderFileInfoTrait {
1914 ASTWriter &Writer;
Douglas Gregor09b69892011-02-10 17:09:37 +00001915
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001916 // Keep track of the framework names we've used during serialization.
1917 SmallVector<char, 128> FrameworkStringData;
1918 llvm::StringMap<unsigned> FrameworkNameOffset;
1919
Douglas Gregor09b69892011-02-10 17:09:37 +00001920 public:
Richard Smith040e1262017-06-02 01:55:39 +00001921 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1922
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001923 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001924 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001925 off_t Size;
1926 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001927 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001928 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001929
1930 using UnresolvedModule =
1931 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Douglas Gregor09b69892011-02-10 17:09:37 +00001932
Richard Smith040e1262017-06-02 01:55:39 +00001933 struct data_type {
1934 const HeaderFileInfo &HFI;
1935 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1936 UnresolvedModule Unresolved;
1937 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001938 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001939
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001940 using hash_value_type = unsigned;
1941 using offset_type = unsigned;
Douglas Gregor09b69892011-02-10 17:09:37 +00001942
Richard Smithe75ee0f2015-08-17 07:13:32 +00001943 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001944 // The hash is based only on size/time of the file, so that the reader can
1945 // match even when symlinking or excess path elements ("foo/../", "../")
1946 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001947 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001948 }
1949
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001950 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001951 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001952 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001953
Richard Smith386bb072015-08-18 23:42:23 +00001954 endian::Writer<little> LE(Out);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001955 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001956 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001957 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001958 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001959 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1960 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001961 if (Data.Unresolved.getPointer())
1962 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001963 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001964 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001965 }
Richard Smith040e1262017-06-02 01:55:39 +00001966
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001967 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001968 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001969
Justin Bognere1c147c2014-03-28 22:03:19 +00001970 endian::Writer<little> LE(Out);
Richard Smith040e1262017-06-02 01:55:39 +00001971 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001972 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001973 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001974 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001975 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001976 }
Richard Smith040e1262017-06-02 01:55:39 +00001977
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001978 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001979 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001980 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001981
Justin Bognere1c147c2014-03-28 22:03:19 +00001982 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001983 uint64_t Start = Out.tell(); (void)Start;
1984
Richard Smithf3f84612017-06-29 02:19:42 +00001985 unsigned char Flags = (Data.HFI.isImport << 5)
1986 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001987 | (Data.HFI.DirInfo << 1)
1988 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001989 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001990 LE.write<uint16_t>(Data.HFI.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001991
Richard Smith040e1262017-06-02 01:55:39 +00001992 if (!Data.HFI.ControllingMacro)
1993 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001994 else
Richard Smith040e1262017-06-02 01:55:39 +00001995 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1996
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001997 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001998 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001999 // If this header refers into a framework, save the framework name.
2000 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00002001 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002002 if (Pos == FrameworkNameOffset.end()) {
2003 Offset = FrameworkStringData.size() + 1;
Richard Smith040e1262017-06-02 01:55:39 +00002004 FrameworkStringData.append(Data.HFI.Framework.begin(),
2005 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002006 FrameworkStringData.push_back(0);
2007
Richard Smith040e1262017-06-02 01:55:39 +00002008 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002009 } else
2010 Offset = Pos->second;
2011 }
Justin Bognere1c147c2014-03-28 22:03:19 +00002012 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002013
Richard Smith040e1262017-06-02 01:55:39 +00002014 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2015 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2016 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00002017 assert((Value >> 2) == ModID && "overflow in header module info");
2018 LE.write<uint32_t>(Value);
2019 }
Richard Smith040e1262017-06-02 01:55:39 +00002020 };
2021
2022 // FIXME: If the header is excluded, we should write out some
2023 // record of that fact.
2024 for (auto ModInfo : Data.KnownHeaders)
2025 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2026 if (Data.Unresolved.getPointer())
2027 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002028
Douglas Gregor09b69892011-02-10 17:09:37 +00002029 assert(Out.tell() - Start == DataLen && "Wrong data length");
2030 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002031
2032 const char *strings_begin() const { return FrameworkStringData.begin(); }
2033 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00002034 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002035
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002036} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00002037
2038/// \brief Write the header search block for the list of files that
2039///
2040/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00002041void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00002042 HeaderFileInfoTrait GeneratorTrait(*this);
2043 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2044 SmallVector<const char *, 4> SavedStrings;
2045 unsigned NumHeaderSearchEntries = 0;
2046
2047 // Find all unresolved headers for the current module. We generally will
2048 // have resolved them before we get here, but not necessarily: we might be
2049 // compiling a preprocessed module, where there is no requirement for the
2050 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00002051 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00002052 if (WritingModule) {
2053 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2054 while (!Worklist.empty()) {
2055 Module *M = Worklist.pop_back_val();
2056 if (!M->isAvailable())
2057 continue;
2058
2059 // Map to disk files where possible, to pick up any missing stat
2060 // information. This also means we don't need to check the unresolved
2061 // headers list when emitting resolved headers in the first loop below.
2062 // FIXME: It'd be preferable to avoid doing this if we were given
2063 // sufficient stat information in the module map.
2064 HS.getModuleMap().resolveHeaderDirectives(M);
2065
2066 // If the file didn't exist, we can still create a module if we were given
2067 // enough information in the module map.
2068 for (auto U : M->MissingHeaders) {
2069 // Check that we were given enough information to build a module
2070 // without this file existing on disk.
2071 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2072 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2073 << WritingModule->getFullModuleName() << U.Size.hasValue()
2074 << U.FileName;
2075 continue;
2076 }
2077
2078 // Form the effective relative pathname for the file.
2079 SmallString<128> Filename(M->Directory->getName());
2080 llvm::sys::path::append(Filename, U.FileName);
2081 PreparePathForOutput(Filename);
2082
2083 StringRef FilenameDup = strdup(Filename.c_str());
2084 SavedStrings.push_back(FilenameDup.data());
2085
2086 HeaderFileInfoTrait::key_type Key = {
2087 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2088 };
2089 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00002090 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00002091 };
2092 // FIXME: Deal with cases where there are multiple unresolved header
2093 // directives in different submodules for the same header.
2094 Generator.insert(Key, Data, GeneratorTrait);
2095 ++NumHeaderSearchEntries;
2096 }
2097
2098 Worklist.append(M->submodule_begin(), M->submodule_end());
2099 }
2100 }
2101
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002102 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00002103 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2104
2105 if (FilesByUID.size() > HS.header_file_size())
2106 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00002107
Douglas Gregor09b69892011-02-10 17:09:37 +00002108 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2109 const FileEntry *File = FilesByUID[UID];
2110 if (!File)
2111 continue;
2112
Richard Smith386bb072015-08-18 23:42:23 +00002113 // Get the file info. This will load info from the external source if
2114 // necessary. Skip emitting this file if we have no information on it
2115 // as a header file (in which case HFI will be null) or if it hasn't
2116 // changed since it was loaded. Also skip it if it's for a modular header
2117 // from a different module; in that case, we rely on the module(s)
2118 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00002119 const HeaderFileInfo *HFI =
2120 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2121 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00002122 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00002123
Richard Smith7ed1bc92014-12-05 22:42:13 +00002124 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00002125 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00002126 SmallString<128> FilenameTmp(Filename);
2127 if (PreparePathForOutput(FilenameTmp)) {
2128 // If we performed any translation on the file name at all, we need to
2129 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00002130 Filename = StringRef(strdup(FilenameTmp.c_str()));
2131 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00002132 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002133
Richard Smith040e1262017-06-02 01:55:39 +00002134 HeaderFileInfoTrait::key_type Key = {
2135 Filename, File->getSize(), getTimestampForOutput(File)
2136 };
2137 HeaderFileInfoTrait::data_type Data = {
2138 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2139 };
2140 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00002141 ++NumHeaderSearchEntries;
2142 }
Richard Smith040e1262017-06-02 01:55:39 +00002143
Douglas Gregor09b69892011-02-10 17:09:37 +00002144 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002145 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00002146 uint32_t BucketOffset;
2147 {
Justin Bognere1c147c2014-03-28 22:03:19 +00002148 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002149
Douglas Gregor09b69892011-02-10 17:09:37 +00002150 llvm::raw_svector_ostream Out(TableData);
2151 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00002152 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00002153 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2154 }
2155
2156 // Create a blob abbreviation
2157 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002158
David Blaikieb44f0bf2017-01-04 22:36:43 +00002159 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00002160 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2161 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2162 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00002164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002165 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor09b69892011-02-10 17:09:37 +00002166
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002167 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00002168 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2169 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002170 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00002171 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00002172
2173 // Free all of the strings we had to duplicate.
2174 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00002175 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00002176}
2177
George Rimarc39f5492017-01-17 15:45:31 +00002178static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2179 unsigned SLocBufferBlobCompressedAbbrv,
2180 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002181 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00002182
2183 // Compress the buffer if possible. We expect that almost all PCM
2184 // consumers will not want its contents.
2185 SmallString<0> CompressedBuffer;
2186 if (llvm::zlib::isAvailable()) {
2187 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2188 if (!E) {
2189 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2190 Blob.size() - 1};
2191 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2192 CompressedBuffer);
2193 return;
2194 }
2195 llvm::consumeError(std::move(E));
2196 }
2197
2198 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2199 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2200}
2201
Douglas Gregora7f71a92009-04-10 03:52:48 +00002202/// \brief Writes the block containing the serialized form of the
2203/// source manager.
2204///
2205/// TODO: We should probably use an on-disk hash table (stored in a
2206/// blob), indexed based on the file name, so that we only create
2207/// entries for files that we actually need. In the common case (no
2208/// errors), we probably won't have to create file entries for any of
2209/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002210void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00002211 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00002212 RecordData Record;
2213
Chris Lattner0910e3b2009-04-10 17:16:57 +00002214 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00002215 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00002216
2217 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00002218 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2219 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00002220 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2221 unsigned SLocBufferBlobCompressedAbbrv =
2222 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002223 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00002224
Douglas Gregor258ae542009-04-27 06:38:32 +00002225 // Write out the source location entry table. We skip the first
2226 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00002227 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00002228 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00002229 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2230 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00002231 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00002232 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00002233 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00002234 FileID FID = FileID::get(I);
2235 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00002236
Douglas Gregor258ae542009-04-27 06:38:32 +00002237 // Record the offset of this source-location entry.
2238 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2239
2240 // Figure out which record code to use.
2241 unsigned Code;
2242 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00002243 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2244 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00002245 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00002246 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00002247 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00002248 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002249 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00002250 Record.clear();
2251 Record.push_back(Code);
2252
Douglas Gregor925296b2011-07-19 16:10:42 +00002253 // Starting offset of this entry within this module, so skip the dummy.
2254 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00002255 if (SLoc->isFile()) {
2256 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00002257 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002258 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2259 Record.push_back(File.hasLineDirectives());
2260
2261 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00002262 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002263 if (Content->OrigEntry) {
2264 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00002265 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002266
Douglas Gregor3120d2c2012-10-22 18:42:04 +00002267 // The source location entry is a file. Emit input file ID.
2268 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2269 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002271 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002272
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00002273 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002274 if (FDI != FileDeclIDs.end()) {
2275 Record.push_back(FDI->second->FirstDeclIndex);
2276 Record.push_back(FDI->second->DeclIDs.size());
2277 } else {
2278 Record.push_back(0);
2279 Record.push_back(0);
2280 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002281
2282 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2283
Richard Smithaada85c2016-02-06 02:06:43 +00002284 if (Content->BufferOverridden || Content->IsTransient)
2285 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00002286 } else {
2287 // The source location entry is a buffer. The blob associated
2288 // with this entry contains the contents of the buffer.
2289
2290 // We add one to the size so that we capture the trailing NULL
2291 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2292 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00002293 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00002294 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00002295 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002296 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00002297 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00002298 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00002299
Mehdi Amini99d1b292016-10-01 16:38:28 +00002300 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00002301 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00002302 }
Richard Smithaada85c2016-02-06 02:06:43 +00002303
2304 if (EmitBlob) {
2305 // Include the implicit terminating null character in the on-disk buffer
2306 // if we're writing it uncompressed.
2307 const llvm::MemoryBuffer *Buffer =
2308 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2309 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00002310 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2311 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00002312 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002313 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002314 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002315 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002316 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2317 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2318 AddSourceLocation(Expansion.isMacroArgExpansion()
2319 ? SourceLocation()
2320 : Expansion.getExpansionLocEnd(),
2321 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002322
2323 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002324 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002325 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002326 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002327 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002328 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002329 }
2330 }
2331
Douglas Gregor8f45df52009-04-16 22:23:12 +00002332 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002333
2334 if (SLocEntryOffsets.empty())
2335 return;
2336
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002337 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002338 // table is used for lazily loading source-location information.
2339 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002340
David Blaikieb44f0bf2017-01-04 22:36:43 +00002341 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002342 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002344 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002345 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00002346 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002347 {
2348 RecordData::value_type Record[] = {
2349 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2350 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2351 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2352 bytes(SLocEntryOffsets));
2353 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002354 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002355 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002356 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002357
2358 // Write the line table. It depends on remapping working, so it must come
2359 // after the source location offsets.
2360 if (SourceMgr.hasLineTable()) {
2361 LineTableInfo &LineTable = SourceMgr.getLineTable();
2362
2363 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002364
2365 // Emit the needed file names.
2366 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002367 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002368 for (const auto &L : LineTable) {
2369 if (L.first.ID < 0)
2370 continue;
2371 for (auto &LE : L.second) {
2372 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002373 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002374 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2375 }
2376 }
2377 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002378
2379 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002380 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002381 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002382 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002383 continue;
2384
2385 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002386 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002387
2388 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002389 Record.push_back(L.second.size());
2390 for (const auto &LE : L.second) {
2391 Record.push_back(LE.FileOffset);
2392 Record.push_back(LE.LineNo);
2393 Record.push_back(FilenameMap[LE.FilenameID]);
2394 Record.push_back((unsigned)LE.FileKind);
2395 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002396 }
2397 }
Richard Smith63078492015-09-01 07:41:55 +00002398
Douglas Gregor925296b2011-07-19 16:10:42 +00002399 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2400 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002401}
2402
Douglas Gregorc5046832009-04-27 18:38:38 +00002403//===----------------------------------------------------------------------===//
2404// Preprocessor Serialization
2405//===----------------------------------------------------------------------===//
2406
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002407static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2408 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002409 if (MacroInfo *MI = MD->getMacroInfo())
2410 if (MI->isBuiltinMacro())
2411 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002412
2413 if (IsModule) {
2414 SourceLocation Loc = MD->getLocation();
2415 if (Loc.isInvalid())
2416 return true;
2417 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2418 return true;
2419 }
2420
2421 return false;
2422}
2423
Chris Lattnereeffaef2009-04-10 17:15:23 +00002424/// \brief Writes the block containing the serialized form of the
2425/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002426void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002427 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2428 if (PPRec)
2429 WritePreprocessorDetail(*PPRec);
2430
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002431 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002432 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002433
Chris Lattner0af3ba12009-04-13 01:29:17 +00002434 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2435 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002436 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002437 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002438 }
2439
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002440 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2441 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002442 auto SkipInfo = PP.getPreambleSkipInfo();
2443 if (SkipInfo.hasValue()) {
2444 Record.push_back(true);
2445 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2446 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2447 Record.push_back(SkipInfo->FoundNonSkipPortion);
2448 Record.push_back(SkipInfo->FoundElse);
2449 AddSourceLocation(SkipInfo->ElseLoc, Record);
2450 } else {
2451 Record.push_back(false);
2452 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002453 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2454 AddSourceLocation(Cond.IfLoc, Record);
2455 Record.push_back(Cond.WasSkipping);
2456 Record.push_back(Cond.FoundNonSkip);
2457 Record.push_back(Cond.FoundElse);
2458 }
2459 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2460 Record.clear();
2461 }
2462
Douglas Gregoreda6a892009-04-26 00:07:37 +00002463 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002464 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002465
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002466 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002467 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002468 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002469 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002470
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002471 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002472 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002473
Richard Smithee977932015-05-01 21:22:17 +00002474 // Construct the list of identifiers with macro directives that need to be
2475 // serialized.
2476 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2477 for (auto &Id : PP.getIdentifierTable())
2478 if (Id.second->hadMacroDefinition() &&
2479 (!Id.second->isFromAST() ||
2480 Id.second->hasChangedSinceDeserialization()))
2481 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002482 // Sort the set of macro definitions that need to be serialized by the
2483 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002484 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2485 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002486
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002487 // Emit the macro directives as a list and associate the offset with the
2488 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002489 for (const IdentifierInfo *Name : MacroIdentifiers) {
2490 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002491 auto StartOffset = Stream.GetCurrentBitNo();
2492
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002493 // Emit the macro directives in reverse source order.
2494 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002495 // Once we hit an ignored macro, we're done: the rest of the chain
2496 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002497 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002498 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002499
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002500 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002501 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002502 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002503 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002504 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002505 Record.push_back(VisMD->isPublic());
2506 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002507 }
Richard Smithd7329392015-04-21 21:46:32 +00002508
Richard Smithb8b2ed62015-04-23 18:18:26 +00002509 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002510 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002511 // We write out exported module macros for PCH as well.
2512 auto Leafs = PP.getLeafModuleMacros(Name);
2513 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2514 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2515 while (!Worklist.empty()) {
2516 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002517
Manman Ren33d80292016-05-31 18:19:32 +00002518 // Emit a record indicating this submodule exports this macro.
2519 ModuleMacroRecord.push_back(
2520 getSubmoduleID(Macro->getOwningModule()));
2521 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2522 for (auto *M : Macro->overrides())
2523 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002524
Manman Ren33d80292016-05-31 18:19:32 +00002525 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2526 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002527
Manman Ren33d80292016-05-31 18:19:32 +00002528 // Enqueue overridden macros once we've visited all their ancestors.
2529 for (auto *M : Macro->overrides())
2530 if (++Visits[M] == M->getNumOverridingMacros())
2531 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002532
Manman Ren33d80292016-05-31 18:19:32 +00002533 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002534 }
Richard Smithd7329392015-04-21 21:46:32 +00002535
Richard Smithee977932015-05-01 21:22:17 +00002536 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002537 continue;
2538
Richard Smithd7329392015-04-21 21:46:32 +00002539 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002540 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2541 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002542 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002543
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002544 /// \brief Offsets of each of the macros into the bitstream, indexed by
2545 /// the local macro ID
2546 ///
2547 /// For each identifier that is associated with a macro, this map
2548 /// provides the offset into the bitstream where that macro is
2549 /// defined.
2550 std::vector<uint32_t> MacroOffsets;
2551
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002552 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2553 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2554 MacroInfo *MI = MacroInfosToEmit[I].MI;
2555 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002556
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002557 if (ID < FirstMacroID) {
2558 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2559 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002560 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002561
2562 // Record the local offset of this macro.
2563 unsigned Index = ID - FirstMacroID;
2564 if (Index == MacroOffsets.size())
2565 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2566 else {
2567 if (Index > MacroOffsets.size())
2568 MacroOffsets.resize(Index + 1);
2569
2570 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2571 }
2572
2573 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002574 AddSourceLocation(MI->getDefinitionLoc(), Record);
2575 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2576 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002577 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002578 unsigned Code;
2579 if (MI->isObjectLike()) {
2580 Code = PP_MACRO_OBJECT_LIKE;
2581 } else {
2582 Code = PP_MACRO_FUNCTION_LIKE;
2583
2584 Record.push_back(MI->isC99Varargs());
2585 Record.push_back(MI->isGNUVarargs());
2586 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002587 Record.push_back(MI->getNumParams());
2588 for (const IdentifierInfo *Param : MI->params())
2589 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002590 }
2591
2592 // If we have a detailed preprocessing record, record the macro definition
2593 // ID that corresponds to this macro.
2594 if (PPRec)
2595 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2596
2597 Stream.EmitRecord(Code, Record);
2598 Record.clear();
2599
2600 // Emit the tokens array.
2601 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2602 // Note that we know that the preprocessor does not have any annotation
2603 // tokens in it because they are created by the parser, and thus can't
2604 // be in a macro definition.
2605 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002606 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002607 Stream.EmitRecord(PP_TOKEN, Record);
2608 Record.clear();
2609 }
2610 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002611 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002612
Douglas Gregor92a96f52011-02-08 21:58:10 +00002613 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002614
2615 // Write the offsets table for macro IDs.
2616 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002617
David Blaikieb44f0bf2017-01-04 22:36:43 +00002618 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002619 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2622 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2623
David Blaikieb44f0bf2017-01-04 22:36:43 +00002624 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002625 {
2626 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2627 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2628 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2629 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002630}
2631
2632void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002633 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002634 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002635
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002636 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002637
Douglas Gregor92a96f52011-02-08 21:58:10 +00002638 // Enter the preprocessor block.
2639 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002640
Douglas Gregoraae92242010-03-19 21:51:54 +00002641 // If the preprocessor has a preprocessing record, emit it.
2642 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002643 using namespace llvm;
2644
2645 // Set up the abbreviation for
2646 unsigned InclusionAbbrev = 0;
2647 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002648 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002649 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002655 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002656 }
2657
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002658 unsigned FirstPreprocessorEntityID
2659 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2660 + NUM_PREDEF_PP_ENTITY_IDS;
2661 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002662 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002663 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2664 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002665 E != EEnd;
2666 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002667 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002668
Richard Smith66a81862015-05-04 02:25:31 +00002669 PreprocessedEntityOffsets.push_back(
2670 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002671
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002672 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002673 // Record this macro definition's ID.
2674 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002675
Douglas Gregor92a96f52011-02-08 21:58:10 +00002676 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002677 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2678 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002679 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002680
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002681 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002682 Record.push_back(ME->isBuiltinMacro());
2683 if (ME->isBuiltinMacro())
2684 AddIdentifierRef(ME->getName(), Record);
2685 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002686 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002687 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002688 continue;
2689 }
2690
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002691 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002692 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002693 Record.push_back(ID->getFileName().size());
2694 Record.push_back(ID->wasInQuotes());
2695 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002696 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002697 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002698 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002699 // Check that the FileEntry is not null because it was not resolved and
2700 // we create a PCH even with compiler errors.
2701 if (ID->getFile())
2702 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002703 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002704 continue;
2705 }
2706
2707 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2708 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002709 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002710
Douglas Gregoraae92242010-03-19 21:51:54 +00002711 // Write the offsets table for the preprocessing record.
2712 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002713 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2714
Douglas Gregoraae92242010-03-19 21:51:54 +00002715 // Write the offsets table for identifier IDs.
2716 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002717
David Blaikieb44f0bf2017-01-04 22:36:43 +00002718 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002719 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002722 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002723
Mehdi Amini57a41912015-09-10 01:46:39 +00002724 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2725 FirstPreprocessorEntityID -
2726 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002727 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002728 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002729 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002730
2731 // Write the skipped region table for the preprocessing record.
2732 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2733 if (SkippedRanges.size() > 0) {
2734 std::vector<PPSkippedRange> SerializedSkippedRanges;
2735 SerializedSkippedRanges.reserve(SkippedRanges.size());
2736 for (auto const& Range : SkippedRanges)
2737 SerializedSkippedRanges.emplace_back(Range);
2738
2739 using namespace llvm;
2740 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2741 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2743 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2744
2745 Record.clear();
2746 Record.push_back(PPD_SKIPPED_RANGES);
2747 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2748 bytes(SerializedSkippedRanges));
2749 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002750}
2751
Richard Smith386bb072015-08-18 23:42:23 +00002752unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002753 if (!Mod)
2754 return 0;
2755
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002756 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2757 if (Known != SubmoduleIDs.end())
2758 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002759
Richard Smithdc1f0422016-07-20 19:10:16 +00002760 auto *Top = Mod->getTopLevelModule();
2761 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002762 (getLangOpts().CompilingPCH ||
2763 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002764 return 0;
2765
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002766 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2767}
2768
Richard Smith386bb072015-08-18 23:42:23 +00002769unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2770 // FIXME: This can easily happen, if we have a reference to a submodule that
2771 // did not result in us loading a module file for that submodule. For
2772 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2773 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2774 assert((ID || !Mod) &&
2775 "asked for module ID for non-local, non-imported module");
2776 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002777}
2778
Douglas Gregor253eefe2011-12-01 00:59:36 +00002779/// \brief Compute the number of modules within the given tree (including the
2780/// given module).
2781static unsigned getNumberOfModules(Module *Mod) {
2782 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002783 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002784 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002785 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002786
2787 return ChildModules + 1;
2788}
2789
Douglas Gregorde3ef502011-11-30 23:21:26 +00002790void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002791 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002792 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002793
2794 // Write the abbreviations needed for the submodules block.
2795 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002796
David Blaikieb44f0bf2017-01-04 22:36:43 +00002797 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002798 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002800 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002801 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002802 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2803 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2805 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002806 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002807 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002808 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002811 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002812
David Blaikieb44f0bf2017-01-04 22:36:43 +00002813 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002814 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002816 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002817
David Blaikieb44f0bf2017-01-04 22:36:43 +00002818 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002819 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002821 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002822
David Blaikieb44f0bf2017-01-04 22:36:43 +00002823 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002824 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002826 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002827
David Blaikieb44f0bf2017-01-04 22:36:43 +00002828 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002829 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002831 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002832
David Blaikieb44f0bf2017-01-04 22:36:43 +00002833 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002834 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2836 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002837 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002838
David Blaikieb44f0bf2017-01-04 22:36:43 +00002839 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002840 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002842 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002843
David Blaikieb44f0bf2017-01-04 22:36:43 +00002844 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002845 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002847 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002848
David Blaikieb44f0bf2017-01-04 22:36:43 +00002849 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002850 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002852 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002853
David Blaikieb44f0bf2017-01-04 22:36:43 +00002854 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002855 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2856 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002857 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002858
David Blaikieb44f0bf2017-01-04 22:36:43 +00002859 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002860 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2861 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2862 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002863 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002864
David Blaikieb44f0bf2017-01-04 22:36:43 +00002865 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002866 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2867 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002868 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002869
David Blaikieb44f0bf2017-01-04 22:36:43 +00002870 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002871 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002874 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002875
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002876 Abbrev = std::make_shared<BitCodeAbbrev>();
2877 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2879 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2880
Douglas Gregor253eefe2011-12-01 00:59:36 +00002881 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002882 RecordData::value_type Record[] = {
2883 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002884 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002885 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2886
Douglas Gregor69021972011-11-30 17:33:56 +00002887 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002888 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002889 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002890 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002891 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002892 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002893 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002894
2895 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002896 if (Mod->Parent) {
2897 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002898 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002899 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002900
2901 // Emit the definition of the block.
2902 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002903 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2904 ID,
2905 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002906 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002907 Mod->IsFramework,
2908 Mod->IsExplicit,
2909 Mod->IsSystem,
2910 Mod->IsExternC,
2911 Mod->InferSubmodules,
2912 Mod->InferExplicitSubmodules,
2913 Mod->InferExportWildcard,
David Blaikiee6b7c282017-04-11 20:46:34 +00002914 Mod->ConfigMacrosExhaustive};
Mehdi Amini57a41912015-09-10 01:46:39 +00002915 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2916 }
2917
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002918 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002919 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002920 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002921 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002922 }
2923
Douglas Gregor69021972011-11-30 17:33:56 +00002924 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002925 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002926 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002927 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2928 UmbrellaHeader.NameAsWritten);
2929 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002930 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2931 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002932 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002933 }
Richard Smith306d8922014-10-22 23:50:56 +00002934
Douglas Gregor69021972011-11-30 17:33:56 +00002935 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002936 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002937 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002938 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002939 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002940 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002941 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2942 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2943 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002944 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002945 Module::HK_PrivateTextual},
2946 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002947 };
2948 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002949 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002950 for (auto &H : Mod->Headers[HL.HeaderKind])
2951 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2952 }
2953
2954 // Emit the top headers.
2955 {
2956 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002957 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002958 for (auto *H : TopHeaders)
2959 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002960 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002961
2962 // Emit the imports.
2963 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002964 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002965 for (auto *I : Mod->Imports)
2966 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002967 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2968 }
2969
Douglas Gregor24bb9232011-12-02 18:58:38 +00002970 // Emit the exports.
2971 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002972 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002973 for (const auto &E : Mod->Exports) {
2974 // FIXME: This may fail; we don't require that all exported modules
2975 // are local or imported.
2976 Record.push_back(getSubmoduleID(E.getPointer()));
2977 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002978 }
2979 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2980 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002981
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002982 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2983 // Might be unnecessary as use declarations are only used to build the
2984 // module itself.
2985
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002986 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002987 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002988 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2989 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002990 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002991 }
2992
Douglas Gregorfb912652013-03-20 21:10:35 +00002993 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002994 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002995 // FIXME: This may fail; we don't require that all conflicting modules
2996 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002997 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2998 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002999 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00003000 }
3001
Douglas Gregor35b13ec2013-03-20 00:22:05 +00003002 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00003003 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003004 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00003005 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00003006 }
3007
Richard Smithdc1f0422016-07-20 19:10:16 +00003008 // Emit the initializers, if any.
3009 RecordData Inits;
3010 for (Decl *D : Context->getModuleInitializers(Mod))
3011 Inits.push_back(GetDeclRef(D));
3012 if (!Inits.empty())
3013 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3014
Douglas Gregorf0b11de2017-09-14 23:38:44 +00003015 // Emit the name of the re-exported module, if any.
3016 if (!Mod->ExportAsModule.empty()) {
3017 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3018 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3019 }
3020
Douglas Gregor69021972011-11-30 17:33:56 +00003021 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00003022 for (auto *M : Mod->submodules())
3023 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00003024 }
3025
3026 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00003027
Richard Smith23d8d032015-05-14 00:45:20 +00003028 assert((NextSubmoduleID - FirstSubmoduleID ==
3029 getNumberOfModules(WritingModule)) &&
3030 "Wrong # of submodules; found a reference to a non-local, "
3031 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00003032}
3033
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00003034void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3035 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003036 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3037 DiagStateIDMap;
3038 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003039 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003040
Richard Smithe37391c2017-05-03 00:28:49 +00003041 auto EncodeDiagStateFlags =
3042 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3043 unsigned Result = (unsigned)DS->ExtBehavior;
3044 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00003045 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3046 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3047 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00003048 Result = (Result << 1) | Val;
3049 return Result;
3050 };
3051
3052 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3053 Record.push_back(Flags);
3054
Richard Smithd230de22017-01-26 01:01:01 +00003055 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3056 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00003057 // Ensure that the diagnostic state wasn't modified since it was created.
3058 // We will not correctly round-trip this information otherwise.
3059 assert(Flags == EncodeDiagStateFlags(State) &&
3060 "diag state flags vary in single AST file");
3061
Richard Smithd230de22017-01-26 01:01:01 +00003062 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003063 Record.push_back(DiagStateID);
Richard Smithd230de22017-01-26 01:01:01 +00003064
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003065 if (DiagStateID == 0) {
3066 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00003067
3068 // Add a placeholder for the number of mappings.
3069 auto SizeIdx = Record.size();
3070 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00003071 for (const auto &I : *State) {
3072 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003073 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00003074 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003075 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003076 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00003077 // Update the placeholder.
3078 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00003079 }
3080 };
3081
3082 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00003083
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003084 // Reserve a spot for the number of locations with state transitions.
3085 auto NumLocationsIdx = Record.size();
3086 Record.emplace_back();
3087
3088 // Emit the state transitions.
3089 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00003090 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3091 if (!FileIDAndFile.first.isValid() ||
3092 !FileIDAndFile.second.HasLocalTransitions)
3093 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003094 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00003095
3096 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3097 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3098 AddSourceLocation(Loc, Record);
3099
Richard Smithd230de22017-01-26 01:01:01 +00003100 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3101 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3102 Record.push_back(StatePoint.Offset);
3103 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003104 }
3105 }
3106
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003107 // Backpatch the number of locations.
3108 Record[NumLocationsIdx] = NumLocations;
3109
3110 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00003111 //
3112 // This also protects against a hypothetical corner case with simulating
3113 // -Werror settings for implicit modules in the ASTReader, where reading
3114 // CurDiagState out of context could change whether warning pragmas are
3115 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003116 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3117 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3118
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00003119 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003120}
3121
Douglas Gregorc5046832009-04-27 18:38:38 +00003122//===----------------------------------------------------------------------===//
3123// Type Serialization
3124//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00003125
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003126/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003127void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00003128 TypeIdx &IdxRef = TypeIdxs[T];
3129 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3130 IdxRef = TypeIdx(NextTypeID++);
3131 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00003132
Douglas Gregor9b3932c2010-10-05 18:37:06 +00003133 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00003134
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003135 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00003136
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003137 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003138 ASTTypeWriter W(*this, Record);
Richard Smith290d8012016-04-06 17:06:00 +00003139 W.Visit(T);
3140 uint64_t Offset = W.Emit();
John McCall8ccfcb52009-09-24 19:53:00 +00003141
Richard Smith290d8012016-04-06 17:06:00 +00003142 // Record the offset for this type.
3143 unsigned Index = Idx.getIndex() - FirstTypeID;
3144 if (TypeOffsets.size() == Index)
3145 TypeOffsets.push_back(Offset);
3146 else if (TypeOffsets.size() < Index) {
3147 TypeOffsets.resize(Index + 1);
3148 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00003149 } else {
Richard Smith290d8012016-04-06 17:06:00 +00003150 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003151 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003152}
3153
Douglas Gregorc5046832009-04-27 18:38:38 +00003154//===----------------------------------------------------------------------===//
3155// Declaration Serialization
3156//===----------------------------------------------------------------------===//
3157
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003158/// \brief Write the block containing all of the declaration IDs
3159/// lexically declared within the given DeclContext.
3160///
3161/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3162/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003163uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003164 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003165 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003166 return 0;
3167
Douglas Gregor8f45df52009-04-16 22:23:12 +00003168 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003169 SmallVector<uint32_t, 128> KindDeclPairs;
3170 for (const auto *D : DC->decls()) {
3171 KindDeclPairs.push_back(D->getKind());
3172 KindDeclPairs.push_back(GetDeclRef(D));
3173 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003174
Douglas Gregora57c3ab2009-04-22 22:34:57 +00003175 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00003176 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00003177 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3178 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003179 return Offset;
3180}
3181
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003182void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003183 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003184
3185 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00003186 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003187 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00003189 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003190 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00003191 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003192 {
3193 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3194 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3195 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3196 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003197
3198 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00003199 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003200 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00003202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00003204 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003205 {
3206 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3207 FirstDeclID - NUM_PREDEF_DECL_IDS};
3208 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3209 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003210}
3211
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003212void ASTWriter::WriteFileDeclIDsMap() {
3213 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003214
Chandler Carruthb306d732015-03-27 00:31:20 +00003215 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3216 FileDeclIDs.begin(), FileDeclIDs.end());
3217 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
3218 llvm::less_first());
3219
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003220 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00003221 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3222 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3223 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3224 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3225 for (auto &LocDeclEntry : Info.DeclIDs)
3226 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003227 }
3228
David Blaikieb44f0bf2017-01-04 22:36:43 +00003229 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003230 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00003231 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003232 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003233 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003234 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3235 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00003236 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003237}
3238
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003239void ASTWriter::WriteComments() {
3240 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00003241 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003242 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003243 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003244 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003245 AddSourceRange(I->getSourceRange(), Record);
3246 Record.push_back(I->getKind());
3247 Record.push_back(I->isTrailingComment());
3248 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003249 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3250 }
3251 Stream.ExitBlock();
3252}
3253
Douglas Gregorc5046832009-04-27 18:38:38 +00003254//===----------------------------------------------------------------------===//
3255// Global Method Pool and Selector Serialization
3256//===----------------------------------------------------------------------===//
3257
Douglas Gregore84a9da2009-04-20 20:36:09 +00003258namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003259
Douglas Gregorc78d3462009-04-24 21:10:55 +00003260// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003261class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003262 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003263
3264public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003265 using key_type = Selector;
3266 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003267
Sebastian Redl834bb972010-08-04 17:20:04 +00003268 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00003269 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00003270 ObjCMethodList Instance, Factory;
3271 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003272 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003273
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003274 using hash_value_type = unsigned;
3275 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003276
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003277 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00003278
Justin Bogner25463f12014-04-18 20:27:24 +00003279 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00003280 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003283 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003284 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00003285 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003286 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003287
Justin Bognere1c147c2014-03-28 22:03:19 +00003288 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003289 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00003290 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00003291 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3292 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003293 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003294 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003295 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00003296 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003297 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003298 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003299 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00003300 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003301 return std::make_pair(KeyLen, DataLen);
3302 }
Mike Stump11289f42009-09-09 15:08:12 +00003303
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003304 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003305 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003306
Justin Bognere1c147c2014-03-28 22:03:19 +00003307 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00003308 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003309 assert((Start >> 32) == 0 && "Selector key offset too large");
3310 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003311 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00003312 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003313 if (N == 0)
3314 N = 1;
3315 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00003316 LE.write<uint32_t>(
3317 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003318 }
Mike Stump11289f42009-09-09 15:08:12 +00003319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003321 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003322 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003323
Justin Bognere1c147c2014-03-28 22:03:19 +00003324 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003325 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00003326 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003327 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003328 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003329 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003330 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003331 ++NumInstanceMethods;
3332
3333 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003334 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003335 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003336 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003337 ++NumFactoryMethods;
3338
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003339 unsigned InstanceBits = Methods.Instance.getBits();
3340 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003341 unsigned InstanceHasMoreThanOneDeclBit =
3342 Methods.Instance.hasMoreThanOneDecl();
3343 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3344 (InstanceHasMoreThanOneDeclBit << 2) |
3345 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003346 unsigned FactoryBits = Methods.Factory.getBits();
3347 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003348 unsigned FactoryHasMoreThanOneDeclBit =
3349 Methods.Factory.hasMoreThanOneDecl();
3350 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3351 (FactoryHasMoreThanOneDeclBit << 2) |
3352 FactoryBits;
3353 LE.write<uint16_t>(FullInstanceBits);
3354 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003355 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003356 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003357 if (Method->getMethod())
3358 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003359 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003360 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003361 if (Method->getMethod())
3362 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003363
3364 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003365 }
3366};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003367
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003368} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003369
Sebastian Redla19a67f2010-08-03 21:58:15 +00003370/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003371///
3372/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003373/// in an on-disk hash table indexed by the selector. The hash table also
3374/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003375void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003376 using namespace llvm;
3377
Sebastian Redla19a67f2010-08-03 21:58:15 +00003378 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003379 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003380 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003381 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003382 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003383 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003384 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003385 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003386
Sebastian Redla19a67f2010-08-03 21:58:15 +00003387 // Create the on-disk hash table representation. We walk through every
3388 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003389 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003390 for (auto &SelectorAndID : SelectorIDs) {
3391 Selector S = SelectorAndID.first;
3392 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003393 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003394 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003395 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003396 ObjCMethodList(),
3397 ObjCMethodList()
3398 };
3399 if (F != SemaRef.MethodPool.end()) {
3400 Data.Instance = F->second.first;
3401 Data.Factory = F->second.second;
3402 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003403 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003404 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003405 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003406 // Selector already exists. Did it change?
3407 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003408 for (ObjCMethodList *M = &Data.Instance;
3409 !changed && M && M->getMethod(); M = M->getNext()) {
3410 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003411 changed = true;
3412 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003413 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003414 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003415 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003416 changed = true;
3417 }
3418 if (!changed)
3419 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003420 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003421 // A new method pool entry.
3422 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003423 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003424 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003425 }
3426
Douglas Gregorc78d3462009-04-24 21:10:55 +00003427 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003428 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003429 uint32_t BucketOffset;
3430 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003431 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003432
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003433 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003434 llvm::raw_svector_ostream Out(MethodPool);
3435 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003436 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003437 BucketOffset = Generator.Emit(Out, Trait);
3438 }
3439
3440 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003441 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003442 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003444 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003446 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003447
Douglas Gregor95c13f52009-04-25 17:48:32 +00003448 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003449 {
3450 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3451 NumTableEntries};
3452 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3453 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003454
3455 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003456 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003457 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003461 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003462
3463 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003464 {
3465 RecordData::value_type Record[] = {
3466 SELECTOR_OFFSETS, SelectorOffsets.size(),
3467 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3468 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3469 bytes(SelectorOffsets));
3470 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003471 }
3472}
3473
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003474/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003475void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003476 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003477
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003478 if (SemaRef.ReferencedSelectors.empty())
3479 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003480
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003481 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003482 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003483
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003484 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003485 // very tricky to fix, and given that @selector shouldn't really appear in
3486 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003487 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3488 Selector Sel = SelectorAndLocation.first;
3489 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003490 Writer.AddSelectorRef(Sel);
3491 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003492 }
Richard Smithe64e7452016-04-18 21:54:58 +00003493 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003494}
3495
Douglas Gregorc5046832009-04-27 18:38:38 +00003496//===----------------------------------------------------------------------===//
3497// Identifier Table Serialization
3498//===----------------------------------------------------------------------===//
3499
Richard Smithb3761912015-02-05 23:08:52 +00003500/// Determine the declaration that should be put into the name lookup table to
3501/// represent the given declaration in this module. This is usually D itself,
3502/// but if D was imported and merged into a local declaration, we want the most
3503/// recent local declaration instead. The chosen declaration will be the most
3504/// recent declaration in any module that imports this one.
3505static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3506 NamedDecl *D) {
3507 if (!LangOpts.Modules || !D->isFromASTFile())
3508 return D;
3509
3510 if (Decl *Redecl = D->getPreviousDecl()) {
3511 // For Redeclarable decls, a prior declaration might be local.
3512 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003513 // If we find a local decl, we're done.
3514 if (!Redecl->isFromASTFile()) {
3515 // Exception: in very rare cases (for injected-class-names), not all
3516 // redeclarations are in the same semantic context. Skip ones in a
3517 // different context. They don't go in this lookup table at all.
3518 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3519 D->getDeclContext()->getRedeclContext()))
3520 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003521 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003522 }
3523
Richard Smithfe620d22015-03-05 23:24:12 +00003524 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003525 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003526 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003527 break;
3528 }
3529 } else if (Decl *First = D->getCanonicalDecl()) {
3530 // For Mergeable decls, the first decl might be local.
3531 if (!First->isFromASTFile())
3532 return cast<NamedDecl>(First);
3533 }
3534
3535 // All declarations are imported. Our most recent declaration will also be
3536 // the most recent one in anyone who imports us.
3537 return D;
3538}
3539
Douglas Gregorc78d3462009-04-24 21:10:55 +00003540namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003541
Richard Smithcf97cf62015-04-19 01:34:23 +00003542class ASTIdentifierTableTrait {
3543 ASTWriter &Writer;
3544 Preprocessor &PP;
3545 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003546 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003547 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003548 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003549
3550 /// \brief Determines whether this is an "interesting" identifier that needs a
3551 /// full IdentifierInfo structure written into the hash table. Notably, this
3552 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3553 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003554 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003555 if (MacroOffset ||
3556 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003557 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003558 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003559 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003560 return true;
3561
3562 return false;
3563 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003564
Douglas Gregore84a9da2009-04-20 20:36:09 +00003565public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003566 using key_type = IdentifierInfo *;
3567 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003568
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003569 using data_type = IdentID;
3570 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003571
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003572 using hash_value_type = unsigned;
3573 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003574
Richard Smithd7329392015-04-21 21:46:32 +00003575 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003576 IdentifierResolver &IdResolver, bool IsModule,
3577 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003578 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003579 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3580 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003581
Richard Smithd79514e2016-02-05 19:03:40 +00003582 bool needDecls() const { return NeedDecls; }
3583
Justin Bogner25463f12014-04-18 20:27:24 +00003584 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003585 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003586 }
Mike Stump11289f42009-09-09 15:08:12 +00003587
Richard Smith33e0f7e2015-07-22 02:08:40 +00003588 bool isInterestingIdentifier(const IdentifierInfo *II) {
3589 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3590 return isInterestingIdentifier(II, MacroOffset);
3591 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003592
Richard Smith9c254182015-07-19 21:41:12 +00003593 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3594 return isInterestingIdentifier(II, 0);
3595 }
3596
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003597 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003598 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003599 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003600 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003601 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3602 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003603 DataLen += 2; // 2 bytes for builtin ID
3604 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003605 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003606 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003607
Richard Smitha534a312015-07-21 23:54:07 +00003608 if (NeedDecls) {
3609 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3610 DEnd = IdResolver.end();
3611 D != DEnd; ++D)
3612 DataLen += 4;
3613 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003614 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003615
Justin Bognere1c147c2014-03-28 22:03:19 +00003616 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003617
Justin Bognere1c147c2014-03-28 22:03:19 +00003618 endian::Writer<little> LE(Out);
3619
Richard Smithdf8a8312015-03-13 04:05:01 +00003620 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003621 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003622 // We emit the key length after the data length so that every
3623 // string is preceded by a 16-bit length. This matches the PTH
3624 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003625 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003626 return std::make_pair(KeyLen, DataLen);
3627 }
Mike Stump11289f42009-09-09 15:08:12 +00003628
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003629 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003630 unsigned KeyLen) {
3631 // Record the location of the key data. This is used when generating
3632 // the mapping from persistent IDs to strings.
3633 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003634
3635 // Emit the offset of the key/data length information to the interesting
3636 // identifiers table if necessary.
3637 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3638 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3639
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003640 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003641 }
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003643 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003644 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003645 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003646
Justin Bognere1c147c2014-03-28 22:03:19 +00003647 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003648
Richard Smithd7329392015-04-21 21:46:32 +00003649 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3650 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003651 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003652 return;
3653 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003654
Justin Bognere1c147c2014-03-28 22:03:19 +00003655 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003656 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3657 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003658 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003659 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003660 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003661 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003662 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3663 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003664 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003665 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003666 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003667 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003668
Richard Smithd7329392015-04-21 21:46:32 +00003669 if (HadMacroDefinition)
3670 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003671
Richard Smitha534a312015-07-21 23:54:07 +00003672 if (NeedDecls) {
3673 // Emit the declaration IDs in reverse order, because the
3674 // IdentifierResolver provides the declarations as they would be
3675 // visible (e.g., the function "stat" would come before the struct
3676 // "stat"), but the ASTReader adds declarations to the end of the list
3677 // (so we need to see the struct "stat" before the function "stat").
3678 // Only emit declarations that aren't from a chained PCH, though.
3679 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3680 IdResolver.end());
3681 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3682 DEnd = Decls.rend();
3683 D != DEnd; ++D)
3684 LE.write<uint32_t>(
3685 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3686 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003687 }
3688};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003689
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003690} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003691
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003692/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003693///
3694/// The identifier table consists of a blob containing string data
3695/// (the actual identifiers themselves) and a separate "offsets" index
3696/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003697void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3698 IdentifierResolver &IdResolver,
3699 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003700 using namespace llvm;
3701
Richard Smith33e0f7e2015-07-22 02:08:40 +00003702 RecordData InterestingIdents;
3703
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003704 // Create and write out the blob that contains the identifier
3705 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003706 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003707 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003708 ASTIdentifierTableTrait Trait(
3709 *this, PP, IdResolver, IsModule,
3710 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003711
Douglas Gregore6648fb2009-04-28 20:33:11 +00003712 // Look for any identifiers that were named while processing the
3713 // headers, but are otherwise not needed. We add these to the hash
3714 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003715 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003716 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003717 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003718 for (const auto &ID : PP.getIdentifierTable())
3719 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003720 // Sort the identifiers lexicographically before getting them references so
3721 // that their order is stable.
3722 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3723 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003724 if (Trait.isInterestingNonMacroIdentifier(II))
3725 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003726
Sebastian Redlff4a2952010-07-23 23:49:55 +00003727 // Create the on-disk hash table representation. We only store offsets
3728 // for identifiers that appear here for the first time.
3729 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003730 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003731 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003732 IdentID ID = IdentIDPair.second;
3733 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003734 // Write out identifiers if either the ID is local or the identifier has
3735 // changed since it was loaded.
3736 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3737 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003738 (Trait.needDecls() &&
3739 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003740 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003741 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003742
Douglas Gregore84a9da2009-04-20 20:36:09 +00003743 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003744 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003745 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003746 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003747 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003748
Douglas Gregore84a9da2009-04-20 20:36:09 +00003749 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003750 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003751 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003752 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003753 }
3754
3755 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003756 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003757 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003760 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003761
3762 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003763 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003764 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003765 }
3766
3767 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003768 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003769 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003770 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003773 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003774
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003775#ifndef NDEBUG
3776 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3777 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3778#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003779
3780 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3781 IdentifierOffsets.size(),
3782 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003783 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003784 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003785
3786 // In C++, write the list of interesting identifiers (those that are
3787 // defined as macros, poisoned, or similar unusual things).
3788 if (!InterestingIdents.empty())
3789 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003790}
3791
Douglas Gregorc5046832009-04-27 18:38:38 +00003792//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003793// DeclContext's Name Lookup Table Serialization
3794//===----------------------------------------------------------------------===//
3795
3796namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003797
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003798// Trait used for the on-disk hash table used in the method pool.
3799class ASTDeclContextNameLookupTrait {
3800 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003801 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003802
3803public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003804 using key_type = DeclarationNameKey;
3805 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003806
Richard Smithd88a7f12015-09-01 20:35:42 +00003807 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003808 using data_type = std::pair<unsigned, unsigned>;
3809 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003810
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003811 using hash_value_type = unsigned;
3812 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003813
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003814 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003815
Richard Smithd88a7f12015-09-01 20:35:42 +00003816 template<typename Coll>
3817 data_type getData(const Coll &Decls) {
3818 unsigned Start = DeclIDs.size();
3819 for (NamedDecl *D : Decls) {
3820 DeclIDs.push_back(
3821 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3822 }
3823 return std::make_pair(Start, DeclIDs.size());
3824 }
3825
3826 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3827 unsigned Start = DeclIDs.size();
3828 for (auto ID : FromReader)
3829 DeclIDs.push_back(ID);
3830 return std::make_pair(Start, DeclIDs.size());
3831 }
3832
3833 static bool EqualKey(key_type_ref a, key_type_ref b) {
3834 return a == b;
3835 }
3836
Richard Smitha06c7e62015-08-26 23:55:49 +00003837 hash_value_type ComputeHash(DeclarationNameKey Name) {
3838 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003839 }
3840
Richard Smithd88a7f12015-09-01 20:35:42 +00003841 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3842 assert(Writer.hasChain() &&
3843 "have reference to loaded module file but no chain?");
3844
3845 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003846
Richard Smithd88a7f12015-09-01 20:35:42 +00003847 endian::Writer<little>(Out)
3848 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3849 }
3850
Richard Smitha06c7e62015-08-26 23:55:49 +00003851 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3852 DeclarationNameKey Name,
3853 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003854 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003855
Justin Bognere1c147c2014-03-28 22:03:19 +00003856 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003857 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003858 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003859 case DeclarationName::Identifier:
3860 case DeclarationName::ObjCZeroArgSelector:
3861 case DeclarationName::ObjCOneArgSelector:
3862 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003863 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003864 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003865 KeyLen += 4;
3866 break;
3867 case DeclarationName::CXXOperatorName:
3868 KeyLen += 1;
3869 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003870 case DeclarationName::CXXConstructorName:
3871 case DeclarationName::CXXDestructorName:
3872 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003873 case DeclarationName::CXXUsingDirective:
3874 break;
3875 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003876 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003877
Richard Smithf02662d2015-07-30 03:17:16 +00003878 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003879 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3880 assert(uint16_t(DataLen) == DataLen &&
3881 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003882 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003883
3884 return std::make_pair(KeyLen, DataLen);
3885 }
3886
Richard Smitha06c7e62015-08-26 23:55:49 +00003887 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003888 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003889
Justin Bognere1c147c2014-03-28 22:03:19 +00003890 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003891 LE.write<uint8_t>(Name.getKind());
3892 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003893 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003894 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003895 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003896 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003897 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003898 case DeclarationName::ObjCZeroArgSelector:
3899 case DeclarationName::ObjCOneArgSelector:
3900 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003901 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003902 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003903 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003904 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003905 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003906 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003907 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003908 case DeclarationName::CXXConstructorName:
3909 case DeclarationName::CXXDestructorName:
3910 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003911 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003912 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003913 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003914
3915 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003916 }
3917
Richard Smitha06c7e62015-08-26 23:55:49 +00003918 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3919 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003920 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003921
Justin Bognere1c147c2014-03-28 22:03:19 +00003922 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003923 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003924 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3925 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003926 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3927 }
3928};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003929
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003930} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003931
Chandler Carruthe972c362015-03-26 03:11:40 +00003932bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3933 DeclContext *DC) {
3934 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3935}
3936
3937bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3938 DeclContext *DC) {
3939 for (auto *D : Result.getLookupResult())
3940 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3941 return false;
3942
3943 return true;
3944}
3945
Richard Smithd88a7f12015-09-01 20:35:42 +00003946void
Chandler Carruthe972c362015-03-26 03:11:40 +00003947ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003948 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003949 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3950 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003951 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003952
Chandler Carruthe972c362015-03-26 03:11:40 +00003953 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003954 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003955 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3956
3957 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003958 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3959 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003960 ASTDeclContextNameLookupTrait Trait(*this);
3961
Chandler Carruthe972c362015-03-26 03:11:40 +00003962 // The first step is to collect the declaration names which we need to
3963 // serialize into the name lookup table, and to collect them in a stable
3964 // order.
3965 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003966
Chandler Carruthe972c362015-03-26 03:11:40 +00003967 // We also build up small sets of the constructor and conversion function
3968 // names which are visible.
3969 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003970
Chandler Carruthe972c362015-03-26 03:11:40 +00003971 for (auto &Lookup : *DC->buildLookup()) {
3972 auto &Name = Lookup.first;
3973 auto &Result = Lookup.second;
3974
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003975 // If there are no local declarations in our lookup result, we
3976 // don't need to write an entry for the name at all. If we can't
3977 // write out a lookup set without performing more deserialization,
3978 // just skip this entry.
3979 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003980 isLookupResultEntirelyExternal(Result, DC))
3981 continue;
3982
3983 // We also skip empty results. If any of the results could be external and
3984 // the currently available results are empty, then all of the results are
3985 // external and we skip it above. So the only way we get here with an empty
3986 // results is when no results could have been external *and* we have
3987 // external results.
3988 //
3989 // FIXME: While we might want to start emitting on-disk entries for negative
3990 // lookups into a decl context as an optimization, today we *have* to skip
3991 // them because there are names with empty lookup results in decl contexts
3992 // which we can't emit in any stable ordering: we lookup constructors and
3993 // conversion functions in the enclosing namespace scope creating empty
3994 // results for them. This in almost certainly a bug in Clang's name lookup,
3995 // but that is likely to be hard or impossible to fix and so we tolerate it
3996 // here by omitting lookups with empty results.
3997 if (Lookup.second.getLookupResult().empty())
3998 continue;
3999
4000 switch (Lookup.first.getNameKind()) {
4001 default:
4002 Names.push_back(Lookup.first);
4003 break;
4004
Richard Smithcd45dbc2014-04-19 03:48:30 +00004005 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00004006 assert(isa<CXXRecordDecl>(DC) &&
4007 "Cannot have a constructor name outside of a class!");
4008 ConstructorNameSet.insert(Name);
4009 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00004010
4011 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00004012 assert(isa<CXXRecordDecl>(DC) &&
4013 "Cannot have a conversion function name outside of a class!");
4014 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00004015 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00004016 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00004017 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00004018
Chandler Carruthe972c362015-03-26 03:11:40 +00004019 // Sort the names into a stable order.
4020 std::sort(Names.begin(), Names.end());
4021
Chandler Carruthffbf7052015-03-26 22:27:09 +00004022 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00004023 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00004024 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00004025
Chandler Carruthffbf7052015-03-26 22:27:09 +00004026 // First we try the easy case by forming the current context's constructor
4027 // name and adding that name first. This is a very useful optimization to
4028 // avoid walking the lexical declarations in many cases, and it also
4029 // handles the only case where a constructor name can come from some other
4030 // lexical context -- when that name is an implicit constructor merged from
4031 // another declaration in the redecl chain. Any non-implicit constructor or
4032 // conversion function which doesn't occur in all the lexical contexts
4033 // would be an ODR violation.
4034 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4035 Context->getCanonicalType(Context->getRecordType(D)));
4036 if (ConstructorNameSet.erase(ImplicitCtorName))
4037 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00004038
Chandler Carruthffbf7052015-03-26 22:27:09 +00004039 // If we still have constructors or conversion functions, we walk all the
4040 // names in the decl and add the constructors and conversion functions
4041 // which are visible in the order they lexically occur within the context.
4042 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4043 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4044 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4045 auto Name = ChildND->getDeclName();
4046 switch (Name.getNameKind()) {
4047 default:
4048 continue;
4049
4050 case DeclarationName::CXXConstructorName:
4051 if (ConstructorNameSet.erase(Name))
4052 Names.push_back(Name);
4053 break;
4054
4055 case DeclarationName::CXXConversionFunctionName:
4056 if (ConversionNameSet.erase(Name))
4057 Names.push_back(Name);
4058 break;
4059 }
4060
4061 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4062 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00004063 }
4064
Chandler Carruthe972c362015-03-26 03:11:40 +00004065 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4066 "constructors by walking all the "
4067 "lexical members of the context.");
4068 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4069 "conversion functions by walking all "
4070 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00004071 }
4072
Chandler Carruthe972c362015-03-26 03:11:40 +00004073 // Next we need to do a lookup with each name into this decl context to fully
4074 // populate any results from external sources. We don't actually use the
4075 // results of these lookups because we only want to use the results after all
4076 // results have been loaded and the pointers into them will be stable.
4077 for (auto &Name : Names)
4078 DC->lookup(Name);
4079
4080 // Now we need to insert the results for each name into the hash table. For
4081 // constructor names and conversion function names, we actually need to merge
4082 // all of the results for them into one list of results each and insert
4083 // those.
4084 SmallVector<NamedDecl *, 8> ConstructorDecls;
4085 SmallVector<NamedDecl *, 8> ConversionDecls;
4086
4087 // Now loop over the names, either inserting them or appending for the two
4088 // special cases.
4089 for (auto &Name : Names) {
4090 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4091
4092 switch (Name.getNameKind()) {
4093 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00004094 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004095 break;
4096
4097 case DeclarationName::CXXConstructorName:
4098 ConstructorDecls.append(Result.begin(), Result.end());
4099 break;
4100
4101 case DeclarationName::CXXConversionFunctionName:
4102 ConversionDecls.append(Result.begin(), Result.end());
4103 break;
4104 }
4105 }
4106
4107 // Handle our two special cases if we ended up having any. We arbitrarily use
4108 // the first declaration's name here because the name itself isn't part of
4109 // the key, only the kind of name is used.
4110 if (!ConstructorDecls.empty())
4111 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00004112 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004113 if (!ConversionDecls.empty())
4114 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00004115 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004116
Richard Smithd88a7f12015-09-01 20:35:42 +00004117 // Create the on-disk hash table. Also emit the existing imported and
4118 // merged table if there is one.
4119 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4120 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00004121}
4122
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004123/// \brief Write the block containing all of the declaration IDs
4124/// visible from the given DeclContext.
4125///
4126/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00004127/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004128uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4129 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00004130 // If we imported a key declaration of this namespace, write the visible
4131 // lookup results as an update record for it rather than including them
4132 // on this declaration. We will only look at key declarations on reload.
4133 if (isa<NamespaceDecl>(DC) && Chain &&
4134 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4135 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004136 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00004137 Prev = Prev->getPreviousDecl())
4138 if (!Prev->isFromASTFile())
4139 return 0;
4140
4141 // Note that we need to emit an update record for the primary context.
4142 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4143
4144 // Make sure all visible decls are written. They will be recorded later. We
4145 // do this using a side data structure so we can sort the names into
4146 // a deterministic order.
4147 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4148 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4149 LookupResults;
4150 if (Map) {
4151 LookupResults.reserve(Map->size());
4152 for (auto &Entry : *Map)
4153 LookupResults.push_back(
4154 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4155 }
4156
4157 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
4158 for (auto &NameAndResult : LookupResults) {
4159 DeclarationName Name = NameAndResult.first;
4160 DeclContext::lookup_result Result = NameAndResult.second;
4161 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4162 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4163 // We have to work around a name lookup bug here where negative lookup
4164 // results for these names get cached in namespace lookup tables (these
4165 // names should never be looked up in a namespace).
4166 assert(Result.empty() && "Cannot have a constructor or conversion "
4167 "function name in a namespace!");
4168 continue;
4169 }
4170
4171 for (NamedDecl *ND : Result)
4172 if (!ND->isFromASTFile())
4173 GetDeclRef(ND);
4174 }
4175
4176 return 0;
4177 }
4178
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004179 if (DC->getPrimaryContext() != DC)
4180 return 0;
4181
Chandler Carruthe972c362015-03-26 03:11:40 +00004182 // Skip contexts which don't support name lookup.
4183 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004184 return 0;
4185
4186 // If not in C++, we perform name lookup for the translation unit via the
4187 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004188 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004189 return 0;
4190
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004191 // Serialize the contents of the mapping used for lookup. Note that,
4192 // although we have two very different code paths, the serialized
4193 // representation is the same for both cases: a declaration name,
4194 // followed by a size, followed by references to the visible
4195 // declarations that have that name.
4196 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00004197 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004198 if (!Map || Map->empty())
4199 return 0;
4200
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004201 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004202 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00004203 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004204
4205 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00004206 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004207 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00004208 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004209 ++NumVisibleDeclContexts;
4210 return Offset;
4211}
4212
Sebastian Redla4071b42010-08-24 00:50:09 +00004213/// \brief Write an UPDATE_VISIBLE block for the given context.
4214///
4215/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4216/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00004217/// (in C++), for namespaces, and for classes with forward-declared unscoped
4218/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00004219void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00004220 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00004221 if (!Map || Map->empty())
4222 return;
4223
Sebastian Redla4071b42010-08-24 00:50:09 +00004224 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004225 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00004226 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00004227
Richard Smith5fc18a92015-07-12 23:43:21 +00004228 // If we're updating a namespace, select a key declaration as the key for the
4229 // update record; those are the only ones that will be checked on reload.
4230 if (isa<NamespaceDecl>(DC))
4231 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4232
Sebastian Redla4071b42010-08-24 00:50:09 +00004233 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00004234 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00004235 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00004236}
4237
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004238/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4239void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Adam Nemet484aa452017-03-27 19:17:25 +00004240 RecordData::value_type Record[] = {Opts.getInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004241 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4242}
4243
4244/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4245void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004246 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004247 return;
4248
4249 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4250 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00004251 for (const auto &I:Opts.OptMap) {
4252 AddString(I.getKey(), Record);
4253 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00004254 Record.push_back(V.Supported ? 1 : 0);
4255 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00004256 Record.push_back(V.Avail);
4257 Record.push_back(V.Core);
4258 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004259 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4260}
4261
Yaxun Liu5b746652016-12-18 05:18:55 +00004262void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4263 if (!SemaRef.Context.getLangOpts().OpenCL)
4264 return;
4265
4266 RecordData Record;
4267 for (const auto &I : SemaRef.OpenCLTypeExtMap) {
4268 Record.push_back(
4269 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
4270 Record.push_back(I.second.size());
4271 for (auto Ext : I.second)
4272 AddString(Ext, Record);
4273 }
4274 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4275}
4276
4277void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4278 if (!SemaRef.Context.getLangOpts().OpenCL)
4279 return;
4280
4281 RecordData Record;
4282 for (const auto &I : SemaRef.OpenCLDeclExtMap) {
4283 Record.push_back(getDeclID(I.first));
4284 Record.push_back(static_cast<unsigned>(I.second.size()));
4285 for (auto Ext : I.second)
4286 AddString(Ext, Record);
4287 }
4288 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4289}
4290
Justin Lebar67a78a62016-10-08 22:15:58 +00004291void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4292 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4293 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4294 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4295 }
4296}
4297
Douglas Gregor404cdde2012-01-27 01:47:08 +00004298void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004299 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00004300 RecordData Categories;
4301
4302 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4303 unsigned Size = 0;
4304 unsigned StartIndex = Categories.size();
4305
4306 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4307
4308 // Allocate space for the size.
4309 Categories.push_back(0);
4310
4311 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004312 for (ObjCInterfaceDecl::known_categories_iterator
4313 Cat = Class->known_categories_begin(),
4314 CatEnd = Class->known_categories_end();
4315 Cat != CatEnd; ++Cat, ++Size) {
4316 assert(getDeclID(*Cat) != 0 && "Bogus category");
4317 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004318 }
4319
4320 // Update the size.
4321 Categories[StartIndex] = Size;
4322
4323 // Record this interface -> category map.
4324 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4325 CategoriesMap.push_back(CatInfo);
4326 }
4327
4328 // Sort the categories map by the definition ID, since the reader will be
4329 // performing binary searches on this information.
4330 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4331
4332 // Emit the categories map.
4333 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004334
David Blaikieb44f0bf2017-01-04 22:36:43 +00004335 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004336 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4338 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004339 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004340
4341 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4342 Stream.EmitRecordWithBlob(AbbrevID, Record,
4343 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004344 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004345
Douglas Gregor404cdde2012-01-27 01:47:08 +00004346 // Emit the category lists.
4347 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4348}
4349
Richard Smithe40f2ba2013-08-07 21:41:30 +00004350void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4351 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4352
4353 if (LPTMap.empty())
4354 return;
4355
4356 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004357 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004358 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004359 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004360 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004361 AddDeclRef(LPT.D, Record);
4362 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004363
Justin Lebar28f09c52016-10-10 16:26:08 +00004364 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004365 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004366 }
4367 }
4368 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4369}
4370
Dario Domizioli13a0a382014-05-23 12:13:25 +00004371/// \brief Write the state of 'pragma clang optimize' at the end of the module.
4372void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4373 RecordData Record;
4374 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4375 AddSourceLocation(PragmaLoc, Record);
4376 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4377}
4378
Nico Weber779355f2016-03-02 23:22:00 +00004379/// \brief Write the state of 'pragma ms_struct' at the end of the module.
4380void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4381 RecordData Record;
4382 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4383 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4384}
4385
Nico Weber42932312016-03-03 00:17:35 +00004386/// \brief Write the state of 'pragma pointers_to_members' at the end of the
4387//module.
4388void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4389 RecordData Record;
4390 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4391 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4392 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4393}
4394
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004395/// \brief Write the state of 'pragma pack' at the end of the module.
4396void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004397 // Don't serialize pragma pack state for modules, since it should only take
4398 // effect on a per-submodule basis.
4399 if (WritingModule)
4400 return;
4401
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004402 RecordData Record;
4403 Record.push_back(SemaRef.PackStack.CurrentValue);
4404 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4405 Record.push_back(SemaRef.PackStack.Stack.size());
4406 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4407 Record.push_back(StackEntry.Value);
4408 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004409 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004410 AddString(StackEntry.StackSlotLabel, Record);
4411 }
4412 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4413}
4414
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004415void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4416 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004417 // Enter the extension block.
4418 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4419
4420 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004421 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004422 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4423 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4424 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4425 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4426 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4427 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004428 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004429
4430 // Emit the metadata record.
4431 RecordData Record;
4432 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4433 Record.push_back(EXTENSION_METADATA);
4434 Record.push_back(Metadata.MajorVersion);
4435 Record.push_back(Metadata.MinorVersion);
4436 Record.push_back(Metadata.BlockName.size());
4437 Record.push_back(Metadata.UserInfo.size());
4438 SmallString<64> Buffer;
4439 Buffer += Metadata.BlockName;
4440 Buffer += Metadata.UserInfo;
4441 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4442
4443 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004444 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004445
4446 // Exit the extension block.
4447 Stream.ExitBlock();
4448}
4449
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004450//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004451// General Serialization Routines
4452//===----------------------------------------------------------------------===//
4453
Richard Smith69c82bf2016-04-01 22:52:03 +00004454/// \brief Emit the list of attributes to the specified record.
Richard Smith290d8012016-04-06 17:06:00 +00004455void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4456 auto &Record = *this;
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00004457 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004458 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004459 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Richard Smith290d8012016-04-06 17:06:00 +00004460 Record.AddSourceRange(A->getRange());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004461
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004462#include "clang/Serialization/AttrPCHWrite.inc"
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004463 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004464}
4465
John McCallf413f5e2013-05-03 00:10:13 +00004466void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4467 AddSourceLocation(Tok.getLocation(), Record);
4468 Record.push_back(Tok.getLength());
4469
4470 // FIXME: When reading literal tokens, reconstruct the literal pointer
4471 // if it is needed.
4472 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4473 // FIXME: Should translate token kind to a stable encoding.
4474 Record.push_back(Tok.getKind());
4475 // FIXME: Should translate token flags to a stable encoding.
4476 Record.push_back(Tok.getFlags());
4477}
4478
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004479void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004480 Record.push_back(Str.size());
4481 Record.insert(Record.end(), Str.begin(), Str.end());
4482}
4483
Richard Smith7ed1bc92014-12-05 22:42:13 +00004484bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004485 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004486
Richard Smith54cc3c22014-12-11 20:50:24 +00004487 bool Changed =
4488 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004489
4490 // Remove a prefix to make the path relative, if relevant.
4491 const char *PathBegin = Path.data();
4492 const char *PathPtr =
4493 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4494 if (PathPtr != PathBegin) {
4495 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4496 Changed = true;
4497 }
4498
4499 return Changed;
4500}
4501
4502void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4503 SmallString<128> FilePath(Path);
4504 PreparePathForOutput(FilePath);
4505 AddString(FilePath, Record);
4506}
4507
Mehdi Amini57a41912015-09-10 01:46:39 +00004508void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004509 StringRef Path) {
4510 SmallString<128> FilePath(Path);
4511 PreparePathForOutput(FilePath);
4512 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4513}
4514
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004515void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4516 RecordDataImpl &Record) {
4517 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004518 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004519 Record.push_back(*Minor + 1);
4520 else
4521 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004522 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004523 Record.push_back(*Subminor + 1);
4524 else
4525 Record.push_back(0);
4526}
4527
Douglas Gregore84a9da2009-04-20 20:36:09 +00004528/// \brief Note that the identifier II occurs at the given offset
4529/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004530void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004531 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004532 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004533 // up earlier in the chain and thus don't need an offset.
4534 if (ID >= FirstIdentID)
4535 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004536}
4537
Douglas Gregor95c13f52009-04-25 17:48:32 +00004538/// \brief Note that the selector Sel occurs at the given offset
4539/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004540void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004541 unsigned ID = SelectorIDs[Sel];
4542 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004543 // Don't record offsets for selectors that are also available in a different
4544 // file.
4545 if (ID < FirstSelectorID)
4546 return;
4547 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004548}
4549
David Blaikie61137e12017-01-05 18:23:18 +00004550ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004551 SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
David Blaikie61137e12017-01-05 18:23:18 +00004552 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4553 bool IncludeTimestamps)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004554 : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
4555 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004556 for (const auto &Ext : Extensions) {
4557 if (auto Writer = Ext->createExtensionWriter(*this))
4558 ModuleFileExtensionWriters.push_back(std::move(Writer));
4559 }
4560}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004561
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004562ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004563 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004564}
4565
Richard Smithb3761912015-02-05 23:08:52 +00004566const LangOptions &ASTWriter::getLangOpts() const {
4567 assert(WritingAST && "can't determine lang opts when not writing AST");
4568 return Context->getLangOpts();
4569}
4570
Richard Smithe75ee0f2015-08-17 07:13:32 +00004571time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4572 return IncludeTimestamps ? E->getModificationTime() : 0;
4573}
4574
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004575ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4576 const std::string &OutputFile,
4577 Module *WritingModule, StringRef isysroot,
4578 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004579 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004580
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004581 ASTHasCompilerErrors = hasErrors;
4582
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004583 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004584 Stream.Emit((unsigned)'C', 8);
4585 Stream.Emit((unsigned)'P', 8);
4586 Stream.Emit((unsigned)'C', 8);
4587 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004588
Chris Lattner28fa4e62009-04-26 22:26:21 +00004589 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004590
Douglas Gregoreda8e122011-08-09 15:13:55 +00004591 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004592 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004593 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004594 ASTFileSignature Signature =
4595 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004596 Context = nullptr;
4597 PP = nullptr;
4598 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004599 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004600
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004601 WritingAST = false;
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004602 if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
4603 // Construct MemoryBuffer and update buffer manager.
4604 PCMCache.addBuffer(OutputFile,
4605 llvm::MemoryBuffer::getMemBufferCopy(
4606 StringRef(Buffer.begin(), Buffer.size())));
4607 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004608 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004609}
4610
Douglas Gregora94a1542011-07-27 21:45:57 +00004611template<typename Vector>
4612static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4613 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004614 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4615 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004616 Writer.AddDeclRef(*I, Record);
4617 }
4618}
4619
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004620ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4621 const std::string &OutputFile,
4622 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004623 using namespace llvm;
4624
Craig Toppera13603a2014-05-22 05:54:18 +00004625 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004626
Douglas Gregorcf68c582011-12-01 22:20:10 +00004627 // Make sure that the AST reader knows to finalize itself.
4628 if (Chain)
4629 Chain->finalizeForWriting();
4630
Sebastian Redl143413f2010-07-12 22:02:52 +00004631 ASTContext &Context = SemaRef.Context;
4632 Preprocessor &PP = SemaRef.PP;
4633
Douglas Gregordab42432011-08-12 00:15:20 +00004634 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004635 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4636 if (D) {
4637 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4638 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004639 }
4640 };
4641 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4642 PREDEF_DECL_TRANSLATION_UNIT_ID);
4643 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4644 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4645 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4646 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4647 PREDEF_DECL_OBJC_PROTOCOL_ID);
4648 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4649 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4650 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4651 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4652 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004653 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004654 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4655 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004656 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004657 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4658 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004659 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4660 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004661 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4662 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004663 RegisterPredefDecl(Context.TypePackElementDecl,
4664 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004665
Chris Lattner0c797362009-09-08 18:19:27 +00004666 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004667 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004668 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004669 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004670 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004671
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004672 // Build a record containing all of the file scoped decls in this file.
4673 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004674 if (!isModule)
4675 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4676 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004677
Douglas Gregor851443c2011-08-12 01:39:19 +00004678 // Build a record containing all of the delegating constructors we still need
4679 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004680 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004681 if (!isModule)
4682 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004683
Douglas Gregor851443c2011-08-12 01:39:19 +00004684 // Write the set of weak, undeclared identifiers. We always write the
4685 // entire table, since later PCH files in a PCH chain are only interested in
4686 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004687 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004688 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4689 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4690 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4691 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4692 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4693 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4694 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004695 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004696
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004697 // Build a record containing all of the ext_vector declarations.
4698 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004699 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004700
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004701 // Build a record containing all of the VTable uses information.
4702 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004703 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004704 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4705 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4706 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4707 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4708 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004709 }
4710
Nico Weber72889432014-09-06 01:25:55 +00004711 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4712 RecordData UnusedLocalTypedefNameCandidates;
4713 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4714 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4715
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004716 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004717 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004718 for (const auto &I : SemaRef.PendingInstantiations) {
4719 AddDeclRef(I.first, PendingInstantiations);
4720 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004721 }
4722 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4723 "There are local ones at end of translation unit!");
4724
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004725 // Build a record containing some declaration references.
4726 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004727 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004728 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4729 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004730 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004731 }
4732
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004733 RecordData CUDASpecialDeclRefs;
4734 if (Context.getcudaConfigureCallDecl()) {
4735 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4736 }
4737
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004738 // Build a record containing all of the known namespaces.
4739 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004740 for (const auto &I : SemaRef.KnownNamespaces) {
4741 if (!I.second)
4742 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004743 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004744
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004745 // Build a record of all used, undefined objects that require definitions.
4746 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004747
4748 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004749 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004750 for (const auto &I : Undefined) {
4751 AddDeclRef(I.first, UndefinedButUsed);
4752 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004753 }
4754
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004755 // Build a record containing all delete-expressions that we would like to
4756 // analyze later in AST.
4757 RecordData DeleteExprsToAnalyze;
4758
4759 for (const auto &DeleteExprsInfo :
4760 SemaRef.getMismatchingDeleteExpressions()) {
4761 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4762 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4763 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4764 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4765 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4766 }
4767 }
4768
Douglas Gregor112b9072012-10-18 05:31:06 +00004769 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004770 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004771
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004772 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004773 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004774
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004775 // This is so that older clang versions, before the introduction
4776 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004777 {
4778 RecordData Record = {VERSION_MAJOR};
4779 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4780 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004781
Douglas Gregor851443c2011-08-12 01:39:19 +00004782 // Create a lexical update block containing all of the declarations in the
4783 // translation unit that do not come from other AST files.
4784 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004785 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4786 for (const auto *D : TU->noload_decls()) {
4787 if (!D->isFromASTFile()) {
4788 NewGlobalKindDeclPairs.push_back(D->getKind());
4789 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4790 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004791 }
4792
David Blaikieb44f0bf2017-01-04 22:36:43 +00004793 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004794 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4795 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004796 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004797 {
4798 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4799 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4800 bytes(NewGlobalKindDeclPairs));
4801 }
4802
Douglas Gregor851443c2011-08-12 01:39:19 +00004803 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004804 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004805 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4806 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004807 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004808 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004809 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004810
4811 // If we have any extern "C" names, write out a visible update for them.
4812 if (Context.ExternCContext)
4813 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004814
4815 // If the translation unit has an anonymous namespace, and we don't already
4816 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004817 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004818 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4819 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004820 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004821 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004822 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004823
Richard Smith5652c0f2014-03-21 01:48:23 +00004824 // Add update records for all mangling numbers and static local numbers.
4825 // These aren't really update records, but this is a convenient way of
4826 // tagging this rare extra data onto the declarations.
4827 for (const auto &Number : Context.MangleNumbers)
4828 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004829 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4830 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004831 for (const auto &Number : Context.StaticLocalNumbers)
4832 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004833 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4834 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004835
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004836 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004837 // an AST file, are registered for serialization. Likewise for template
4838 // specializations added to imported templates.
4839 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004840 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004841 }
4842
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004843 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004844 // serialization, if we're storing decls with identifiers.
4845 if (!WritingModule || !getLangOpts().CPlusPlus) {
4846 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004847 for (const auto &ID : PP.getIdentifierTable()) {
4848 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004849 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4850 IIs.push_back(II);
4851 }
4852 // Sort the identifiers to visit based on their name.
4853 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4854 for (const IdentifierInfo *II : IIs) {
4855 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4856 DEnd = SemaRef.IdResolver.end();
4857 D != DEnd; ++D) {
4858 GetDeclRef(*D);
4859 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004860 }
4861 }
4862
Manman Rena0f31a02016-04-29 19:04:05 +00004863 // For method pool in the module, if it contains an entry for a selector,
4864 // the entry should be complete, containing everything introduced by that
4865 // module and all modules it imports. It's possible that the entry is out of
4866 // date, so we need to pull in the new content here.
4867
4868 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4869 // safe, we copy all selectors out.
4870 llvm::SmallVector<Selector, 256> AllSelectors;
4871 for (auto &SelectorAndID : SelectorIDs)
4872 AllSelectors.push_back(SelectorAndID.first);
4873 for (auto &Selector : AllSelectors)
4874 SemaRef.updateOutOfDateSelector(Selector);
4875
Douglas Gregor5204bde2011-08-02 16:26:37 +00004876 // Form the record of special types.
4877 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004878 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004879 AddTypeRef(Context.getFILEType(), SpecialTypes);
4880 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4881 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4882 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4883 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004884 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004885 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004886
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004887 if (Chain) {
4888 // Write the mapping information describing our module dependencies and how
4889 // each of those modules were mapped into our own offset/ID space, so that
4890 // the reader can build the appropriate mapping to its own offset/ID space.
4891 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004892 // *(module-kind:i8
4893 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004894 // source-location-offset:i32
4895 // identifier-id:i32
4896 // preprocessed-entity-id:i32
4897 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004898 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004899 // selector-id:i32
4900 // declaration-id:i32
4901 // c++-base-specifiers-id:i32
4902 // type-id:i32)
4903 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004904 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4905 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4906 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004907 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004908 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004910 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004911 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004912 {
4913 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004914 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004915 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004916
Justin Bognere1c147c2014-03-28 22:03:19 +00004917 endian::Writer<little> LE(Out);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004918 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4919 StringRef Name =
4920 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4921 ? M.ModuleName
4922 : M.FileName;
4923 LE.write<uint16_t>(Name.size());
4924 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004925
Ben Langmuir785180e2014-10-20 16:27:30 +00004926 // Note: if a base ID was uint max, it would not be possible to load
4927 // another module after it or have more than one entity inside it.
4928 uint32_t None = std::numeric_limits<uint32_t>::max();
4929
4930 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4931 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4932 if (ShouldWrite)
4933 LE.write<uint32_t>(BaseID);
4934 else
4935 LE.write<uint32_t>(None);
4936 };
4937
Ben Langmuirfe971d92014-08-16 04:54:18 +00004938 // These values should be unique within a chain, since they will be read
4939 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004940 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4941 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4942 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4943 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4944 M.NumPreprocessedEntities);
4945 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4946 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4947 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4948 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004949 }
4950 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004951 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004952 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4953 Buffer.data(), Buffer.size());
4954 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004955
Richard Smithb9eab6d2014-03-20 19:44:17 +00004956 RecordData DeclUpdatesOffsetsRecord;
4957
Richard Smith59442b42014-03-20 20:07:19 +00004958 // Keep writing types, declarations, and declaration update records
4959 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004960 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4961 WriteTypeAbbrevs();
4962 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004963 do {
4964 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4965 while (!DeclTypesToEmit.empty()) {
4966 DeclOrType DOT = DeclTypesToEmit.front();
4967 DeclTypesToEmit.pop();
4968 if (DOT.isType())
4969 WriteType(DOT.getType());
4970 else
4971 WriteDecl(Context, DOT.getDecl());
4972 }
4973 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004974 Stream.ExitBlock();
4975
Richard Smithb9eab6d2014-03-20 19:44:17 +00004976 DoneWritingDeclsAndTypes = true;
4977
4978 // These things can only be done once we've written out decls and types.
4979 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004980 if (!DeclUpdatesOffsetsRecord.empty())
4981 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004982 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004983 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004984 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004985 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004986 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004987 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004988 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004989 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004990 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004991 WriteFPPragmaOptions(SemaRef.getFPOptions());
4992 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004993 WriteOpenCLExtensionTypes(SemaRef);
4994 WriteOpenCLExtensionDecls(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004995 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004996
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004997 // If we're emitting a module, write out the submodule information.
4998 if (WritingModule)
4999 WriteSubmodules(WritingModule);
5000
Douglas Gregor5204bde2011-08-02 16:26:37 +00005001 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5002
Douglas Gregord4df8652009-04-22 22:02:47 +00005003 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00005004 if (!EagerlyDeserializedDecls.empty())
5005 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00005006
David Blaikief63556d2017-04-12 20:58:33 +00005007 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00005008 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5009
Douglas Gregord4df8652009-04-22 22:02:47 +00005010 // Write the record containing tentative definitions.
5011 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005012 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00005013
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00005014 // Write the record containing unused file scoped decls.
5015 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005016 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005017
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00005018 // Write the record containing weak undeclared identifiers.
5019 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005020 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00005021 WeakUndeclaredIdentifiers);
5022
Douglas Gregor61cac2b2009-04-27 20:06:05 +00005023 // Write the record containing ext_vector type names.
5024 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005025 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00005026
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00005027 // Write the record containing VTable uses information.
5028 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005029 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00005030
Nico Weber72889432014-09-06 01:25:55 +00005031 // Write the record containing potentially unused local typedefs.
5032 if (!UnusedLocalTypedefNameCandidates.empty())
5033 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5034 UnusedLocalTypedefNameCandidates);
5035
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00005036 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00005037 if (!PendingInstantiations.empty())
5038 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00005039
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005040 // Write the record containing declaration references of Sema.
5041 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005042 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005043
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005044 // Write the record containing CUDA-specific declaration references.
5045 if (!CUDASpecialDeclRefs.empty())
5046 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00005047
5048 // Write the delegating constructors.
5049 if (!DelegatingCtorDecls.empty())
5050 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005051
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005052 // Write the known namespaces.
5053 if (!KnownNamespaces.empty())
5054 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00005055
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00005056 // Write the undefined internal functions and variables, and inline functions.
5057 if (!UndefinedButUsed.empty())
5058 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00005059
5060 if (!DeleteExprsToAnalyze.empty())
5061 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5062
Douglas Gregor851443c2011-08-12 01:39:19 +00005063 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00005064 for (auto *DC : UpdatedDeclContexts)
5065 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00005066
Douglas Gregor959bb062011-12-03 01:15:29 +00005067 if (!WritingModule) {
5068 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00005069 struct ModuleInfo {
5070 uint64_t ID;
5071 Module *M;
5072 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5073 };
Richard Smith56be7542014-03-21 00:33:59 +00005074 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00005075 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00005076 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00005077 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5078 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00005079 }
Richard Smith56be7542014-03-21 00:33:59 +00005080
5081 if (!Imports.empty()) {
5082 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5083 return A.ID < B.ID;
5084 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00005085 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5086 return A.ID == B.ID;
5087 };
Richard Smith56be7542014-03-21 00:33:59 +00005088
5089 // Sort and deduplicate module IDs.
5090 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00005091 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00005092 Imports.end());
5093
5094 RecordData ImportedModules;
5095 for (const auto &Import : Imports) {
5096 ImportedModules.push_back(Import.ID);
5097 // FIXME: If the module has macros imported then later has declarations
5098 // imported, this location won't be the right one as a location for the
5099 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00005100 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00005101 }
5102
Douglas Gregor959bb062011-12-03 01:15:29 +00005103 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5104 }
Douglas Gregor0a839132011-12-03 00:59:55 +00005105 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005106
Douglas Gregor404cdde2012-01-27 01:47:08 +00005107 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00005108 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00005109 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00005110 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00005111 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00005112 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00005113 WritePackPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00005114
Douglas Gregor08f01292009-04-17 22:13:46 +00005115 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00005116 RecordData::value_type Record[] = {
5117 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00005118 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00005119 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00005120
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005121 // Write the module file extension blocks.
5122 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00005123 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005124
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005125 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005126}
5127
Richard Smithb9eab6d2014-03-20 19:44:17 +00005128void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005129 if (DeclUpdates.empty())
5130 return;
5131
Richard Smith59442b42014-03-20 20:07:19 +00005132 DeclUpdateMap LocalUpdates;
5133 LocalUpdates.swap(DeclUpdates);
5134
Richard Smith6ef42932014-03-20 21:02:00 +00005135 for (auto &DeclUpdate : LocalUpdates) {
5136 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00005137
Richard Smithd28ac5b2014-03-22 23:33:22 +00005138 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00005139 RecordData RecordData;
5140 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00005141 for (auto &Update : DeclUpdate.second) {
5142 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5143
Richard Smith69c82bf2016-04-01 22:52:03 +00005144 // An updated body is emitted last, so that the reader doesn't need
5145 // to skip over the lazy body to reach statements for other records.
5146 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5147 HasUpdatedBody = true;
5148 else
5149 Record.push_back(Kind);
5150
Richard Smith6ef42932014-03-20 21:02:00 +00005151 switch (Kind) {
5152 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5153 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5154 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00005155 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00005156 Record.push_back(GetDeclRef(Update.getDecl()));
5157 break;
5158
Richard Smith4d235792014-08-07 18:53:08 +00005159 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00005160 break;
5161
Richard Smith891fc7f2017-12-05 01:31:47 +00005162 case UPD_CXX_POINT_OF_INSTANTIATION:
5163 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00005164 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00005165 break;
5166
5167 case UPD_CXX_ADDED_VAR_DEFINITION: {
5168 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00005169 Record.push_back(VD->isInline());
5170 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00005171 if (VD->getInit()) {
5172 Record.push_back(!VD->isInitKnownICE() ? 1
5173 : (VD->isInitICE() ? 3 : 2));
5174 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5175 } else {
5176 Record.push_back(0);
5177 }
Richard Smith4d235792014-08-07 18:53:08 +00005178 break;
Richard Smith05a21352017-06-22 22:18:46 +00005179 }
Richard Smith4d235792014-08-07 18:53:08 +00005180
John McCall32791cc2016-01-06 22:34:54 +00005181 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00005182 Record.AddStmt(const_cast<Expr *>(
5183 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00005184 break;
5185
Richard Smith4b054b22016-08-24 21:25:37 +00005186 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5187 Record.AddStmt(
5188 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5189 break;
5190
Richard Smithcd45dbc2014-04-19 03:48:30 +00005191 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5192 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00005193 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00005194 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00005195 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00005196 *Context, const_cast<CXXRecordDecl *>(RD)));
5197
5198 // This state is sometimes updated by template instantiation, when we
5199 // switch from the specialization referring to the template declaration
5200 // to it referring to the template definition.
5201 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5202 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005203 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005204 } else {
5205 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5206 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005207 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00005208
5209 // The instantiation might have been resolved to a partial
5210 // specialization. If so, record which one.
5211 auto From = Spec->getInstantiatedFrom();
5212 if (auto PartialSpec =
5213 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5214 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00005215 Record.AddDeclRef(PartialSpec);
5216 Record.AddTemplateArgumentList(
5217 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00005218 } else {
5219 Record.push_back(false);
5220 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005221 }
5222 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005223 Record.AddSourceLocation(RD->getLocation());
5224 Record.AddSourceLocation(RD->getLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00005225 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005226
5227 // Instantiation may change attributes; write them all out afresh.
5228 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00005229 if (D->hasAttrs())
5230 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005231
5232 // FIXME: Ensure we don't get here for explicit instantiations.
5233 break;
5234 }
5235
Richard Smithf8134002015-03-10 01:41:22 +00005236 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005237 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00005238 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00005239 break;
5240
Richard Smith564417a2014-03-20 21:47:22 +00005241 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5242 addExceptionSpec(
Richard Smith564417a2014-03-20 21:47:22 +00005243 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5244 Record);
5245 break;
5246
Richard Smith6ef42932014-03-20 21:02:00 +00005247 case UPD_CXX_DEDUCED_RETURN_TYPE:
5248 Record.push_back(GetOrCreateTypeID(Update.getType()));
5249 break;
5250
5251 case UPD_DECL_MARKED_USED:
5252 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00005253
5254 case UPD_MANGLING_NUMBER:
5255 case UPD_STATIC_LOCAL_NUMBER:
5256 Record.push_back(Update.getNumber());
5257 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005258
Alexey Bataev97720002014-11-11 04:05:39 +00005259 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005260 Record.AddSourceRange(
5261 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00005262 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005263
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005264 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5265 Record.AddSourceRange(
5266 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5267 break;
5268
Richard Smith65ebb4a2015-03-26 04:09:53 +00005269 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00005270 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005271 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005272
5273 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00005274 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00005275 break;
Richard Smith6ef42932014-03-20 21:02:00 +00005276 }
5277 }
5278
Richard Smithd28ac5b2014-03-22 23:33:22 +00005279 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005280 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005281 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005282 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005283 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005284 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005285 }
5286
Richard Smithcd45dbc2014-04-19 03:48:30 +00005287 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005288 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005289 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005290}
5291
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005292void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005293 uint32_t Raw = Loc.getRawEncoding();
5294 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005295}
5296
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005297void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005298 AddSourceLocation(Range.getBegin(), Record);
5299 AddSourceLocation(Range.getEnd(), Record);
5300}
5301
Richard Smithf144b542016-04-08 21:54:32 +00005302void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5303 Record->push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00005304 const uint64_t *Words = Value.getRawData();
Richard Smithf144b542016-04-08 21:54:32 +00005305 Record->append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005306}
5307
Richard Smithf144b542016-04-08 21:54:32 +00005308void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5309 Record->push_back(Value.isUnsigned());
5310 AddAPInt(Value);
Douglas Gregor1daeb692009-04-13 18:14:40 +00005311}
5312
Richard Smithf144b542016-04-08 21:54:32 +00005313void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5314 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005315}
5316
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005317void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005318 Record.push_back(getIdentifierRef(II));
5319}
5320
Sebastian Redl539c5062010-08-18 23:57:32 +00005321IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005322 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005323 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005324
Sebastian Redl539c5062010-08-18 23:57:32 +00005325 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005326 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005327 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005328 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005329}
5330
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005331MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005332 // Don't emit builtin macros like __LINE__ to the AST file unless they
5333 // have been redefined by the header (in which case they are not
5334 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005335 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005336 return 0;
5337
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005338 MacroID &ID = MacroIDs[MI];
5339 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005340 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005341 MacroInfoToEmitData Info = { Name, MI, ID };
5342 MacroInfosToEmit.push_back(Info);
5343 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005344 return ID;
5345}
5346
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005347MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005348 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005349 return 0;
5350
5351 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5352 return MacroIDs[MI];
5353}
5354
5355uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005356 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005357}
5358
Richard Smithe64e7452016-04-18 21:54:58 +00005359void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5360 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005361}
5362
Sebastian Redl539c5062010-08-18 23:57:32 +00005363SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005364 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005365 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005366 }
5367
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005368 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005369 if (SID == 0 && Chain) {
5370 // This might trigger a ReadSelector callback, which will set the ID for
5371 // this selector.
5372 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005373 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005374 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005375 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005376 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005377 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005378 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005379 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005380}
5381
Richard Smithe64e7452016-04-18 21:54:58 +00005382void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5383 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005384}
5385
Richard Smith290d8012016-04-06 17:06:00 +00005386void ASTRecordWriter::AddTemplateArgumentLocInfo(
5387 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005388 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005389 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005390 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005391 break;
5392 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005393 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005394 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005395 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005396 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5397 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005398 break;
5399 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005400 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5401 AddSourceLocation(Arg.getTemplateNameLoc());
5402 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005403 break;
John McCall0ad16662009-10-29 08:12:44 +00005404 case TemplateArgument::Null:
5405 case TemplateArgument::Integral:
5406 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005407 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005408 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005409 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005410 break;
5411 }
5412}
5413
Richard Smith290d8012016-04-06 17:06:00 +00005414void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5415 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005416
5417 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5418 bool InfoHasSameExpr
5419 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005420 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005421 if (InfoHasSameExpr)
5422 return; // Avoid storing the same expr twice.
5423 }
Richard Smith290d8012016-04-06 17:06:00 +00005424 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005425}
5426
Richard Smith290d8012016-04-06 17:06:00 +00005427void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005428 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005429 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005430 return;
5431 }
5432
Richard Smith290d8012016-04-06 17:06:00 +00005433 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005434}
5435
Richard Smith290d8012016-04-06 17:06:00 +00005436void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5437 AddTypeRef(TL.getType());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005438
Richard Smith290d8012016-04-06 17:06:00 +00005439 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005440 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005441 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005442}
5443
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005444void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005445 Record.push_back(GetOrCreateTypeID(T));
5446}
5447
Richard Smith2095ffe2015-03-16 20:11:03 +00005448TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005449 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005450 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5451 if (T.isNull())
5452 return TypeIdx();
5453 assert(!T.getLocalFastQualifiers());
5454
5455 TypeIdx &Idx = TypeIdxs[T];
5456 if (Idx.getIndex() == 0) {
5457 if (DoneWritingDeclsAndTypes) {
5458 assert(0 && "New type seen after serializing all the types to emit!");
5459 return TypeIdx();
5460 }
5461
5462 // We haven't seen this type before. Assign it a new ID and put it
5463 // into the queue of types to emit.
5464 Idx = TypeIdx(NextTypeID++);
5465 DeclTypesToEmit.push(T);
5466 }
5467 return Idx;
5468 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005469}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005470
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005471TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005472 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005473 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5474 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005475 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005476 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005477
Richard Smith2095ffe2015-03-16 20:11:03 +00005478 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5479 assert(I != TypeIdxs.end() && "Type not emitted!");
5480 return I->second;
5481 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005482}
5483
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005484void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005485 Record.push_back(GetDeclRef(D));
5486}
5487
Sebastian Redl539c5062010-08-18 23:57:32 +00005488DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005489 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005490
5491 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005492 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005493 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005494
5495 // If D comes from an AST file, its declaration ID is already known and
5496 // fixed.
5497 if (D->isFromASTFile())
5498 return D->getGlobalID();
5499
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005500 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005501 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005502 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005503 if (DoneWritingDeclsAndTypes) {
5504 assert(0 && "New decl seen after serializing all the decls to emit!");
5505 return 0;
5506 }
5507
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005508 // We haven't seen this declaration before. Give it a new ID and
5509 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005510 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005511 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005512 }
5513
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005514 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005515}
5516
Sebastian Redl539c5062010-08-18 23:57:32 +00005517DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005518 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005519 return 0;
5520
Douglas Gregorb3163e52012-01-05 22:33:30 +00005521 // If D comes from an AST file, its declaration ID is already known and
5522 // fixed.
5523 if (D->isFromASTFile())
5524 return D->getGlobalID();
5525
Douglas Gregore84a9da2009-04-20 20:36:09 +00005526 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5527 return DeclIDs[D];
5528}
5529
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005530void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005531 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005532 assert(D);
5533
5534 SourceLocation Loc = D->getLocation();
5535 if (Loc.isInvalid())
5536 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005537
5538 // We only keep track of the file-level declarations of each file.
5539 if (!D->getLexicalDeclContext()->isFileContext())
5540 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005541 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5542 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005543 // TemplateTemplateParmDecls that are part of an alias template, should not
5544 // have TU as lexical context.
5545 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005546 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005547
5548 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005549 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005550 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005551 FileID FID;
5552 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005553 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005554 if (FID.isInvalid())
5555 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005556 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005557
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005558 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005559 if (!Info)
5560 Info = new DeclIDInFileInfo();
5561
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005562 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005563 LocDeclIDsTy &Decls = Info->DeclIDs;
5564
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005565 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005566 Decls.push_back(LocDecl);
5567 return;
5568 }
5569
Benjamin Kramer45025c02013-08-24 13:22:59 +00005570 LocDeclIDsTy::iterator I =
5571 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005572
5573 Decls.insert(I, LocDecl);
5574}
5575
Richard Smithe64e7452016-04-18 21:54:58 +00005576void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
Chris Lattner258172e2009-04-27 07:35:58 +00005577 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Richard Smithe64e7452016-04-18 21:54:58 +00005578 Record->push_back(Name.getNameKind());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005579 switch (Name.getNameKind()) {
5580 case DeclarationName::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005581 AddIdentifierRef(Name.getAsIdentifierInfo());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005582 break;
5583
5584 case DeclarationName::ObjCZeroArgSelector:
5585 case DeclarationName::ObjCOneArgSelector:
5586 case DeclarationName::ObjCMultiArgSelector:
Richard Smithe64e7452016-04-18 21:54:58 +00005587 AddSelectorRef(Name.getObjCSelector());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005588 break;
5589
5590 case DeclarationName::CXXConstructorName:
5591 case DeclarationName::CXXDestructorName:
5592 case DeclarationName::CXXConversionFunctionName:
Richard Smithe64e7452016-04-18 21:54:58 +00005593 AddTypeRef(Name.getCXXNameType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005594 break;
5595
Richard Smith35845152017-02-07 01:37:30 +00005596 case DeclarationName::CXXDeductionGuideName:
5597 AddDeclRef(Name.getCXXDeductionGuideTemplate());
5598 break;
5599
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005600 case DeclarationName::CXXOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005601 Record->push_back(Name.getCXXOverloadedOperator());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005602 break;
5603
Alexis Hunt3d221f22009-11-29 07:34:05 +00005604 case DeclarationName::CXXLiteralOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005605 AddIdentifierRef(Name.getCXXLiteralIdentifier());
Alexis Hunt3d221f22009-11-29 07:34:05 +00005606 break;
5607
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005608 case DeclarationName::CXXUsingDirective:
5609 // No extra data to emit
5610 break;
5611 }
5612}
Chris Lattnerca025db2010-05-07 21:43:38 +00005613
Richard Smithd08aeb62014-08-28 01:33:39 +00005614unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5615 assert(needsAnonymousDeclarationNumber(D) &&
5616 "expected an anonymous declaration");
5617
5618 // Number the anonymous declarations within this context, if we've not
5619 // already done so.
5620 auto It = AnonymousDeclarationNumbers.find(D);
5621 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005622 auto *DC = D->getLexicalDeclContext();
5623 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5624 AnonymousDeclarationNumbers[ND] = Number;
5625 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005626
5627 It = AnonymousDeclarationNumbers.find(D);
5628 assert(It != AnonymousDeclarationNumbers.end() &&
5629 "declaration not found within its lexical context");
5630 }
5631
5632 return It->second;
5633}
5634
Richard Smith290d8012016-04-06 17:06:00 +00005635void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5636 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005637 switch (Name.getNameKind()) {
5638 case DeclarationName::CXXConstructorName:
5639 case DeclarationName::CXXDestructorName:
5640 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005641 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005642 break;
5643
5644 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005645 AddSourceLocation(SourceLocation::getFromRawEncoding(
5646 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005647 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005648 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005649 break;
5650
5651 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005652 AddSourceLocation(SourceLocation::getFromRawEncoding(
5653 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005654 break;
5655
5656 case DeclarationName::Identifier:
5657 case DeclarationName::ObjCZeroArgSelector:
5658 case DeclarationName::ObjCOneArgSelector:
5659 case DeclarationName::ObjCMultiArgSelector:
5660 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005661 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005662 break;
5663 }
5664}
5665
Richard Smith290d8012016-04-06 17:06:00 +00005666void ASTRecordWriter::AddDeclarationNameInfo(
5667 const DeclarationNameInfo &NameInfo) {
5668 AddDeclarationName(NameInfo.getName());
5669 AddSourceLocation(NameInfo.getLoc());
5670 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005671}
5672
Richard Smith290d8012016-04-06 17:06:00 +00005673void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5674 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5675 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005676 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005677 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005678}
5679
Richard Smithe64e7452016-04-18 21:54:58 +00005680void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005681 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005682 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005683 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005684
5685 // Push each of the NNS's onto a stack for serialization in reverse order.
5686 while (NNS) {
5687 NestedNames.push_back(NNS);
5688 NNS = NNS->getPrefix();
5689 }
5690
Richard Smithe64e7452016-04-18 21:54:58 +00005691 Record->push_back(NestedNames.size());
Chris Lattnerca025db2010-05-07 21:43:38 +00005692 while(!NestedNames.empty()) {
5693 NNS = NestedNames.pop_back_val();
5694 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
Richard Smithe64e7452016-04-18 21:54:58 +00005695 Record->push_back(Kind);
Chris Lattnerca025db2010-05-07 21:43:38 +00005696 switch (Kind) {
5697 case NestedNameSpecifier::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005698 AddIdentifierRef(NNS->getAsIdentifier());
Chris Lattnerca025db2010-05-07 21:43:38 +00005699 break;
5700
5701 case NestedNameSpecifier::Namespace:
Richard Smithe64e7452016-04-18 21:54:58 +00005702 AddDeclRef(NNS->getAsNamespace());
Chris Lattnerca025db2010-05-07 21:43:38 +00005703 break;
5704
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005705 case NestedNameSpecifier::NamespaceAlias:
Richard Smithe64e7452016-04-18 21:54:58 +00005706 AddDeclRef(NNS->getAsNamespaceAlias());
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005707 break;
5708
Chris Lattnerca025db2010-05-07 21:43:38 +00005709 case NestedNameSpecifier::TypeSpec:
5710 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smithe64e7452016-04-18 21:54:58 +00005711 AddTypeRef(QualType(NNS->getAsType(), 0));
5712 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Chris Lattnerca025db2010-05-07 21:43:38 +00005713 break;
5714
5715 case NestedNameSpecifier::Global:
5716 // Don't need to write an associated value.
5717 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005718
5719 case NestedNameSpecifier::Super:
Richard Smithe64e7452016-04-18 21:54:58 +00005720 AddDeclRef(NNS->getAsRecordDecl());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005721 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005722 }
5723 }
5724}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005725
Richard Smith290d8012016-04-06 17:06:00 +00005726void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005727 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005728 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005729 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005730
5731 // Push each of the nested-name-specifiers's onto a stack for
5732 // serialization in reverse order.
5733 while (NNS) {
5734 NestedNames.push_back(NNS);
5735 NNS = NNS.getPrefix();
5736 }
5737
Richard Smith290d8012016-04-06 17:06:00 +00005738 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005739 while(!NestedNames.empty()) {
5740 NNS = NestedNames.pop_back_val();
5741 NestedNameSpecifier::SpecifierKind Kind
5742 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005743 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005744 switch (Kind) {
5745 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005746 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5747 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005748 break;
5749
5750 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005751 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5752 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005753 break;
5754
5755 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005756 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5757 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005758 break;
5759
5760 case NestedNameSpecifier::TypeSpec:
5761 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005762 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5763 AddTypeLoc(NNS.getTypeLoc());
5764 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005765 break;
5766
5767 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005768 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005769 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005770
5771 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005772 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5773 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005774 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005775 }
5776 }
5777}
5778
Richard Smith290d8012016-04-06 17:06:00 +00005779void ASTRecordWriter::AddTemplateName(TemplateName Name) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005780 TemplateName::NameKind Kind = Name.getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005781 Record->push_back(Kind);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005782 switch (Kind) {
5783 case TemplateName::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005784 AddDeclRef(Name.getAsTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005785 break;
5786
5787 case TemplateName::OverloadedTemplate: {
5788 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
Richard Smith290d8012016-04-06 17:06:00 +00005789 Record->push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005790 for (const auto &I : *OvT)
Richard Smith290d8012016-04-06 17:06:00 +00005791 AddDeclRef(I);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005792 break;
5793 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005794
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005795 case TemplateName::QualifiedTemplate: {
5796 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005797 AddNestedNameSpecifier(QualT->getQualifier());
5798 Record->push_back(QualT->hasTemplateKeyword());
5799 AddDeclRef(QualT->getTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005800 break;
5801 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005802
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005803 case TemplateName::DependentTemplate: {
5804 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005805 AddNestedNameSpecifier(DepT->getQualifier());
5806 Record->push_back(DepT->isIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005807 if (DepT->isIdentifier())
Richard Smith290d8012016-04-06 17:06:00 +00005808 AddIdentifierRef(DepT->getIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005809 else
Richard Smith290d8012016-04-06 17:06:00 +00005810 Record->push_back(DepT->getOperator());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005811 break;
5812 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005813
5814 case TemplateName::SubstTemplateTemplateParm: {
5815 SubstTemplateTemplateParmStorage *subst
5816 = Name.getAsSubstTemplateTemplateParm();
Richard Smith290d8012016-04-06 17:06:00 +00005817 AddDeclRef(subst->getParameter());
5818 AddTemplateName(subst->getReplacement());
John McCalld9dfe3a2011-06-30 08:33:18 +00005819 break;
5820 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005821
5822 case TemplateName::SubstTemplateTemplateParmPack: {
5823 SubstTemplateTemplateParmPackStorage *SubstPack
5824 = Name.getAsSubstTemplateTemplateParmPack();
Richard Smith290d8012016-04-06 17:06:00 +00005825 AddDeclRef(SubstPack->getParameterPack());
5826 AddTemplateArgument(SubstPack->getArgumentPack());
Douglas Gregor5590be02011-01-15 06:45:20 +00005827 break;
5828 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005829 }
5830}
5831
Richard Smith290d8012016-04-06 17:06:00 +00005832void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5833 Record->push_back(Arg.getKind());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005834 switch (Arg.getKind()) {
5835 case TemplateArgument::Null:
5836 break;
5837 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005838 AddTypeRef(Arg.getAsType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005839 break;
5840 case TemplateArgument::Declaration:
Richard Smith290d8012016-04-06 17:06:00 +00005841 AddDeclRef(Arg.getAsDecl());
5842 AddTypeRef(Arg.getParamTypeForDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00005843 break;
5844 case TemplateArgument::NullPtr:
Richard Smith290d8012016-04-06 17:06:00 +00005845 AddTypeRef(Arg.getNullPtrType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005846 break;
5847 case TemplateArgument::Integral:
Richard Smith290d8012016-04-06 17:06:00 +00005848 AddAPSInt(Arg.getAsIntegral());
5849 AddTypeRef(Arg.getIntegralType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005850 break;
5851 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005852 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
Douglas Gregore1d60df2011-01-14 23:41:42 +00005853 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005854 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005855 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
David Blaikie05785d12013-02-20 22:23:23 +00005856 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Richard Smith290d8012016-04-06 17:06:00 +00005857 Record->push_back(*NumExpansions + 1);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005858 else
Richard Smith290d8012016-04-06 17:06:00 +00005859 Record->push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005860 break;
5861 case TemplateArgument::Expression:
5862 AddStmt(Arg.getAsExpr());
5863 break;
5864 case TemplateArgument::Pack:
Richard Smith290d8012016-04-06 17:06:00 +00005865 Record->push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005866 for (const auto &P : Arg.pack_elements())
Richard Smith290d8012016-04-06 17:06:00 +00005867 AddTemplateArgument(P);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005868 break;
5869 }
5870}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005871
Richard Smithe64e7452016-04-18 21:54:58 +00005872void ASTRecordWriter::AddTemplateParameterList(
5873 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005874 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005875 AddSourceLocation(TemplateParams->getTemplateLoc());
5876 AddSourceLocation(TemplateParams->getLAngleLoc());
5877 AddSourceLocation(TemplateParams->getRAngleLoc());
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00005878 // TODO: Concepts
Richard Smithe64e7452016-04-18 21:54:58 +00005879 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005880 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005881 AddDeclRef(P);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005882}
5883
5884/// \brief Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005885void ASTRecordWriter::AddTemplateArgumentList(
5886 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005887 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005888 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005889 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005890 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005891}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005892
Richard Smith290d8012016-04-06 17:06:00 +00005893void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5894 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005895 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005896 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5897 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5898 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005899 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005900 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005901 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005902}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005903
Richard Smithe64e7452016-04-18 21:54:58 +00005904void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5905 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005906 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005907 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005908 AddDeclRef(I.getDecl());
5909 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005910 }
5911}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005912
Richard Smith290d8012016-04-06 17:06:00 +00005913// FIXME: Move this out of the main ASTRecordWriter interface.
5914void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5915 Record->push_back(Base.isVirtual());
5916 Record->push_back(Base.isBaseOfClass());
5917 Record->push_back(Base.getAccessSpecifierAsWritten());
5918 Record->push_back(Base.getInheritConstructors());
5919 AddTypeSourceInfo(Base.getTypeSourceInfo());
5920 AddSourceRange(Base.getSourceRange());
Douglas Gregor752a5952011-01-03 22:36:02 +00005921 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005922 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005923}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005924
Richard Smith645d2cf2016-04-14 00:29:55 +00005925static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5926 ArrayRef<CXXBaseSpecifier> Bases) {
5927 ASTWriter::RecordData Record;
5928 ASTRecordWriter Writer(W, Record);
5929 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005930
Richard Smith645d2cf2016-04-14 00:29:55 +00005931 for (auto &Base : Bases)
5932 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005933
Richard Smith645d2cf2016-04-14 00:29:55 +00005934 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005935}
5936
Richard Smith290d8012016-04-06 17:06:00 +00005937// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005938void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5939 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5940}
5941
Richard Smithaa165cf2016-04-13 21:57:08 +00005942static uint64_t
5943EmitCXXCtorInitializers(ASTWriter &W,
5944 ArrayRef<CXXCtorInitializer *> CtorInits) {
5945 ASTWriter::RecordData Record;
5946 ASTRecordWriter Writer(W, Record);
5947 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005948
Richard Smithaa165cf2016-04-13 21:57:08 +00005949 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005950 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005951 Writer.push_back(CTOR_INITIALIZER_BASE);
5952 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5953 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005954 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005955 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5956 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005957 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005958 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5959 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005960 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005961 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5962 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005963 }
Francois Pichetd583da02010-12-04 09:14:42 +00005964
Richard Smithaa165cf2016-04-13 21:57:08 +00005965 Writer.AddSourceLocation(Init->getMemberLocation());
5966 Writer.AddStmt(Init->getInit());
5967 Writer.AddSourceLocation(Init->getLParenLoc());
5968 Writer.AddSourceLocation(Init->getRParenLoc());
5969 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005970 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005971 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005972 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005973
5974 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005975}
5976
Richard Smithaa165cf2016-04-13 21:57:08 +00005977// FIXME: Move this out of the main ASTRecordWriter interface.
5978void ASTRecordWriter::AddCXXCtorInitializers(
5979 ArrayRef<CXXCtorInitializer *> CtorInits) {
5980 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005981}
5982
Richard Smith290d8012016-04-06 17:06:00 +00005983void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005984 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005985 Record->push_back(Data.IsLambda);
5986 Record->push_back(Data.UserDeclaredConstructor);
5987 Record->push_back(Data.UserDeclaredSpecialMembers);
5988 Record->push_back(Data.Aggregate);
5989 Record->push_back(Data.PlainOldData);
5990 Record->push_back(Data.Empty);
5991 Record->push_back(Data.Polymorphic);
5992 Record->push_back(Data.Abstract);
5993 Record->push_back(Data.IsStandardLayout);
5994 Record->push_back(Data.HasNoNonEmptyBases);
5995 Record->push_back(Data.HasPrivateFields);
5996 Record->push_back(Data.HasProtectedFields);
5997 Record->push_back(Data.HasPublicFields);
5998 Record->push_back(Data.HasMutableFields);
5999 Record->push_back(Data.HasVariantMembers);
6000 Record->push_back(Data.HasOnlyCMembers);
6001 Record->push_back(Data.HasInClassInitializer);
6002 Record->push_back(Data.HasUninitializedReferenceMember);
6003 Record->push_back(Data.HasUninitializedFields);
Richard Smith12e79312016-05-13 06:47:56 +00006004 Record->push_back(Data.HasInheritedConstructor);
6005 Record->push_back(Data.HasInheritedAssignment);
Richard Smith96cd6712017-08-16 01:49:53 +00006006 Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
Richard Smith290d8012016-04-06 17:06:00 +00006007 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
6008 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
6009 Record->push_back(Data.NeedOverloadResolutionForDestructor);
Richard Smith96cd6712017-08-16 01:49:53 +00006010 Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
Richard Smith290d8012016-04-06 17:06:00 +00006011 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
6012 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
6013 Record->push_back(Data.DefaultedDestructorIsDeleted);
6014 Record->push_back(Data.HasTrivialSpecialMembers);
Akira Hatanaka02914dc2018-02-05 20:23:22 +00006015 Record->push_back(Data.HasTrivialSpecialMembersForCall);
Richard Smith290d8012016-04-06 17:06:00 +00006016 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
Akira Hatanaka02914dc2018-02-05 20:23:22 +00006017 Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall);
Richard Smith290d8012016-04-06 17:06:00 +00006018 Record->push_back(Data.HasIrrelevantDestructor);
6019 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
6020 Record->push_back(Data.HasDefaultedDefaultConstructor);
Richard Smith96cd6712017-08-16 01:49:53 +00006021 Record->push_back(Data.CanPassInRegisters);
Richard Smith290d8012016-04-06 17:06:00 +00006022 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
6023 Record->push_back(Data.HasConstexprDefaultConstructor);
6024 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
6025 Record->push_back(Data.ComputedVisibleConversions);
6026 Record->push_back(Data.UserProvidedDefaultConstructor);
6027 Record->push_back(Data.DeclaredSpecialMembers);
Richard Smithdf054d32017-02-25 23:53:05 +00006028 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
6029 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
Richard Smith290d8012016-04-06 17:06:00 +00006030 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
6031 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
6032 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Trieufd1acbb2017-04-11 21:31:00 +00006033
6034 // getODRHash will compute the ODRHash if it has not been previously computed.
6035 Record->push_back(D->getODRHash());
David Blaikief63556d2017-04-12 20:58:33 +00006036 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
6037 Writer->WritingModule && !D->isDependentType();
6038 Record->push_back(ModulesDebugInfo);
6039 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00006040 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6041
Richard Smith561fb152012-02-25 07:33:38 +00006042 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006043
Richard Smith290d8012016-04-06 17:06:00 +00006044 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00006045 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00006046 AddCXXBaseSpecifiers(Data.bases());
6047
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006048 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00006049 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00006050 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00006051 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006052
Richard Smith290d8012016-04-06 17:06:00 +00006053 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6054 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006055 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00006056 AddDeclRef(D->getFirstFriend());
Douglas Gregor99ae8062012-02-14 17:54:36 +00006057
6058 // Add lambda-specific data.
6059 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00006060 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00006061 Record->push_back(Lambda.Dependent);
6062 Record->push_back(Lambda.IsGenericLambda);
6063 Record->push_back(Lambda.CaptureDefault);
6064 Record->push_back(Lambda.NumCaptures);
6065 Record->push_back(Lambda.NumExplicitCaptures);
6066 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00006067 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00006068 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00006069 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00006070 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00006071 AddSourceLocation(Capture.getLocation());
6072 Record->push_back(Capture.isImplicit());
6073 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00006074 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00006075 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00006076 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00006077 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00006078 break;
6079 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00006080 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00006081 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00006082 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00006083 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00006084 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00006085 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00006086 break;
6087 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00006088 }
6089 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006090}
6091
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006092void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00006093 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00006094 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00006095 assert(FirstDeclID == NextDeclID &&
6096 FirstTypeID == NextTypeID &&
6097 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006098 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00006099 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00006100 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00006101 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00006102
Sebastian Redl07a89a82010-07-30 00:29:29 +00006103 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006104
Richard Smith7f330cd2015-03-18 01:42:29 +00006105 // Note, this will get called multiple times, once one the reader starts up
6106 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00006107 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6108 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6109 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006110 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00006111 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00006112 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006113 NextDeclID = FirstDeclID;
6114 NextTypeID = FirstTypeID;
6115 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006116 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006117 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00006118 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00006119}
6120
Sebastian Redl539c5062010-08-18 23:57:32 +00006121void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006122 // Always keep the highest ID. See \p TypeRead() for more information.
6123 IdentID &StoredID = IdentifierIDs[II];
6124 if (ID > StoredID)
6125 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00006126}
6127
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006128void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006129 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006130 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006131 if (ID > StoredID)
6132 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006133}
6134
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00006135void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00006136 // Always take the highest-numbered type index. This copes with an interesting
6137 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00006138 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00006139 // keep the higher-numbered entry so that we can properly write it out to
6140 // the AST file.
6141 TypeIdx &StoredIdx = TypeIdxs[T];
6142 if (Idx.getIndex() >= StoredIdx.getIndex())
6143 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00006144}
6145
Sebastian Redl539c5062010-08-18 23:57:32 +00006146void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006147 // Always keep the highest ID. See \p TypeRead() for more information.
6148 SelectorID &StoredID = SelectorIDs[S];
6149 if (ID > StoredID)
6150 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00006151}
Douglas Gregor91096292010-10-02 19:29:26 +00006152
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00006153void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00006154 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00006155 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00006156 MacroDefinitions[MD] = ID;
6157}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006158
Douglas Gregore37a85a2011-12-02 17:30:13 +00006159void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6160 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
6161 SubmoduleIDs[Mod] = ID;
6162}
6163
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006164void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006165 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00006166 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006167 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00006168 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006169 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00006170 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006171 // A forward reference was mutated into a definition. Rewrite it.
6172 // FIXME: This happens during template instantiation, should we
6173 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00006174 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6175 "completed a tag from another module but not by instantiation?");
6176 DeclUpdates[RD].push_back(
6177 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006178 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006179 }
6180}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006181
Richard Smithf983f7f2015-10-13 00:23:25 +00006182static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6183 if (D->isFromASTFile())
6184 return true;
6185
Richard Smithf983f7f2015-10-13 00:23:25 +00006186 // The predefined __va_list_tag struct is imported if we imported any decls.
6187 // FIXME: This is a gross hack.
6188 return D == D->getASTContext().getVaListTagDecl();
6189}
6190
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006191void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006192 if (Chain && Chain->isProcessingUpdateRecords()) return;
6193 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00006194 "Should not add lookup results to non-lookup contexts!");
6195
Vassil Vassilev632eac32016-03-16 11:17:04 +00006196 // TU is handled elsewhere.
6197 if (isa<TranslationUnitDecl>(DC))
6198 return;
6199
6200 // Namespaces are handled elsewhere, except for template instantiations of
6201 // FunctionTemplateDecls in namespaces. We are interested in cases where the
6202 // local instantiations are added to an imported context. Only happens when
6203 // adding ADL lookup candidates, for example templated friends.
6204 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6205 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006206 return;
6207
Richard Smithf983f7f2015-10-13 00:23:25 +00006208 // We're only interested in cases where a local declaration is added to an
6209 // imported context.
6210 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6211 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006212
Richard Smith0f4e2c42015-08-06 04:23:48 +00006213 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00006214 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00006215 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00006216 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6217 // We're adding a visible declaration to a predefined decl context. Ensure
6218 // that we write out all of its lookup results so we don't get a nasty
6219 // surprise when we try to emit its lookup table.
6220 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00006221 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00006222 }
Richard Smithc26d9742016-10-06 20:30:51 +00006223 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006224}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006225
6226void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006227 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006228 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00006229
6230 // We're only interested in cases where a local declaration is added to an
6231 // imported context.
6232 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6233 return;
6234
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006235 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00006236 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006237
6238 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00006239 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00006240 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00006241 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006242}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00006243
Richard Smith564417a2014-03-20 21:47:22 +00006244void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006245 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00006246 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6247 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006248 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006249 // If we don't already know the exception specification for this redecl
6250 // chain, add an update record for it.
6251 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6252 ->getType()
6253 ->castAs<FunctionProtoType>()
6254 ->getExceptionSpecType()))
6255 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6256 });
Richard Smith564417a2014-03-20 21:47:22 +00006257}
6258
Richard Smith1fa5d642013-05-11 05:45:24 +00006259void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006260 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00006261 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00006262 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006263 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006264 DeclUpdates[D].push_back(
6265 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6266 });
Richard Smith1fa5d642013-05-11 05:45:24 +00006267}
6268
Richard Smithf8134002015-03-10 01:41:22 +00006269void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00006270 const FunctionDecl *Delete,
6271 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006272 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00006273 assert(!WritingAST && "Already writing the AST!");
6274 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00006275 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006276 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006277 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6278 });
Richard Smithf8134002015-03-10 01:41:22 +00006279}
6280
Sebastian Redlab238a72011-04-24 16:28:06 +00006281void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006282 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006283 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006284 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00006285 return; // Declaration not imported from PCH.
6286
Richard Smith4d235792014-08-07 18:53:08 +00006287 // Implicit function decl from a PCH was defined.
6288 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00006289}
6290
Richard Smith891fc7f2017-12-05 01:31:47 +00006291void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6292 if (Chain && Chain->isProcessingUpdateRecords()) return;
6293 assert(!WritingAST && "Already writing the AST!");
6294 if (!D->isFromASTFile())
6295 return;
6296
6297 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6298}
6299
Richard Smithd28ac5b2014-03-22 23:33:22 +00006300void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006301 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00006302 assert(!WritingAST && "Already writing the AST!");
6303 if (!D->isFromASTFile())
6304 return;
6305
Richard Smith9e2341d2015-03-23 03:25:59 +00006306 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00006307}
6308
Richard Smith891fc7f2017-12-05 01:31:47 +00006309void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006310 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006311 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006312 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00006313 return;
6314
6315 // Since the actual instantiation is delayed, this really means that we need
6316 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00006317 SourceLocation POI;
6318 if (auto *VD = dyn_cast<VarDecl>(D))
6319 POI = VD->getPointOfInstantiation();
6320 else
6321 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6322 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00006323}
6324
John McCall32791cc2016-01-06 22:34:54 +00006325void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006326 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00006327 assert(!WritingAST && "Already writing the AST!");
6328 if (!D->isFromASTFile())
6329 return;
6330
6331 DeclUpdates[D].push_back(
6332 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6333}
6334
Richard Smith4b054b22016-08-24 21:25:37 +00006335void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6336 assert(!WritingAST && "Already writing the AST!");
6337 if (!D->isFromASTFile())
6338 return;
6339
6340 DeclUpdates[D].push_back(
6341 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6342}
6343
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006344void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6345 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006346 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006347 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006348 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006349 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00006350
6351 assert(IFD->getDefinition() && "Category on a class without a definition?");
6352 ObjCClassesWithCategories.insert(
6353 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006354}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00006355
Eli Friedman276dd182013-09-05 00:02:25 +00006356void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006357 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00006358 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00006359
6360 // If there is *any* declaration of the entity that's not from an AST file,
6361 // we can skip writing the update record. We make sure that isUsed() triggers
6362 // completion of the redeclaration chain of the entity.
6363 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6364 if (IsLocalDecl(Prev))
6365 return;
Eli Friedman276dd182013-09-05 00:02:25 +00006366
Aaron Ballman4f45b712014-03-21 15:22:56 +00006367 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00006368}
Alexey Bataev97720002014-11-11 04:05:39 +00006369
6370void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006371 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00006372 assert(!WritingAST && "Already writing the AST!");
6373 if (!D->isFromASTFile())
6374 return;
6375
6376 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6377}
Richard Smith65ebb4a2015-03-26 04:09:53 +00006378
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006379void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6380 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006381 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006382 assert(!WritingAST && "Already writing the AST!");
6383 if (!D->isFromASTFile())
6384 return;
6385
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006386 DeclUpdates[D].push_back(
6387 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006388}
6389
Richard Smith4caa4492015-05-15 02:34:32 +00006390void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006391 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00006392 assert(!WritingAST && "Already writing the AST!");
6393 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00006394 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00006395}
Alex Denisovfde64952015-06-26 05:28:36 +00006396
6397void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6398 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006399 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00006400 assert(!WritingAST && "Already writing the AST!");
6401 if (!Record->isFromASTFile())
6402 return;
6403 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6404}
Richard Smithc26d9742016-10-06 20:30:51 +00006405
6406void ASTWriter::AddedCXXTemplateSpecialization(
6407 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6408 assert(!WritingAST && "Already writing the AST!");
6409
6410 if (!TD->getFirstDecl()->isFromASTFile())
6411 return;
6412 if (Chain && Chain->isProcessingUpdateRecords())
6413 return;
6414
6415 DeclsToEmitEvenIfUnreferenced.push_back(D);
6416}
6417
6418void ASTWriter::AddedCXXTemplateSpecialization(
6419 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6420 assert(!WritingAST && "Already writing the AST!");
6421
6422 if (!TD->getFirstDecl()->isFromASTFile())
6423 return;
6424 if (Chain && Chain->isProcessingUpdateRecords())
6425 return;
6426
6427 DeclsToEmitEvenIfUnreferenced.push_back(D);
6428}
6429
6430void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6431 const FunctionDecl *D) {
6432 assert(!WritingAST && "Already writing the AST!");
6433
6434 if (!TD->getFirstDecl()->isFromASTFile())
6435 return;
6436 if (Chain && Chain->isProcessingUpdateRecords())
6437 return;
6438
6439 DeclsToEmitEvenIfUnreferenced.push_back(D);
6440}