blob: 8c39309d263e75d03163d8fc90d0697e2f5f3bd9 [file] [log] [blame]
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregoref84c4b2009-04-09 22:27:44 +00006//
7//===----------------------------------------------------------------------===//
8//
Sebastian Redl55c0ad52010-08-18 23:56:21 +00009// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000010//
11//===----------------------------------------------------------------------===//
12
Sebastian Redl1914c6f2010-08-18 23:56:37 +000013#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000014#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000015#include "ASTReaderInternals.h"
16#include "MultiOnDiskHashTable.h"
John McCalld505e572019-12-13 21:54:44 -050017#include "clang/AST/AbstractTypeWriter.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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/Module.h"
46#include "clang/Basic/ObjCRuntime.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000047#include "clang/Basic/OpenCLOptions.h"
48#include "clang/Basic/SourceLocation.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000049#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000050#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000051#include "clang/Basic/Specifiers.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000052#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000053#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000054#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000055#include "clang/Lex/HeaderSearch.h"
56#include "clang/Lex/HeaderSearchOptions.h"
57#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000058#include "clang/Lex/ModuleMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000059#include "clang/Lex/PreprocessingRecord.h"
60#include "clang/Lex/Preprocessor.h"
61#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Lex/Token.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000063#include "clang/Sema/IdentifierResolver.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000064#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000065#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include "clang/Sema/Weak.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000067#include "clang/Serialization/ASTReader.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000068#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080069#include "clang/Serialization/ModuleFile.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000070#include "clang/Serialization/ModuleFileExtension.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000071#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000072#include "llvm/ADT/APFloat.h"
73#include "llvm/ADT/APInt.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000074#include "llvm/ADT/APSInt.h"
75#include "llvm/ADT/ArrayRef.h"
76#include "llvm/ADT/DenseMap.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000077#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000078#include "llvm/ADT/Optional.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000079#include "llvm/ADT/PointerIntPair.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000080#include "llvm/ADT/STLExtras.h"
Ilya Biryukov45643102018-07-09 11:33:23 +000081#include "llvm/ADT/ScopeExit.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"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000085#include "llvm/ADT/StringMap.h"
86#include "llvm/ADT/StringRef.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +000087#include "llvm/Bitstream/BitCodes.h"
88#include "llvm/Bitstream/BitstreamWriter.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000089#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +000090#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000091#include "llvm/Support/DJB.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"
Pavel Labathd8c62902018-06-11 10:28:04 +0000100#include "llvm/Support/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000101#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000102#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000103#include <cassert>
104#include <cstdint>
105#include <cstdlib>
106#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000107#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000108#include <deque>
109#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000110#include <memory>
111#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000112#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000113#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000114#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000115
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000116using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000117using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000118
Sebastian Redl3df5a082010-07-30 17:03:48 +0000119template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000120static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000121 if (v.empty()) return StringRef();
122 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000123 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000124}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000125
126template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000127static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000128 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000129 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000130}
131
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000132//===----------------------------------------------------------------------===//
133// Type serialization
134//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000135
John McCalld505e572019-12-13 21:54:44 -0500136static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
137 switch (id) {
138#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
139 case Type::CLASS_ID: return TYPE_##CODE_ID;
140#include "clang/Serialization/TypeBitCodes.def"
141 case Type::Builtin:
142 llvm_unreachable("shouldn't be serializing a builtin type this way");
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000143 }
John McCalld505e572019-12-13 21:54:44 -0500144 llvm_unreachable("bad type kind");
Xiuli Pan9c14e282016-01-09 12:53:17 +0000145}
146
John McCall8f115c62009-10-16 21:56:05 +0000147namespace {
148
John McCalld505e572019-12-13 21:54:44 -0500149class ASTTypeWriter {
150 ASTWriter &Writer;
151 ASTWriter::RecordData Record;
152 ASTRecordWriter BasicWriter;
153
154public:
155 ASTTypeWriter(ASTWriter &Writer)
156 : Writer(Writer), BasicWriter(Writer, Record) {}
157
158 uint64_t write(QualType T) {
159 if (T.hasLocalNonFastQualifiers()) {
160 Qualifiers Qs = T.getLocalQualifiers();
161 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
162 BasicWriter.writeQualifiers(Qs);
163 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
164 }
165
166 const Type *typePtr = T.getTypePtr();
167 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
168 atw.write(typePtr);
169 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
170 /*abbrev*/ 0);
171 }
172};
173
John McCall8f115c62009-10-16 21:56:05 +0000174class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000175 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000176
177public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000178 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000179
John McCall17001972009-10-18 01:05:36 +0000180#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000181#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000182 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000183#include "clang/AST/TypeLocNodes.def"
184
John McCall17001972009-10-18 01:05:36 +0000185 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
186 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000187};
188
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000189} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000190
John McCall17001972009-10-18 01:05:36 +0000191void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
192 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000193}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000194
John McCall17001972009-10-18 01:05:36 +0000195void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000196 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000197 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000198 Record.push_back(TL.getWrittenTypeSpec());
199 Record.push_back(TL.getWrittenSignSpec());
200 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000201 Record.push_back(TL.hasModeAttr());
202 }
John McCall8f115c62009-10-16 21:56:05 +0000203}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000204
John McCall17001972009-10-18 01:05:36 +0000205void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000206 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000207}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000208
John McCall17001972009-10-18 01:05:36 +0000209void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000210 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000211}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000212
Reid Kleckner8a365022013-06-24 17:51:48 +0000213void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
214 // nothing to do
215}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000216
Reid Kleckner0503a872013-12-05 01:23:43 +0000217void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
218 // nothing to do
219}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000220
John McCall17001972009-10-18 01:05:36 +0000221void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000222 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000223}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000224
John McCall17001972009-10-18 01:05:36 +0000225void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000226 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000227}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000228
John McCall17001972009-10-18 01:05:36 +0000229void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000230 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000231}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000232
John McCall17001972009-10-18 01:05:36 +0000233void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000234 Record.AddSourceLocation(TL.getStarLoc());
235 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000236}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000237
John McCall17001972009-10-18 01:05:36 +0000238void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000239 Record.AddSourceLocation(TL.getLBracketLoc());
240 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000241 Record.push_back(TL.getSizeExpr() ? 1 : 0);
242 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000243 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000244}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000245
John McCall17001972009-10-18 01:05:36 +0000246void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
247 VisitArrayTypeLoc(TL);
248}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000249
John McCall17001972009-10-18 01:05:36 +0000250void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
251 VisitArrayTypeLoc(TL);
252}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000253
John McCall17001972009-10-18 01:05:36 +0000254void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
255 VisitArrayTypeLoc(TL);
256}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000257
John McCall17001972009-10-18 01:05:36 +0000258void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
259 DependentSizedArrayTypeLoc TL) {
260 VisitArrayTypeLoc(TL);
261}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000262
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000263void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
264 DependentAddressSpaceTypeLoc TL) {
265 Record.AddSourceLocation(TL.getAttrNameLoc());
266 SourceRange range = TL.getAttrOperandParensRange();
267 Record.AddSourceLocation(range.getBegin());
268 Record.AddSourceLocation(range.getEnd());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000269 Record.AddStmt(TL.getAttrExprOperand());
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000270}
271
John McCall17001972009-10-18 01:05:36 +0000272void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
273 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000274 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000275}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000276
John McCall17001972009-10-18 01:05:36 +0000277void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000278 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000279}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000280
Erich Keanef702b022018-07-13 19:46:04 +0000281void TypeLocWriter::VisitDependentVectorTypeLoc(
282 DependentVectorTypeLoc TL) {
283 Record.AddSourceLocation(TL.getNameLoc());
284}
285
John McCall17001972009-10-18 01:05:36 +0000286void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000287 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000288}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000289
John McCall17001972009-10-18 01:05:36 +0000290void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000291 Record.AddSourceLocation(TL.getLocalRangeBegin());
292 Record.AddSourceLocation(TL.getLParenLoc());
293 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000294 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000295 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000296 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000297 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000298}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000299
John McCall17001972009-10-18 01:05:36 +0000300void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
301 VisitFunctionTypeLoc(TL);
302}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000303
John McCall17001972009-10-18 01:05:36 +0000304void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
305 VisitFunctionTypeLoc(TL);
306}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000307
John McCallb96ec562009-12-04 22:46:56 +0000308void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000309 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000310}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000311
John McCall17001972009-10-18 01:05:36 +0000312void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000313 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000314}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000315
Manman Rene6be26c2016-09-13 17:25:08 +0000316void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
317 if (TL.getNumProtocols()) {
318 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
319 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
320 }
321 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
322 Record.AddSourceLocation(TL.getProtocolLoc(i));
323}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000324
John McCall17001972009-10-18 01:05:36 +0000325void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000326 Record.AddSourceLocation(TL.getTypeofLoc());
327 Record.AddSourceLocation(TL.getLParenLoc());
328 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000329}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000330
John McCall17001972009-10-18 01:05:36 +0000331void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000332 Record.AddSourceLocation(TL.getTypeofLoc());
333 Record.AddSourceLocation(TL.getLParenLoc());
334 Record.AddSourceLocation(TL.getRParenLoc());
335 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000336}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000337
John McCall17001972009-10-18 01:05:36 +0000338void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000339 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000340}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000341
Alexis Hunte852b102011-05-24 22:41:36 +0000342void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000343 Record.AddSourceLocation(TL.getKWLoc());
344 Record.AddSourceLocation(TL.getLParenLoc());
345 Record.AddSourceLocation(TL.getRParenLoc());
346 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000347}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000348
Richard Smith30482bc2011-02-20 03:19:35 +0000349void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000350 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000351}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000352
Richard Smith600b5262017-01-26 20:40:47 +0000353void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
354 DeducedTemplateSpecializationTypeLoc TL) {
355 Record.AddSourceLocation(TL.getTemplateNameLoc());
356}
357
John McCall17001972009-10-18 01:05:36 +0000358void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000359 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000360}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000361
John McCall17001972009-10-18 01:05:36 +0000362void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000363 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000364}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000365
John McCall81904512011-01-06 01:58:22 +0000366void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +0000367 Record.AddAttr(TL.getAttr());
John McCall81904512011-01-06 01:58:22 +0000368}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000369
John McCall17001972009-10-18 01:05:36 +0000370void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000371 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000372}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000373
John McCallcebee162009-10-18 09:09:24 +0000374void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
375 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000376 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000377}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000378
Douglas Gregorada4b792011-01-14 02:55:32 +0000379void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
380 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000381 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000382}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000383
John McCall17001972009-10-18 01:05:36 +0000384void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
385 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000386 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
387 Record.AddSourceLocation(TL.getTemplateNameLoc());
388 Record.AddSourceLocation(TL.getLAngleLoc());
389 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000390 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000391 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
392 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000393}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000394
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000395void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000396 Record.AddSourceLocation(TL.getLParenLoc());
397 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000398}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000399
Leonard Chanc72aaf62019-05-07 03:20:17 +0000400void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
401 Record.AddSourceLocation(TL.getExpansionLoc());
402}
403
Abramo Bagnara6150c882010-05-11 21:36:43 +0000404void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000405 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
406 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000407}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000408
John McCalle78aac42010-03-10 03:28:59 +0000409void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000410 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000411}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000412
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000413void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000414 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
415 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
416 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000417}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000418
John McCallc392f372010-06-11 00:33:02 +0000419void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
420 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000421 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
422 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
423 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
424 Record.AddSourceLocation(TL.getTemplateNameLoc());
425 Record.AddSourceLocation(TL.getLAngleLoc());
426 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000427 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000428 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
429 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000430}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000431
Douglas Gregord2fa7662010-12-20 02:24:11 +0000432void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000433 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000434}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000435
John McCall17001972009-10-18 01:05:36 +0000436void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000437 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000438}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000439
John McCall8b07ec22010-05-15 11:32:37 +0000440void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
441 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000442 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
443 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000444 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000445 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
446 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
447 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000448 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000449 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000450}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000451
John McCallfc93cf92009-10-22 22:37:11 +0000452void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000453 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000454}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000455
Eli Friedman0dfb8892011-10-06 23:00:33 +0000456void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000457 Record.AddSourceLocation(TL.getKWLoc());
458 Record.AddSourceLocation(TL.getLParenLoc());
459 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000460}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000461
Xiuli Pan9c14e282016-01-09 12:53:17 +0000462void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000463 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000464}
John McCall8f115c62009-10-16 21:56:05 +0000465
Richard Smith01b2cb42014-07-26 06:37:51 +0000466void ASTWriter::WriteTypeAbbrevs() {
467 using namespace llvm;
468
David Blaikieb44f0bf2017-01-04 22:36:43 +0000469 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000470
471 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000472 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000473 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
474 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
475 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000476 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000477
478 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000479 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000480 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
481 // FunctionType
482 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
483 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
484 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
485 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
486 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
487 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000488 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000489 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
Richard Smith01b2cb42014-07-26 06:37:51 +0000490 // FunctionProtoType
491 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
492 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
493 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
494 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
495 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
496 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
497 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
498 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000499 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000500}
501
Chris Lattner19cea4e2009-04-22 05:57:30 +0000502//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000503// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000504//===----------------------------------------------------------------------===//
505
Chris Lattner28fa4e62009-04-26 22:26:21 +0000506static void EmitBlockID(unsigned ID, const char *Name,
507 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000508 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000509 Record.clear();
510 Record.push_back(ID);
511 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
512
513 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000514 if (!Name || Name[0] == 0)
515 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000516 Record.clear();
517 while (*Name)
518 Record.push_back(*Name++);
519 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
520}
521
522static void EmitRecordID(unsigned ID, const char *Name,
523 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000524 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000525 Record.clear();
526 Record.push_back(ID);
527 while (*Name)
528 Record.push_back(*Name++);
529 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000530}
531
532static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000533 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000534#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000535 RECORD(STMT_STOP);
536 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000537 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000538 RECORD(STMT_NULL);
539 RECORD(STMT_COMPOUND);
540 RECORD(STMT_CASE);
541 RECORD(STMT_DEFAULT);
542 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000543 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000544 RECORD(STMT_IF);
545 RECORD(STMT_SWITCH);
546 RECORD(STMT_WHILE);
547 RECORD(STMT_DO);
548 RECORD(STMT_FOR);
549 RECORD(STMT_GOTO);
550 RECORD(STMT_INDIRECT_GOTO);
551 RECORD(STMT_CONTINUE);
552 RECORD(STMT_BREAK);
553 RECORD(STMT_RETURN);
554 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000555 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000556 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000557 RECORD(EXPR_PREDEFINED);
558 RECORD(EXPR_DECL_REF);
559 RECORD(EXPR_INTEGER_LITERAL);
560 RECORD(EXPR_FLOATING_LITERAL);
561 RECORD(EXPR_IMAGINARY_LITERAL);
562 RECORD(EXPR_STRING_LITERAL);
563 RECORD(EXPR_CHARACTER_LITERAL);
564 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000565 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000566 RECORD(EXPR_UNARY_OPERATOR);
567 RECORD(EXPR_SIZEOF_ALIGN_OF);
568 RECORD(EXPR_ARRAY_SUBSCRIPT);
569 RECORD(EXPR_CALL);
570 RECORD(EXPR_MEMBER);
571 RECORD(EXPR_BINARY_OPERATOR);
572 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
573 RECORD(EXPR_CONDITIONAL_OPERATOR);
574 RECORD(EXPR_IMPLICIT_CAST);
575 RECORD(EXPR_CSTYLE_CAST);
576 RECORD(EXPR_COMPOUND_LITERAL);
577 RECORD(EXPR_EXT_VECTOR_ELEMENT);
578 RECORD(EXPR_INIT_LIST);
579 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000580 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000581 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000582 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000583 RECORD(EXPR_VA_ARG);
584 RECORD(EXPR_ADDR_LABEL);
585 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000586 RECORD(EXPR_CHOOSE);
587 RECORD(EXPR_GNU_NULL);
588 RECORD(EXPR_SHUFFLE_VECTOR);
589 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000590 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000591 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000592 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000593 RECORD(EXPR_OBJC_ARRAY_LITERAL);
594 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000595 RECORD(EXPR_OBJC_ENCODE);
596 RECORD(EXPR_OBJC_SELECTOR_EXPR);
597 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
598 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
599 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
600 RECORD(EXPR_OBJC_KVC_REF_EXPR);
601 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000602 RECORD(STMT_OBJC_FOR_COLLECTION);
603 RECORD(STMT_OBJC_CATCH);
604 RECORD(STMT_OBJC_FINALLY);
605 RECORD(STMT_OBJC_AT_TRY);
606 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
607 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000608 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000609 RECORD(STMT_CXX_CATCH);
610 RECORD(STMT_CXX_TRY);
611 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000612 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000613 RECORD(EXPR_CXX_MEMBER_CALL);
Richard Smith778dc0f2019-10-19 00:04:38 +0000614 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000615 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000616 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000617 RECORD(EXPR_CXX_STATIC_CAST);
618 RECORD(EXPR_CXX_DYNAMIC_CAST);
619 RECORD(EXPR_CXX_REINTERPRET_CAST);
620 RECORD(EXPR_CXX_CONST_CAST);
621 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000622 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000623 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000624 RECORD(EXPR_CXX_BOOL_LITERAL);
625 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000626 RECORD(EXPR_CXX_TYPEID_EXPR);
627 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000628 RECORD(EXPR_CXX_THIS);
629 RECORD(EXPR_CXX_THROW);
630 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000631 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000632 RECORD(EXPR_CXX_BIND_TEMPORARY);
633 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
634 RECORD(EXPR_CXX_NEW);
635 RECORD(EXPR_CXX_DELETE);
636 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
637 RECORD(EXPR_EXPR_WITH_CLEANUPS);
638 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
639 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
640 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
641 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
642 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000643 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000644 RECORD(EXPR_CXX_NOEXCEPT);
645 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000646 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
647 RECORD(EXPR_TYPE_TRAIT);
648 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000649 RECORD(EXPR_PACK_EXPANSION);
650 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000651 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000652 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000653 RECORD(EXPR_FUNCTION_PARM_PACK);
654 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000655 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000656 RECORD(EXPR_CXX_UUIDOF_EXPR);
657 RECORD(EXPR_CXX_UUIDOF_TYPE);
658 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000659#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000660}
Mike Stump11289f42009-09-09 15:08:12 +0000661
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000662void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000663 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000664 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000665
Sebastian Redl539c5062010-08-18 23:57:32 +0000666#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
667#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000668
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000669 // Control Block.
670 BLOCK(CONTROL_BLOCK);
671 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000672 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000673 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000674 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000675 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000676 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000677 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000678 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000679 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000680
681 BLOCK(OPTIONS_BLOCK);
682 RECORD(LANGUAGE_OPTIONS);
683 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000684 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000685 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000686 RECORD(PREPROCESSOR_OPTIONS);
687
Douglas Gregor108cb222012-10-19 00:45:00 +0000688 BLOCK(INPUT_FILES_BLOCK);
689 RECORD(INPUT_FILE);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +0000690 RECORD(INPUT_FILE_HASH);
Douglas Gregor108cb222012-10-19 00:45:00 +0000691
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000692 // AST Top-Level Block.
693 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000694 RECORD(TYPE_OFFSET);
695 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000696 RECORD(IDENTIFIER_OFFSET);
697 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000698 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +0000699 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000700 RECORD(SPECIAL_TYPES);
701 RECORD(STATISTICS);
702 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000703 RECORD(SELECTOR_OFFSETS);
704 RECORD(METHOD_POOL);
705 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000706 RECORD(SOURCE_LOCATION_OFFSETS);
707 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000708 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000709 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000710 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000711 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000712 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000713 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000714 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000715 RECORD(SEMA_DECL_REFS);
716 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
717 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000718 RECORD(UPDATE_VISIBLE);
719 RECORD(DECL_UPDATE_OFFSETS);
720 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000721 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000722 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000723 RECORD(FP_PRAGMA_OPTIONS);
724 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +0000725 RECORD(OPENCL_EXTENSION_TYPES);
726 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000727 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000728 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000729 RECORD(MODULE_OFFSET_MAP);
730 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000731 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000732 RECORD(FILE_SORTED_DECLS);
733 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000734 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000735 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000736 RECORD(INTERESTING_IDENTIFIERS);
737 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000738 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000739 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000740 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000741 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000742 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000743 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +0000744 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000745 RECORD(PP_CONDITIONAL_STACK);
Douglas Gregor358cd442012-01-15 16:58:34 +0000746
Chris Lattner28fa4e62009-04-26 22:26:21 +0000747 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000748 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000749 RECORD(SM_SLOC_FILE_ENTRY);
750 RECORD(SM_SLOC_BUFFER_ENTRY);
751 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000752 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000753 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattner28fa4e62009-04-26 22:26:21 +0000755 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000756 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000757 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000758 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000759 RECORD(PP_MACRO_OBJECT_LIKE);
760 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000761 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000762
Richard Smithfa715652015-08-31 22:43:10 +0000763 // Submodule Block.
764 BLOCK(SUBMODULE_BLOCK);
765 RECORD(SUBMODULE_METADATA);
766 RECORD(SUBMODULE_DEFINITION);
767 RECORD(SUBMODULE_UMBRELLA_HEADER);
768 RECORD(SUBMODULE_HEADER);
769 RECORD(SUBMODULE_TOPHEADER);
770 RECORD(SUBMODULE_UMBRELLA_DIR);
771 RECORD(SUBMODULE_IMPORTS);
772 RECORD(SUBMODULE_EXPORTS);
773 RECORD(SUBMODULE_REQUIRES);
774 RECORD(SUBMODULE_EXCLUDED_HEADER);
775 RECORD(SUBMODULE_LINK_LIBRARY);
776 RECORD(SUBMODULE_CONFIG_MACRO);
777 RECORD(SUBMODULE_CONFLICT);
778 RECORD(SUBMODULE_PRIVATE_HEADER);
779 RECORD(SUBMODULE_TEXTUAL_HEADER);
780 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +0000781 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +0000782 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +0000783
784 // Comments Block.
785 BLOCK(COMMENTS_BLOCK);
786 RECORD(COMMENTS_RAW_COMMENT);
787
Douglas Gregor12bfa382009-10-17 00:13:19 +0000788 // Decls and Types block.
789 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000790 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000791 RECORD(TYPE_COMPLEX);
792 RECORD(TYPE_POINTER);
793 RECORD(TYPE_BLOCK_POINTER);
794 RECORD(TYPE_LVALUE_REFERENCE);
795 RECORD(TYPE_RVALUE_REFERENCE);
796 RECORD(TYPE_MEMBER_POINTER);
797 RECORD(TYPE_CONSTANT_ARRAY);
798 RECORD(TYPE_INCOMPLETE_ARRAY);
799 RECORD(TYPE_VARIABLE_ARRAY);
800 RECORD(TYPE_VECTOR);
801 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000802 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000803 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000804 RECORD(TYPE_TYPEDEF);
805 RECORD(TYPE_TYPEOF_EXPR);
806 RECORD(TYPE_TYPEOF);
807 RECORD(TYPE_RECORD);
808 RECORD(TYPE_ENUM);
809 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000810 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000811 RECORD(TYPE_DECLTYPE);
812 RECORD(TYPE_ELABORATED);
813 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
814 RECORD(TYPE_UNRESOLVED_USING);
815 RECORD(TYPE_INJECTED_CLASS_NAME);
816 RECORD(TYPE_OBJC_OBJECT);
817 RECORD(TYPE_TEMPLATE_TYPE_PARM);
818 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
819 RECORD(TYPE_DEPENDENT_NAME);
820 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
821 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
822 RECORD(TYPE_PAREN);
Leonard Chanc72aaf62019-05-07 03:20:17 +0000823 RECORD(TYPE_MACRO_QUALIFIED);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000824 RECORD(TYPE_PACK_EXPANSION);
825 RECORD(TYPE_ATTRIBUTED);
826 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000827 RECORD(TYPE_AUTO);
828 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000829 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000830 RECORD(TYPE_DECAYED);
831 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +0000832 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +0000833 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000834 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000835 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000836 RECORD(DECL_ENUM);
837 RECORD(DECL_RECORD);
838 RECORD(DECL_ENUM_CONSTANT);
839 RECORD(DECL_FUNCTION);
840 RECORD(DECL_OBJC_METHOD);
841 RECORD(DECL_OBJC_INTERFACE);
842 RECORD(DECL_OBJC_PROTOCOL);
843 RECORD(DECL_OBJC_IVAR);
844 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000845 RECORD(DECL_OBJC_CATEGORY);
846 RECORD(DECL_OBJC_CATEGORY_IMPL);
847 RECORD(DECL_OBJC_IMPLEMENTATION);
848 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
849 RECORD(DECL_OBJC_PROPERTY);
850 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000851 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +0000852 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000853 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000854 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000855 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000856 RECORD(DECL_FILE_SCOPE_ASM);
857 RECORD(DECL_BLOCK);
858 RECORD(DECL_CONTEXT_LEXICAL);
859 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000860 RECORD(DECL_NAMESPACE);
861 RECORD(DECL_NAMESPACE_ALIAS);
862 RECORD(DECL_USING);
863 RECORD(DECL_USING_SHADOW);
864 RECORD(DECL_USING_DIRECTIVE);
865 RECORD(DECL_UNRESOLVED_USING_VALUE);
866 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
867 RECORD(DECL_LINKAGE_SPEC);
868 RECORD(DECL_CXX_RECORD);
869 RECORD(DECL_CXX_METHOD);
870 RECORD(DECL_CXX_CONSTRUCTOR);
871 RECORD(DECL_CXX_DESTRUCTOR);
872 RECORD(DECL_CXX_CONVERSION);
873 RECORD(DECL_ACCESS_SPEC);
874 RECORD(DECL_FRIEND);
875 RECORD(DECL_FRIEND_TEMPLATE);
876 RECORD(DECL_CLASS_TEMPLATE);
877 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
878 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000879 RECORD(DECL_VAR_TEMPLATE);
880 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
881 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000882 RECORD(DECL_FUNCTION_TEMPLATE);
883 RECORD(DECL_TEMPLATE_TYPE_PARM);
884 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
885 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Saar Razd7aae332019-07-10 21:25:49 +0000886 RECORD(DECL_CONCEPT);
Richard Smithefc884a2016-04-13 07:41:35 +0000887 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000888 RECORD(DECL_STATIC_ASSERT);
889 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +0000890 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000891 RECORD(DECL_INDIRECTFIELD);
892 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +0000893 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
894 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
895 RECORD(DECL_IMPORT);
896 RECORD(DECL_OMP_THREADPRIVATE);
897 RECORD(DECL_EMPTY);
898 RECORD(DECL_OBJC_TYPE_PARAM);
899 RECORD(DECL_OMP_CAPTUREDEXPR);
900 RECORD(DECL_PRAGMA_COMMENT);
901 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
902 RECORD(DECL_OMP_DECLARE_REDUCTION);
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000903 RECORD(DECL_OMP_ALLOCATE);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000904
Douglas Gregor03412ba2011-06-03 02:27:19 +0000905 // Statements and Exprs can occur in the Decls and Types block.
906 AddStmtsExprs(Stream, Record);
907
Douglas Gregor92a96f52011-02-08 21:58:10 +0000908 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000909 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +0000910 RECORD(PPD_MACRO_DEFINITION);
911 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000912
913 // Decls and Types block.
914 BLOCK(EXTENSION_BLOCK);
915 RECORD(EXTENSION_METADATA);
916
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000917 BLOCK(UNHASHED_CONTROL_BLOCK);
918 RECORD(SIGNATURE);
919 RECORD(DIAGNOSTIC_OPTIONS);
920 RECORD(DIAG_PRAGMA_MAPPINGS);
921
Chris Lattner28fa4e62009-04-26 22:26:21 +0000922#undef RECORD
923#undef BLOCK
924 Stream.ExitBlock();
925}
926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000927/// Prepares a path for being written to an AST file by converting it
Richard Smith54cc3c22014-12-11 20:50:24 +0000928/// to an absolute path and removing nested './'s.
929///
930/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000931static bool cleanPathForOutput(FileManager &FileMgr,
932 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +0000933 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000934 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +0000935}
936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000937/// Adjusts the given filename to only write out the portion of the
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000938/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000939///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000940/// \param Filename the file name to adjust.
941///
Richard Smith7ed1bc92014-12-05 22:42:13 +0000942/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
943/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000944///
945/// \returns either the original filename (if it needs no adjustment) or the
946/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000947static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +0000948adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000949 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000950
Richard Smith7ed1bc92014-12-05 22:42:13 +0000951 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000952 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000953
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000954 // Verify that the filename and the system root have the same prefix.
955 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000956 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
957 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000958 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000960 // We hit the end of the filename before we hit the end of the system root.
961 if (!Filename[Pos])
962 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Richard Smith7ed1bc92014-12-05 22:42:13 +0000964 // If there's not a path separator at the end of the base directory nor
965 // immediately after it, then this isn't within the base directory.
966 if (!llvm::sys::path::is_separator(Filename[Pos])) {
967 if (!llvm::sys::path::is_separator(BaseDir.back()))
968 return Filename;
969 } else {
970 // If the file name has a '/' at the current position, skip over the '/'.
971 // We distinguish relative paths from absolute paths by the
972 // absence of '/' at the beginning of relative paths.
973 //
974 // FIXME: This is wrong. We distinguish them by asking if the path is
975 // absolute, which isn't the same thing. And there might be multiple '/'s
976 // in a row. Use a better mechanism to indicate whether we have emitted an
977 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000978 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000981 return Filename + Pos;
982}
Chris Lattner28fa4e62009-04-26 22:26:21 +0000983
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000984ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
985 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
986 llvm::SHA1 Hasher;
987 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
988 auto Hash = Hasher.result();
989
990 // Convert to an array [5*i32].
991 ASTFileSignature Signature;
992 auto LShift = [&](unsigned char Val, unsigned Shift) {
993 return (uint32_t)Val << Shift;
994 };
995 for (int I = 0; I != 5; ++I)
996 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
997 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
998
999 return Signature;
1000}
1001
1002ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1003 ASTContext &Context) {
1004 // Flush first to prepare the PCM hash (signature).
1005 Stream.FlushToWord();
1006 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1007
1008 // Enter the block and prepare to write records.
1009 RecordData Record;
1010 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1011
1012 // For implicit modules, write the hash of the PCM as its signature.
1013 ASTFileSignature Signature;
1014 if (WritingModule &&
1015 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1016 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1017 Record.append(Signature.begin(), Signature.end());
1018 Stream.EmitRecord(SIGNATURE, Record);
1019 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001020 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001021
1022 // Diagnostic options.
1023 const auto &Diags = Context.getDiagnostics();
1024 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1025#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1026#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1027 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1028#include "clang/Basic/DiagnosticOptions.def"
1029 Record.push_back(DiagOpts.Warnings.size());
1030 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1031 AddString(DiagOpts.Warnings[I], Record);
1032 Record.push_back(DiagOpts.Remarks.size());
1033 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1034 AddString(DiagOpts.Remarks[I], Record);
1035 // Note: we don't serialize the log or serialization file names, because they
1036 // are generally transient files and will almost always be overridden.
1037 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1038
1039 // Write out the diagnostic/pragma mappings.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001040 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001041
1042 // Leave the options block.
1043 Stream.ExitBlock();
1044 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001045}
1046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001047/// Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001048void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1049 StringRef isysroot,
1050 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001051 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001052
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001053 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001054 RecordData Record;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001055
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001056 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001057 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001058 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1059 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1060 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1061 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1062 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1063 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001064 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001065 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001066 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1067 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001068 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001069 assert((!WritingModule || isysroot.empty()) &&
1070 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001071 {
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001072 RecordData::value_type Record[] = {
1073 METADATA,
1074 VERSION_MAJOR,
1075 VERSION_MINOR,
1076 CLANG_VERSION_MAJOR,
1077 CLANG_VERSION_MINOR,
1078 !isysroot.empty(),
1079 IncludeTimestamps,
1080 Context.getLangOpts().BuildingPCHWithObjectFile,
1081 ASTHasCompilerErrors};
Mehdi Amini57a41912015-09-10 01:46:39 +00001082 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1083 getClangFullRepositoryVersion());
1084 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001085
Richard Smith8b706102017-05-31 20:56:55 +00001086 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001087 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001088 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001089 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1090 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001091 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001092 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001093 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1094 }
1095
Richard Smith7ed1bc92014-12-05 22:42:13 +00001096 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001097 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001098 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001099
1100 // If the home of the module is the current working directory, then we
1101 // want to pick up the cwd of the build process loading the module, not
1102 // our cwd, when we load this module.
1103 if (!PP.getHeaderSearchInfo()
1104 .getHeaderSearchOpts()
1105 .ModuleMapFileHomeIsCwd ||
1106 WritingModule->Directory->getName() != StringRef(".")) {
1107 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001108 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001109 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1110 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001111 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001112
Mehdi Amini57a41912015-09-10 01:46:39 +00001113 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001114 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1115 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001116
1117 // Write out all other paths relative to the base directory if possible.
1118 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1119 } else if (!isysroot.empty()) {
1120 // Write out paths relative to the sysroot if possible.
1121 BaseDirectory = isysroot;
1122 }
1123
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001124 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001125 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001126 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001127
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001128 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001129 AddPath(WritingModule->PresumedModuleMapFile.empty()
1130 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1131 : StringRef(WritingModule->PresumedModuleMapFile),
1132 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001133
1134 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001135 if (auto *AdditionalModMaps =
1136 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001137 Record.push_back(AdditionalModMaps->size());
1138 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001139 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001140 } else {
1141 Record.push_back(0);
1142 }
1143
1144 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001145 }
1146
Douglas Gregor112b9072012-10-18 05:31:06 +00001147 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001148 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001149 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001150 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001151
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001152 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001153 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001154 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001155 continue;
1156
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001157 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1158 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001159
1160 // If we have calculated signature, there is no need to store
1161 // the size or timestamp.
1162 Record.push_back(M.Signature ? 0 : M.File->getSize());
1163 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1164
1165 for (auto I : M.Signature)
1166 Record.push_back(I);
1167
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001168 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001169 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001170 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001171 Stream.EmitRecord(IMPORTS, Record);
1172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Richard Smith0516b182015-09-08 19:40:14 +00001174 // Write the options block.
1175 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1176
Douglas Gregor112b9072012-10-18 05:31:06 +00001177 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001178 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001179 const LangOptions &LangOpts = Context.getLangOpts();
1180#define LANGOPT(Name, Bits, Default, Description) \
1181 Record.push_back(LangOpts.Name);
1182#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1183 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001184#include "clang/Basic/LangOptions.def"
1185#define SANITIZER(NAME, ID) \
1186 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001187#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001188
Ben Langmuircd98cb72015-06-23 18:20:18 +00001189 Record.push_back(LangOpts.ModuleFeatures.size());
1190 for (StringRef Feature : LangOpts.ModuleFeatures)
1191 AddString(Feature, Record);
1192
Douglas Gregor112b9072012-10-18 05:31:06 +00001193 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1194 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001195
1196 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001197
1198 // Comment options.
1199 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001200 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1201 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001202 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001203 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001204
Samuel Antaoee8fb302016-01-06 13:42:12 +00001205 // OpenMP offloading options.
1206 Record.push_back(LangOpts.OMPTargetTriples.size());
1207 for (auto &T : LangOpts.OMPTargetTriples)
1208 AddString(T.getTriple(), Record);
1209
1210 AddString(LangOpts.OMPHostIRFile, Record);
1211
Douglas Gregor112b9072012-10-18 05:31:06 +00001212 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1213
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001214 // Target options.
1215 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001216 const TargetInfo &Target = Context.getTargetInfo();
1217 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001218 AddString(TargetOpts.Triple, Record);
1219 AddString(TargetOpts.CPU, Record);
1220 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001221 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1222 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1223 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1224 }
1225 Record.push_back(TargetOpts.Features.size());
1226 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1227 AddString(TargetOpts.Features[I], Record);
1228 }
1229 Stream.EmitRecord(TARGET_OPTIONS, Record);
1230
Douglas Gregorc6317db2012-10-24 15:49:58 +00001231 // File system options.
1232 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001233 const FileSystemOptions &FSOpts =
1234 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001235 AddString(FSOpts.WorkingDir, Record);
1236 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1237
Douglas Gregor2d302362012-10-24 16:50:34 +00001238 // Header search options.
1239 Record.clear();
1240 const HeaderSearchOptions &HSOpts
1241 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1242 AddString(HSOpts.Sysroot, Record);
1243
1244 // Include entries.
1245 Record.push_back(HSOpts.UserEntries.size());
1246 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1247 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1248 AddString(Entry.Path, Record);
1249 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001250 Record.push_back(Entry.IsFramework);
1251 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001252 }
1253
1254 // System header prefixes.
1255 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1256 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1257 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1258 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1259 }
1260
1261 AddString(HSOpts.ResourceDir, Record);
1262 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001263 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001264 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001265 Record.push_back(HSOpts.ImplicitModuleMaps);
1266 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001267 Record.push_back(HSOpts.UseBuiltinIncludes);
1268 Record.push_back(HSOpts.UseStandardSystemIncludes);
1269 Record.push_back(HSOpts.UseStandardCXXIncludes);
1270 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001271 // Write out the specific module cache path that contains the module files.
1272 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001273 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1274
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001275 // Preprocessor options.
1276 Record.clear();
1277 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1278
1279 // Macro definitions.
1280 Record.push_back(PPOpts.Macros.size());
1281 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1282 AddString(PPOpts.Macros[I].first, Record);
1283 Record.push_back(PPOpts.Macros[I].second);
1284 }
1285
1286 // Includes
1287 Record.push_back(PPOpts.Includes.size());
1288 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1289 AddString(PPOpts.Includes[I], Record);
1290
1291 // Macro includes
1292 Record.push_back(PPOpts.MacroIncludes.size());
1293 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1294 AddString(PPOpts.MacroIncludes[I], Record);
1295
Douglas Gregorb6368752012-10-24 23:41:50 +00001296 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001297 // Detailed record is important since it is used for the module cache hash.
1298 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001299 AddString(PPOpts.ImplicitPCHInclude, Record);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001300 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1301 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1302
Richard Smith0516b182015-09-08 19:40:14 +00001303 // Leave the options block.
1304 Stream.ExitBlock();
1305
Douglas Gregora3b20262011-05-06 21:43:30 +00001306 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001307 SourceManager &SM = Context.getSourceManager();
1308 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001309 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001310 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1311 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001312 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001313 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001314
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001315 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001316 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001317 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001318 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001319 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001320
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001321 Record.clear();
1322 Record.push_back(SM.getMainFileID().getOpaqueValue());
1323 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1324
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001325 // Original PCH directory
1326 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001327 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001328 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1329 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001330 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001331
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001332 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001333
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001334 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001335 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1336
Mehdi Amini57a41912015-09-10 01:46:39 +00001337 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001338 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1339 }
1340
Douglas Gregor49491f72013-03-15 22:15:07 +00001341 WriteInputFiles(Context.SourceMgr,
1342 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001343 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001344 Stream.ExitBlock();
1345}
1346
Douglas Gregor49491f72013-03-15 22:15:07 +00001347namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001349/// An input file.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001350struct InputFileEntry {
1351 const FileEntry *File;
1352 bool IsSystemFile;
1353 bool IsTransient;
1354 bool BufferOverridden;
1355 bool IsTopLevelModuleMap;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001356 uint32_t ContentHash[2];
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001357};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001358
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001359} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001360
1361void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1362 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001363 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001364 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001365
Douglas Gregor72be3902012-10-19 00:38:02 +00001366 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001367
Douglas Gregor72be3902012-10-19 00:38:02 +00001368 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001369 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001370 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001371 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001372 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1373 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001374 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001375 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001376 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001377 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001378 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001379
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001380 // Create input file hash abbreviation.
1381 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1382 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1383 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1384 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1385 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1386
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001387 // Get all ContentCache objects for files, sorted by whether the file is a
1388 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001389 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001390 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1391 // Get this source location entry.
1392 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001393 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001394
1395 // We only care about file entries that were not overridden.
1396 if (!SLoc->isFile())
1397 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001398 const SrcMgr::FileInfo &File = SLoc->getFile();
1399 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001400 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001401 continue;
1402
Douglas Gregor49491f72013-03-15 22:15:07 +00001403 InputFileEntry Entry;
1404 Entry.File = Cache->OrigEntry;
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001405 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
Richard Smitha8cfffa2015-11-26 02:04:16 +00001406 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001407 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001408 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1409 File.getIncludeLoc().isInvalid();
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001410
1411 auto ContentHash = hash_code(-1);
1412 if (PP->getHeaderSearchInfo()
1413 .getHeaderSearchOpts()
1414 .ValidateASTInputFilesContent) {
1415 auto *MemBuff = Cache->getRawBuffer();
1416 if (MemBuff)
1417 ContentHash = hash_value(MemBuff->getBuffer());
1418 else
1419 // FIXME: The path should be taken from the FileEntryRef.
1420 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1421 << Entry.File->getName();
1422 }
1423 auto CH = llvm::APInt(64, ContentHash);
1424 Entry.ContentHash[0] =
1425 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1426 Entry.ContentHash[1] =
1427 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1428
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001429 if (Entry.IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001430 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001431 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001432 SortedFiles.push_front(Entry);
1433 }
1434
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001435 unsigned UserFilesNum = 0;
1436 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001437 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001438 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001439 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001440 if (InputFileID != 0)
1441 continue; // already recorded this file.
1442
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001443 // Record this entry's offset.
1444 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001445
1446 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001447
Douglas Gregor49491f72013-03-15 22:15:07 +00001448 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001449 ++UserFilesNum;
1450
Douglas Gregor72be3902012-10-19 00:38:02 +00001451 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001452 // And whether this file was overridden.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001453 {
1454 RecordData::value_type Record[] = {
1455 INPUT_FILE,
1456 InputFileOffsets.size(),
1457 (uint64_t)Entry.File->getSize(),
1458 (uint64_t)getTimestampForOutput(Entry.File),
1459 Entry.BufferOverridden,
1460 Entry.IsTransient,
1461 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001462
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001463 // FIXME: The path should be taken from the FileEntryRef.
1464 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1465 }
1466
1467 // Emit content hash for this file.
1468 {
1469 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1470 Entry.ContentHash[1]};
1471 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1472 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001473 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001474
Douglas Gregor112b9072012-10-18 05:31:06 +00001475 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001476
1477 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001478 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001479 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1480 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001481 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1482 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001483 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001484 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001485
1486 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001487 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1488 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001489 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001490}
1491
Douglas Gregora7f71a92009-04-10 03:52:48 +00001492//===----------------------------------------------------------------------===//
1493// Source Manager Serialization
1494//===----------------------------------------------------------------------===//
1495
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001496/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001497/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001498static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001499 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001500
David Blaikieb44f0bf2017-01-04 22:36:43 +00001501 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001502 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1504 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001506 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001507 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001508 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001509 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001512 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001513}
1514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001515/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001516/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001517static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001518 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001519
David Blaikieb44f0bf2017-01-04 22:36:43 +00001520 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001521 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001522 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001527 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001528}
1529
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001530/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001531/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001532static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1533 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001534 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001535
David Blaikieb44f0bf2017-01-04 22:36:43 +00001536 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001537 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1538 : SM_SLOC_BUFFER_BLOB));
1539 if (Compressed)
1540 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001541 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001542 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001543}
1544
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001545/// Create an abbreviation for the SLocEntry that refers to a macro
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001546/// expansion.
1547static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001548 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001549
David Blaikieb44f0bf2017-01-04 22:36:43 +00001550 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001551 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Richard Smithb5f81712018-04-30 05:25:48 +00001556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
Douglas Gregor83243272009-04-15 18:05:10 +00001557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001558 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001559}
1560
Douglas Gregor09b69892011-02-10 17:09:37 +00001561namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001562
Douglas Gregor09b69892011-02-10 17:09:37 +00001563 // Trait used for the on-disk hash table of header search information.
1564 class HeaderFileInfoTrait {
1565 ASTWriter &Writer;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001566
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001567 // Keep track of the framework names we've used during serialization.
1568 SmallVector<char, 128> FrameworkStringData;
1569 llvm::StringMap<unsigned> FrameworkNameOffset;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001570
Douglas Gregor09b69892011-02-10 17:09:37 +00001571 public:
Richard Smith040e1262017-06-02 01:55:39 +00001572 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1573
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001574 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001575 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001576 off_t Size;
1577 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001578 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001579 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001580
1581 using UnresolvedModule =
1582 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001583
Richard Smith040e1262017-06-02 01:55:39 +00001584 struct data_type {
1585 const HeaderFileInfo &HFI;
1586 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1587 UnresolvedModule Unresolved;
1588 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001589 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001590
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001591 using hash_value_type = unsigned;
1592 using offset_type = unsigned;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001593
Richard Smithe75ee0f2015-08-17 07:13:32 +00001594 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001595 // The hash is based only on size/time of the file, so that the reader can
1596 // match even when symlinking or excess path elements ("foo/../", "../")
1597 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001598 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001599 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001600
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001601 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001602 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001603 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001604
Peter Collingbournee3f65292018-05-18 19:46:24 +00001605 endian::Writer LE(Out, little);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001606 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001607 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001608 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001609 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001610 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1611 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001612 if (Data.Unresolved.getPointer())
1613 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001614 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001615 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001616 }
Richard Smith040e1262017-06-02 01:55:39 +00001617
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001618 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001619 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001620
Peter Collingbournee3f65292018-05-18 19:46:24 +00001621 endian::Writer LE(Out, little);
Richard Smith040e1262017-06-02 01:55:39 +00001622 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001623 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001624 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001625 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001626 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001627 }
Richard Smith040e1262017-06-02 01:55:39 +00001628
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001629 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001630 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001631 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001632
Peter Collingbournee3f65292018-05-18 19:46:24 +00001633 endian::Writer LE(Out, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001634 uint64_t Start = Out.tell(); (void)Start;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001635
Richard Smithf3f84612017-06-29 02:19:42 +00001636 unsigned char Flags = (Data.HFI.isImport << 5)
1637 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001638 | (Data.HFI.DirInfo << 1)
1639 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001640 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001641 LE.write<uint16_t>(Data.HFI.NumIncludes);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001642
Richard Smith040e1262017-06-02 01:55:39 +00001643 if (!Data.HFI.ControllingMacro)
1644 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001645 else
Richard Smith040e1262017-06-02 01:55:39 +00001646 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1647
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001648 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001649 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001650 // If this header refers into a framework, save the framework name.
1651 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00001652 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001653 if (Pos == FrameworkNameOffset.end()) {
1654 Offset = FrameworkStringData.size() + 1;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001655 FrameworkStringData.append(Data.HFI.Framework.begin(),
Richard Smith040e1262017-06-02 01:55:39 +00001656 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001657 FrameworkStringData.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001658
Richard Smith040e1262017-06-02 01:55:39 +00001659 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001660 } else
1661 Offset = Pos->second;
1662 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001663 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001664
Richard Smith040e1262017-06-02 01:55:39 +00001665 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1666 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1667 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00001668 assert((Value >> 2) == ModID && "overflow in header module info");
1669 LE.write<uint32_t>(Value);
1670 }
Richard Smith040e1262017-06-02 01:55:39 +00001671 };
1672
1673 // FIXME: If the header is excluded, we should write out some
1674 // record of that fact.
1675 for (auto ModInfo : Data.KnownHeaders)
1676 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1677 if (Data.Unresolved.getPointer())
1678 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001679
Douglas Gregor09b69892011-02-10 17:09:37 +00001680 assert(Out.tell() - Start == DataLen && "Wrong data length");
1681 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001682
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001683 const char *strings_begin() const { return FrameworkStringData.begin(); }
1684 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001685 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001686
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001687} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00001688
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001689/// Write the header search block for the list of files that
Douglas Gregor09b69892011-02-10 17:09:37 +00001690///
1691/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001692void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00001693 HeaderFileInfoTrait GeneratorTrait(*this);
1694 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1695 SmallVector<const char *, 4> SavedStrings;
1696 unsigned NumHeaderSearchEntries = 0;
1697
1698 // Find all unresolved headers for the current module. We generally will
1699 // have resolved them before we get here, but not necessarily: we might be
1700 // compiling a preprocessed module, where there is no requirement for the
1701 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00001702 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00001703 if (WritingModule) {
1704 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1705 while (!Worklist.empty()) {
1706 Module *M = Worklist.pop_back_val();
1707 if (!M->isAvailable())
1708 continue;
1709
1710 // Map to disk files where possible, to pick up any missing stat
1711 // information. This also means we don't need to check the unresolved
1712 // headers list when emitting resolved headers in the first loop below.
1713 // FIXME: It'd be preferable to avoid doing this if we were given
1714 // sufficient stat information in the module map.
1715 HS.getModuleMap().resolveHeaderDirectives(M);
1716
1717 // If the file didn't exist, we can still create a module if we were given
1718 // enough information in the module map.
1719 for (auto U : M->MissingHeaders) {
1720 // Check that we were given enough information to build a module
1721 // without this file existing on disk.
1722 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1723 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1724 << WritingModule->getFullModuleName() << U.Size.hasValue()
1725 << U.FileName;
1726 continue;
1727 }
1728
1729 // Form the effective relative pathname for the file.
1730 SmallString<128> Filename(M->Directory->getName());
1731 llvm::sys::path::append(Filename, U.FileName);
1732 PreparePathForOutput(Filename);
1733
1734 StringRef FilenameDup = strdup(Filename.c_str());
1735 SavedStrings.push_back(FilenameDup.data());
1736
1737 HeaderFileInfoTrait::key_type Key = {
1738 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1739 };
1740 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00001741 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00001742 };
1743 // FIXME: Deal with cases where there are multiple unresolved header
1744 // directives in different submodules for the same header.
1745 Generator.insert(Key, Data, GeneratorTrait);
1746 ++NumHeaderSearchEntries;
1747 }
1748
1749 Worklist.append(M->submodule_begin(), M->submodule_end());
1750 }
1751 }
1752
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001753 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001754 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001755
Douglas Gregor09b69892011-02-10 17:09:37 +00001756 if (FilesByUID.size() > HS.header_file_size())
1757 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00001758
Douglas Gregor09b69892011-02-10 17:09:37 +00001759 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1760 const FileEntry *File = FilesByUID[UID];
1761 if (!File)
1762 continue;
1763
Richard Smith386bb072015-08-18 23:42:23 +00001764 // Get the file info. This will load info from the external source if
1765 // necessary. Skip emitting this file if we have no information on it
1766 // as a header file (in which case HFI will be null) or if it hasn't
1767 // changed since it was loaded. Also skip it if it's for a modular header
1768 // from a different module; in that case, we rely on the module(s)
1769 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001770 const HeaderFileInfo *HFI =
1771 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1772 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001773 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001774
Richard Smith7ed1bc92014-12-05 22:42:13 +00001775 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001776 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001777 SmallString<128> FilenameTmp(Filename);
1778 if (PreparePathForOutput(FilenameTmp)) {
1779 // If we performed any translation on the file name at all, we need to
1780 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001781 Filename = StringRef(strdup(FilenameTmp.c_str()));
1782 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00001783 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001784
Richard Smith040e1262017-06-02 01:55:39 +00001785 HeaderFileInfoTrait::key_type Key = {
1786 Filename, File->getSize(), getTimestampForOutput(File)
1787 };
1788 HeaderFileInfoTrait::data_type Data = {
1789 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
1790 };
1791 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001792 ++NumHeaderSearchEntries;
1793 }
Richard Smith040e1262017-06-02 01:55:39 +00001794
Douglas Gregor09b69892011-02-10 17:09:37 +00001795 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001796 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001797 uint32_t BucketOffset;
1798 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001799 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001800
Douglas Gregor09b69892011-02-10 17:09:37 +00001801 llvm::raw_svector_ostream Out(TableData);
1802 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00001803 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001804 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1805 }
1806
1807 // Create a blob abbreviation
1808 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001809
David Blaikieb44f0bf2017-01-04 22:36:43 +00001810 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00001811 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1812 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1813 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00001816 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001817
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001818 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001819 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1820 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001821 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001822 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001823
Douglas Gregor09b69892011-02-10 17:09:37 +00001824 // Free all of the strings we had to duplicate.
1825 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001826 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001827}
1828
George Rimarc39f5492017-01-17 15:45:31 +00001829static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1830 unsigned SLocBufferBlobCompressedAbbrv,
1831 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001832 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00001833
1834 // Compress the buffer if possible. We expect that almost all PCM
1835 // consumers will not want its contents.
1836 SmallString<0> CompressedBuffer;
1837 if (llvm::zlib::isAvailable()) {
1838 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1839 if (!E) {
1840 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1841 Blob.size() - 1};
1842 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1843 CompressedBuffer);
1844 return;
1845 }
1846 llvm::consumeError(std::move(E));
1847 }
1848
1849 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1850 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1851}
1852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001853/// Writes the block containing the serialized form of the
Douglas Gregora7f71a92009-04-10 03:52:48 +00001854/// source manager.
1855///
1856/// TODO: We should probably use an on-disk hash table (stored in a
1857/// blob), indexed based on the file name, so that we only create
1858/// entries for files that we actually need. In the common case (no
1859/// errors), we probably won't have to create file entries for any of
1860/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001861void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001862 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001863 RecordData Record;
1864
Chris Lattner0910e3b2009-04-10 17:16:57 +00001865 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001866 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001867
1868 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001869 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1870 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001871 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1872 unsigned SLocBufferBlobCompressedAbbrv =
1873 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001874 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001875
Douglas Gregor258ae542009-04-27 06:38:32 +00001876 // Write out the source location entry table. We skip the first
1877 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001878 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001879 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001880 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1881 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001882 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001883 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001884 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001885 FileID FID = FileID::get(I);
1886 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001887
Douglas Gregor258ae542009-04-27 06:38:32 +00001888 // Record the offset of this source-location entry.
1889 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1890
1891 // Figure out which record code to use.
1892 unsigned Code;
1893 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001894 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1895 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001896 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001897 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001898 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001899 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001900 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001901 Record.clear();
1902 Record.push_back(Code);
1903
Douglas Gregor925296b2011-07-19 16:10:42 +00001904 // Starting offset of this entry within this module, so skip the dummy.
1905 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001906 if (SLoc->isFile()) {
1907 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001908 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001909 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1910 Record.push_back(File.hasLineDirectives());
1911
1912 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001913 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001914 if (Content->OrigEntry) {
1915 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001916 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001917
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001918 // The source location entry is a file. Emit input file ID.
1919 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1920 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001922 Record.push_back(File.NumCreatedFIDs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001923
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001924 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001925 if (FDI != FileDeclIDs.end()) {
1926 Record.push_back(FDI->second->FirstDeclIndex);
1927 Record.push_back(FDI->second->DeclIDs.size());
1928 } else {
1929 Record.push_back(0);
1930 Record.push_back(0);
1931 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001932
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001933 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001934
Richard Smithaada85c2016-02-06 02:06:43 +00001935 if (Content->BufferOverridden || Content->IsTransient)
1936 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001937 } else {
1938 // The source location entry is a buffer. The blob associated
1939 // with this entry contains the contents of the buffer.
1940
1941 // We add one to the size so that we capture the trailing NULL
1942 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1943 // the reader side).
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001944 const llvm::MemoryBuffer *Buffer =
1945 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00001946 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001947 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00001948 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001949 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001950
Mehdi Amini99d1b292016-10-01 16:38:28 +00001951 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00001952 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00001953 }
Richard Smithaada85c2016-02-06 02:06:43 +00001954
1955 if (EmitBlob) {
1956 // Include the implicit terminating null character in the on-disk buffer
1957 // if we're writing it uncompressed.
1958 const llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001959 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Richard Smithaada85c2016-02-06 02:06:43 +00001960 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00001961 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
1962 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00001963 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001964 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001965 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001966 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00001967 AddSourceLocation(Expansion.getSpellingLoc(), Record);
1968 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
1969 AddSourceLocation(Expansion.isMacroArgExpansion()
1970 ? SourceLocation()
1971 : Expansion.getExpansionLocEnd(),
1972 Record);
Richard Smithb5f81712018-04-30 05:25:48 +00001973 Record.push_back(Expansion.isExpansionTokenRange());
Douglas Gregor258ae542009-04-27 06:38:32 +00001974
1975 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001976 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001977 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001978 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001979 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001980 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001981 }
1982 }
1983
Douglas Gregor8f45df52009-04-16 22:23:12 +00001984 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001985
1986 if (SLocEntryOffsets.empty())
1987 return;
1988
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001989 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00001990 // table is used for lazily loading source-location information.
1991 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001992
David Blaikieb44f0bf2017-01-04 22:36:43 +00001993 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001994 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00001995 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00001996 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00001997 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00001998 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001999 {
2000 RecordData::value_type Record[] = {
2001 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2002 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2003 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2004 bytes(SLocEntryOffsets));
2005 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002006 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002007 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002008 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002009
2010 // Write the line table. It depends on remapping working, so it must come
2011 // after the source location offsets.
2012 if (SourceMgr.hasLineTable()) {
2013 LineTableInfo &LineTable = SourceMgr.getLineTable();
2014
2015 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002016
2017 // Emit the needed file names.
2018 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002019 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002020 for (const auto &L : LineTable) {
2021 if (L.first.ID < 0)
2022 continue;
2023 for (auto &LE : L.second) {
2024 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002025 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002026 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2027 }
2028 }
2029 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002030
2031 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002032 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002033 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002034 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002035 continue;
2036
2037 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002038 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002039
2040 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002041 Record.push_back(L.second.size());
2042 for (const auto &LE : L.second) {
2043 Record.push_back(LE.FileOffset);
2044 Record.push_back(LE.LineNo);
2045 Record.push_back(FilenameMap[LE.FilenameID]);
2046 Record.push_back((unsigned)LE.FileKind);
2047 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002048 }
2049 }
Richard Smith63078492015-09-01 07:41:55 +00002050
Douglas Gregor925296b2011-07-19 16:10:42 +00002051 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2052 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002053}
2054
Douglas Gregorc5046832009-04-27 18:38:38 +00002055//===----------------------------------------------------------------------===//
2056// Preprocessor Serialization
2057//===----------------------------------------------------------------------===//
2058
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002059static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2060 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002061 if (MacroInfo *MI = MD->getMacroInfo())
2062 if (MI->isBuiltinMacro())
2063 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002064
2065 if (IsModule) {
2066 SourceLocation Loc = MD->getLocation();
2067 if (Loc.isInvalid())
2068 return true;
2069 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2070 return true;
2071 }
2072
2073 return false;
2074}
2075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002076/// Writes the block containing the serialized form of the
Chris Lattnereeffaef2009-04-10 17:15:23 +00002077/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002078void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002079 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2080 if (PPRec)
2081 WritePreprocessorDetail(*PPRec);
2082
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002083 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002084 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002085
Chris Lattner0af3ba12009-04-13 01:29:17 +00002086 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2087 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002088 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002089 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002090 }
2091
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002092 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2093 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002094 auto SkipInfo = PP.getPreambleSkipInfo();
2095 if (SkipInfo.hasValue()) {
2096 Record.push_back(true);
2097 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2098 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2099 Record.push_back(SkipInfo->FoundNonSkipPortion);
2100 Record.push_back(SkipInfo->FoundElse);
2101 AddSourceLocation(SkipInfo->ElseLoc, Record);
2102 } else {
2103 Record.push_back(false);
2104 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002105 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2106 AddSourceLocation(Cond.IfLoc, Record);
2107 Record.push_back(Cond.WasSkipping);
2108 Record.push_back(Cond.FoundNonSkip);
2109 Record.push_back(Cond.FoundElse);
2110 }
2111 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2112 Record.clear();
2113 }
2114
Douglas Gregoreda6a892009-04-26 00:07:37 +00002115 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002116 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002117
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002118 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002119 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002120 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002121 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002122
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002123 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002124 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002125
Richard Smithee977932015-05-01 21:22:17 +00002126 // Construct the list of identifiers with macro directives that need to be
2127 // serialized.
2128 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2129 for (auto &Id : PP.getIdentifierTable())
2130 if (Id.second->hadMacroDefinition() &&
2131 (!Id.second->isFromAST() ||
2132 Id.second->hasChangedSinceDeserialization()))
2133 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002134 // Sort the set of macro definitions that need to be serialized by the
2135 // name of the macro, to provide a stable ordering.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00002136 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002137
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002138 // Emit the macro directives as a list and associate the offset with the
2139 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002140 for (const IdentifierInfo *Name : MacroIdentifiers) {
2141 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002142 auto StartOffset = Stream.GetCurrentBitNo();
2143
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002144 // Emit the macro directives in reverse source order.
2145 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002146 // Once we hit an ignored macro, we're done: the rest of the chain
2147 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002148 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002149 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002150
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002151 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002152 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002153 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002154 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002155 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002156 Record.push_back(VisMD->isPublic());
2157 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002158 }
Richard Smithd7329392015-04-21 21:46:32 +00002159
Richard Smithb8b2ed62015-04-23 18:18:26 +00002160 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002161 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002162 // We write out exported module macros for PCH as well.
2163 auto Leafs = PP.getLeafModuleMacros(Name);
2164 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2165 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2166 while (!Worklist.empty()) {
2167 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002168
Manman Ren33d80292016-05-31 18:19:32 +00002169 // Emit a record indicating this submodule exports this macro.
2170 ModuleMacroRecord.push_back(
2171 getSubmoduleID(Macro->getOwningModule()));
2172 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2173 for (auto *M : Macro->overrides())
2174 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002175
Manman Ren33d80292016-05-31 18:19:32 +00002176 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2177 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002178
Manman Ren33d80292016-05-31 18:19:32 +00002179 // Enqueue overridden macros once we've visited all their ancestors.
2180 for (auto *M : Macro->overrides())
2181 if (++Visits[M] == M->getNumOverridingMacros())
2182 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002183
Manman Ren33d80292016-05-31 18:19:32 +00002184 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002185 }
Richard Smithd7329392015-04-21 21:46:32 +00002186
Richard Smithee977932015-05-01 21:22:17 +00002187 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002188 continue;
2189
Richard Smithd7329392015-04-21 21:46:32 +00002190 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002191 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2192 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002193 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002195 /// Offsets of each of the macros into the bitstream, indexed by
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002196 /// the local macro ID
2197 ///
2198 /// For each identifier that is associated with a macro, this map
2199 /// provides the offset into the bitstream where that macro is
2200 /// defined.
2201 std::vector<uint32_t> MacroOffsets;
2202
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002203 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2204 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2205 MacroInfo *MI = MacroInfosToEmit[I].MI;
2206 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002207
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002208 if (ID < FirstMacroID) {
2209 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2210 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002211 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002212
2213 // Record the local offset of this macro.
2214 unsigned Index = ID - FirstMacroID;
2215 if (Index == MacroOffsets.size())
2216 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2217 else {
2218 if (Index > MacroOffsets.size())
2219 MacroOffsets.resize(Index + 1);
2220
2221 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2222 }
2223
2224 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002225 AddSourceLocation(MI->getDefinitionLoc(), Record);
2226 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2227 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002228 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002229 unsigned Code;
2230 if (MI->isObjectLike()) {
2231 Code = PP_MACRO_OBJECT_LIKE;
2232 } else {
2233 Code = PP_MACRO_FUNCTION_LIKE;
2234
2235 Record.push_back(MI->isC99Varargs());
2236 Record.push_back(MI->isGNUVarargs());
2237 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002238 Record.push_back(MI->getNumParams());
2239 for (const IdentifierInfo *Param : MI->params())
2240 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002241 }
2242
2243 // If we have a detailed preprocessing record, record the macro definition
2244 // ID that corresponds to this macro.
2245 if (PPRec)
2246 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2247
2248 Stream.EmitRecord(Code, Record);
2249 Record.clear();
2250
2251 // Emit the tokens array.
2252 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2253 // Note that we know that the preprocessor does not have any annotation
2254 // tokens in it because they are created by the parser, and thus can't
2255 // be in a macro definition.
2256 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002257 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002258 Stream.EmitRecord(PP_TOKEN, Record);
2259 Record.clear();
2260 }
2261 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002262 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002263
Douglas Gregor92a96f52011-02-08 21:58:10 +00002264 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002265
2266 // Write the offsets table for macro IDs.
2267 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002268
David Blaikieb44f0bf2017-01-04 22:36:43 +00002269 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002270 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2273 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2274
David Blaikieb44f0bf2017-01-04 22:36:43 +00002275 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002276 {
2277 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2278 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2279 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2280 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002281}
2282
2283void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002284 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002285 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002286
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002287 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002288
Douglas Gregor92a96f52011-02-08 21:58:10 +00002289 // Enter the preprocessor block.
2290 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002291
Douglas Gregoraae92242010-03-19 21:51:54 +00002292 // If the preprocessor has a preprocessing record, emit it.
2293 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002294 using namespace llvm;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002295
2296 // Set up the abbreviation for
Douglas Gregor92a96f52011-02-08 21:58:10 +00002297 unsigned InclusionAbbrev = 0;
2298 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002299 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002300 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002306 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002307 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002308
2309 unsigned FirstPreprocessorEntityID
2310 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002311 + NUM_PREDEF_PP_ENTITY_IDS;
2312 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002313 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002314 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2315 EEnd = PPRec.local_end();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002316 E != EEnd;
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002317 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002318 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002319
Richard Smith66a81862015-05-04 02:25:31 +00002320 PreprocessedEntityOffsets.push_back(
2321 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002322
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002323 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002324 // Record this macro definition's ID.
2325 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002326
Douglas Gregor92a96f52011-02-08 21:58:10 +00002327 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002328 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2329 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002330 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002331
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002332 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002333 Record.push_back(ME->isBuiltinMacro());
2334 if (ME->isBuiltinMacro())
2335 AddIdentifierRef(ME->getName(), Record);
2336 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002337 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002338 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002339 continue;
2340 }
2341
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002342 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002343 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002344 Record.push_back(ID->getFileName().size());
2345 Record.push_back(ID->wasInQuotes());
2346 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002347 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002348 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002349 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002350 // Check that the FileEntry is not null because it was not resolved and
2351 // we create a PCH even with compiler errors.
2352 if (ID->getFile())
2353 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002354 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002355 continue;
2356 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002357
Douglas Gregor92a96f52011-02-08 21:58:10 +00002358 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2359 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002360 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002361
Douglas Gregoraae92242010-03-19 21:51:54 +00002362 // Write the offsets table for the preprocessing record.
2363 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002364 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2365
Douglas Gregoraae92242010-03-19 21:51:54 +00002366 // Write the offsets table for identifier IDs.
2367 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002368
David Blaikieb44f0bf2017-01-04 22:36:43 +00002369 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002370 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002373 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002374
Mehdi Amini57a41912015-09-10 01:46:39 +00002375 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2376 FirstPreprocessorEntityID -
2377 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002378 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002379 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002380 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002381
2382 // Write the skipped region table for the preprocessing record.
2383 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2384 if (SkippedRanges.size() > 0) {
2385 std::vector<PPSkippedRange> SerializedSkippedRanges;
2386 SerializedSkippedRanges.reserve(SkippedRanges.size());
2387 for (auto const& Range : SkippedRanges)
2388 SerializedSkippedRanges.emplace_back(Range);
2389
2390 using namespace llvm;
2391 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2392 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2394 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2395
2396 Record.clear();
2397 Record.push_back(PPD_SKIPPED_RANGES);
2398 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2399 bytes(SerializedSkippedRanges));
2400 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002401}
2402
Richard Smith386bb072015-08-18 23:42:23 +00002403unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002404 if (!Mod)
2405 return 0;
2406
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002407 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2408 if (Known != SubmoduleIDs.end())
2409 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002410
Richard Smithdc1f0422016-07-20 19:10:16 +00002411 auto *Top = Mod->getTopLevelModule();
2412 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002413 (getLangOpts().CompilingPCH ||
2414 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002415 return 0;
2416
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002417 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2418}
2419
Richard Smith386bb072015-08-18 23:42:23 +00002420unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2421 // FIXME: This can easily happen, if we have a reference to a submodule that
2422 // did not result in us loading a module file for that submodule. For
2423 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2424 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2425 assert((ID || !Mod) &&
2426 "asked for module ID for non-local, non-imported module");
2427 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002428}
2429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002430/// Compute the number of modules within the given tree (including the
Douglas Gregor253eefe2011-12-01 00:59:36 +00002431/// given module).
2432static unsigned getNumberOfModules(Module *Mod) {
2433 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002434 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002435 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002436 ChildModules += getNumberOfModules(*Sub);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002437
Douglas Gregor253eefe2011-12-01 00:59:36 +00002438 return ChildModules + 1;
2439}
2440
Douglas Gregorde3ef502011-11-30 23:21:26 +00002441void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002442 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002443 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002444
Douglas Gregor69021972011-11-30 17:33:56 +00002445 // Write the abbreviations needed for the submodules block.
2446 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002447
David Blaikieb44f0bf2017-01-04 22:36:43 +00002448 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002449 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2454 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
Douglas Gregor69021972011-11-30 17:33:56 +00002462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002463 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002464
David Blaikieb44f0bf2017-01-04 22:36:43 +00002465 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002466 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002467 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002468 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002469
David Blaikieb44f0bf2017-01-04 22:36:43 +00002470 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002471 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2472 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002473 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002474
David Blaikieb44f0bf2017-01-04 22:36:43 +00002475 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002476 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2477 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002478 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002479
David Blaikieb44f0bf2017-01-04 22:36:43 +00002480 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002481 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002483 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002484
David Blaikieb44f0bf2017-01-04 22:36:43 +00002485 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002486 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002487 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2488 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002489 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002490
David Blaikieb44f0bf2017-01-04 22:36:43 +00002491 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002492 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2493 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002494 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002495
David Blaikieb44f0bf2017-01-04 22:36:43 +00002496 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002497 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002499 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002500
David Blaikieb44f0bf2017-01-04 22:36:43 +00002501 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002502 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002504 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002505
David Blaikieb44f0bf2017-01-04 22:36:43 +00002506 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002507 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2508 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002509 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002510
David Blaikieb44f0bf2017-01-04 22:36:43 +00002511 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002512 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002515 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002516
David Blaikieb44f0bf2017-01-04 22:36:43 +00002517 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002518 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2519 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002520 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002521
David Blaikieb44f0bf2017-01-04 22:36:43 +00002522 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002523 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002526 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002527
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002528 Abbrev = std::make_shared<BitCodeAbbrev>();
2529 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2531 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2532
Douglas Gregor253eefe2011-12-01 00:59:36 +00002533 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002534 RecordData::value_type Record[] = {
2535 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002536 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002537 Stream.EmitRecord(SUBMODULE_METADATA, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002538
Douglas Gregor69021972011-11-30 17:33:56 +00002539 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002540 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002541 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002542 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002543 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002544 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002545 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002546
2547 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002548 if (Mod->Parent) {
2549 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002550 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002551 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002552
2553 // Emit the definition of the block.
2554 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002555 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2556 ID,
2557 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002558 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002559 Mod->IsFramework,
2560 Mod->IsExplicit,
2561 Mod->IsSystem,
2562 Mod->IsExternC,
2563 Mod->InferSubmodules,
2564 Mod->InferExplicitSubmodules,
2565 Mod->InferExportWildcard,
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002566 Mod->ConfigMacrosExhaustive,
2567 Mod->ModuleMapIsPrivate};
Mehdi Amini57a41912015-09-10 01:46:39 +00002568 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2569 }
2570
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002571 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002572 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002573 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002574 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002575 }
2576
Douglas Gregor69021972011-11-30 17:33:56 +00002577 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002578 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002579 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002580 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2581 UmbrellaHeader.NameAsWritten);
2582 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002583 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2584 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002585 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002586 }
Richard Smith306d8922014-10-22 23:50:56 +00002587
Douglas Gregor69021972011-11-30 17:33:56 +00002588 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002589 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002590 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002591 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002592 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002593 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002594 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2595 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2596 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002597 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002598 Module::HK_PrivateTextual},
2599 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002600 };
2601 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002602 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002603 for (auto &H : Mod->Headers[HL.HeaderKind])
2604 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2605 }
2606
2607 // Emit the top headers.
2608 {
2609 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002610 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002611 for (auto *H : TopHeaders)
2612 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002613 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002614
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002615 // Emit the imports.
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002616 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002617 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002618 for (auto *I : Mod->Imports)
2619 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002620 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2621 }
2622
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002623 // Emit the exports.
Douglas Gregor24bb9232011-12-02 18:58:38 +00002624 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002625 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002626 for (const auto &E : Mod->Exports) {
2627 // FIXME: This may fail; we don't require that all exported modules
2628 // are local or imported.
2629 Record.push_back(getSubmoduleID(E.getPointer()));
2630 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002631 }
2632 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2633 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002634
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002635 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2636 // Might be unnecessary as use declarations are only used to build the
2637 // module itself.
2638
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002639 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002640 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002641 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2642 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002643 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002644 }
2645
Douglas Gregorfb912652013-03-20 21:10:35 +00002646 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002647 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002648 // FIXME: This may fail; we don't require that all conflicting modules
2649 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002650 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2651 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002652 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002653 }
2654
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002655 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002656 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002657 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002658 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002659 }
2660
Richard Smithdc1f0422016-07-20 19:10:16 +00002661 // Emit the initializers, if any.
2662 RecordData Inits;
2663 for (Decl *D : Context->getModuleInitializers(Mod))
2664 Inits.push_back(GetDeclRef(D));
2665 if (!Inits.empty())
2666 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2667
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002668 // Emit the name of the re-exported module, if any.
2669 if (!Mod->ExportAsModule.empty()) {
2670 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2671 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2672 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002673
Douglas Gregor69021972011-11-30 17:33:56 +00002674 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002675 for (auto *M : Mod->submodules())
2676 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002677 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002678
Douglas Gregor69021972011-11-30 17:33:56 +00002679 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002680
Richard Smith23d8d032015-05-14 00:45:20 +00002681 assert((NextSubmoduleID - FirstSubmoduleID ==
2682 getNumberOfModules(WritingModule)) &&
2683 "Wrong # of submodules; found a reference to a non-local, "
2684 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002685}
2686
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002687void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2688 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002689 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2690 DiagStateIDMap;
2691 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002692 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002693
Richard Smithe37391c2017-05-03 00:28:49 +00002694 auto EncodeDiagStateFlags =
2695 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2696 unsigned Result = (unsigned)DS->ExtBehavior;
2697 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00002698 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2699 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2700 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00002701 Result = (Result << 1) | Val;
2702 return Result;
2703 };
2704
2705 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2706 Record.push_back(Flags);
2707
Richard Smithd230de22017-01-26 01:01:01 +00002708 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2709 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00002710 // Ensure that the diagnostic state wasn't modified since it was created.
2711 // We will not correctly round-trip this information otherwise.
2712 assert(Flags == EncodeDiagStateFlags(State) &&
2713 "diag state flags vary in single AST file");
2714
Richard Smithd230de22017-01-26 01:01:01 +00002715 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002716 Record.push_back(DiagStateID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002717
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002718 if (DiagStateID == 0) {
2719 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002720
2721 // Add a placeholder for the number of mappings.
2722 auto SizeIdx = Record.size();
2723 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00002724 for (const auto &I : *State) {
2725 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002726 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00002727 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002728 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002729 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002730 // Update the placeholder.
2731 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00002732 }
2733 };
2734
2735 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00002736
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002737 // Reserve a spot for the number of locations with state transitions.
2738 auto NumLocationsIdx = Record.size();
2739 Record.emplace_back();
2740
2741 // Emit the state transitions.
2742 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00002743 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2744 if (!FileIDAndFile.first.isValid() ||
2745 !FileIDAndFile.second.HasLocalTransitions)
2746 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002747 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00002748
2749 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2750 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2751 AddSourceLocation(Loc, Record);
2752
Richard Smithd230de22017-01-26 01:01:01 +00002753 Record.push_back(FileIDAndFile.second.StateTransitions.size());
2754 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2755 Record.push_back(StatePoint.Offset);
2756 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002757 }
2758 }
2759
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002760 // Backpatch the number of locations.
2761 Record[NumLocationsIdx] = NumLocations;
2762
2763 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00002764 //
2765 // This also protects against a hypothetical corner case with simulating
2766 // -Werror settings for implicit modules in the ASTReader, where reading
2767 // CurDiagState out of context could change whether warning pragmas are
2768 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002769 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2770 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2771
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00002772 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002773}
2774
Douglas Gregorc5046832009-04-27 18:38:38 +00002775//===----------------------------------------------------------------------===//
2776// Type Serialization
2777//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002779/// Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002780void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002781 TypeIdx &IdxRef = TypeIdxs[T];
2782 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2783 IdxRef = TypeIdx(NextTypeID++);
2784 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002785
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002786 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002787
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002788 // Emit the type's representation.
John McCalld505e572019-12-13 21:54:44 -05002789 uint64_t Offset = ASTTypeWriter(*this).write(T);
John McCall8ccfcb52009-09-24 19:53:00 +00002790
Richard Smith290d8012016-04-06 17:06:00 +00002791 // Record the offset for this type.
2792 unsigned Index = Idx.getIndex() - FirstTypeID;
2793 if (TypeOffsets.size() == Index)
2794 TypeOffsets.push_back(Offset);
2795 else if (TypeOffsets.size() < Index) {
2796 TypeOffsets.resize(Index + 1);
2797 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002798 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002799 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002800 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002801}
2802
Douglas Gregorc5046832009-04-27 18:38:38 +00002803//===----------------------------------------------------------------------===//
2804// Declaration Serialization
2805//===----------------------------------------------------------------------===//
2806
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002807/// Write the block containing all of the declaration IDs
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002808/// lexically declared within the given DeclContext.
2809///
2810/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002811/// bitstream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002812uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002813 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002814 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002815 return 0;
2816
Douglas Gregor8f45df52009-04-16 22:23:12 +00002817 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002818 SmallVector<uint32_t, 128> KindDeclPairs;
2819 for (const auto *D : DC->decls()) {
2820 KindDeclPairs.push_back(D->getKind());
2821 KindDeclPairs.push_back(GetDeclRef(D));
2822 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002823
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002824 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002825 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002826 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2827 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002828 return Offset;
2829}
2830
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002831void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002832 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002833
2834 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002835 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002836 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002840 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002841 {
2842 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2843 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2844 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2845 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002846
2847 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002848 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002849 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002850 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002853 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002854 {
2855 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2856 FirstDeclID - NUM_PREDEF_DECL_IDS};
2857 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2858 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002859}
2860
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002861void ASTWriter::WriteFileDeclIDsMap() {
2862 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002863
Chandler Carruthb306d732015-03-27 00:31:20 +00002864 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2865 FileDeclIDs.begin(), FileDeclIDs.end());
Fangrui Song55fab262018-09-26 22:16:28 +00002866 llvm::sort(SortedFileDeclIDs, llvm::less_first());
Chandler Carruthb306d732015-03-27 00:31:20 +00002867
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002868 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002869 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2870 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2871 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2872 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2873 for (auto &LocDeclEntry : Info.DeclIDs)
2874 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002875 }
2876
David Blaikieb44f0bf2017-01-04 22:36:43 +00002877 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002878 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002879 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002881 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002882 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2883 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002884 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002885}
2886
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002887void ASTWriter::WriteComments() {
2888 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Ilya Biryukov45643102018-07-09 11:33:23 +00002889 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2890 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2891 return;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002892 RecordData Record;
Jan Korousf31d8df2019-08-13 18:11:44 +00002893 for (const auto &FO : Context->Comments.OrderedComments) {
2894 for (const auto &OC : FO.second) {
2895 const RawComment *I = OC.second;
2896 Record.clear();
2897 AddSourceRange(I->getSourceRange(), Record);
2898 Record.push_back(I->getKind());
2899 Record.push_back(I->isTrailingComment());
2900 Record.push_back(I->isAlmostTrailingComment());
2901 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2902 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002903 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002904}
2905
Douglas Gregorc5046832009-04-27 18:38:38 +00002906//===----------------------------------------------------------------------===//
2907// Global Method Pool and Selector Serialization
2908//===----------------------------------------------------------------------===//
2909
Douglas Gregore84a9da2009-04-20 20:36:09 +00002910namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002911
Douglas Gregorc78d3462009-04-24 21:10:55 +00002912// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002913class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002914 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002915
2916public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002917 using key_type = Selector;
2918 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00002919
Sebastian Redl834bb972010-08-04 17:20:04 +00002920 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002921 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002922 ObjCMethodList Instance, Factory;
2923 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002924 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002925
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002926 using hash_value_type = unsigned;
2927 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00002928
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002929 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00002930
Justin Bogner25463f12014-04-18 20:27:24 +00002931 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002932 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002933 }
Mike Stump11289f42009-09-09 15:08:12 +00002934
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002935 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002936 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002937 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002938 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002939
Peter Collingbournee3f65292018-05-18 19:46:24 +00002940 endian::Writer LE(Out, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002941 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002942 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002943 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2944 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002945 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002946 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002947 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002948 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002949 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002950 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002951 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002952 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002953 return std::make_pair(KeyLen, DataLen);
2954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002956 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002957 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002958
Peter Collingbournee3f65292018-05-18 19:46:24 +00002959 endian::Writer LE(Out, little);
Mike Stump11289f42009-09-09 15:08:12 +00002960 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002961 assert((Start >> 32) == 0 && "Selector key offset too large");
2962 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002963 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002964 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002965 if (N == 0)
2966 N = 1;
2967 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002968 LE.write<uint32_t>(
2969 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002970 }
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002972 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002973 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002974 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002975
Peter Collingbournee3f65292018-05-18 19:46:24 +00002976 endian::Writer LE(Out, little);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002977 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002978 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002979 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002980 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002981 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002982 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002983 ++NumInstanceMethods;
2984
2985 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002986 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002987 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002988 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002989 ++NumFactoryMethods;
2990
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002991 unsigned InstanceBits = Methods.Instance.getBits();
2992 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002993 unsigned InstanceHasMoreThanOneDeclBit =
2994 Methods.Instance.hasMoreThanOneDecl();
2995 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2996 (InstanceHasMoreThanOneDeclBit << 2) |
2997 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002998 unsigned FactoryBits = Methods.Factory.getBits();
2999 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003000 unsigned FactoryHasMoreThanOneDeclBit =
3001 Methods.Factory.hasMoreThanOneDecl();
3002 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3003 (FactoryHasMoreThanOneDeclBit << 2) |
3004 FactoryBits;
3005 LE.write<uint16_t>(FullInstanceBits);
3006 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003007 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003008 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003009 if (Method->getMethod())
3010 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003011 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003012 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003013 if (Method->getMethod())
3014 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003015
3016 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003017 }
3018};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003019
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003020} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003022/// Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003023///
3024/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003025/// in an on-disk hash table indexed by the selector. The hash table also
3026/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003027void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003028 using namespace llvm;
3029
Sebastian Redla19a67f2010-08-03 21:58:15 +00003030 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003031 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003032 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003033 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003034 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003035 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003036 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003037 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003038
Sebastian Redla19a67f2010-08-03 21:58:15 +00003039 // Create the on-disk hash table representation. We walk through every
3040 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003041 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003042 for (auto &SelectorAndID : SelectorIDs) {
3043 Selector S = SelectorAndID.first;
3044 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003045 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003046 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003047 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003048 ObjCMethodList(),
3049 ObjCMethodList()
3050 };
3051 if (F != SemaRef.MethodPool.end()) {
3052 Data.Instance = F->second.first;
3053 Data.Factory = F->second.second;
3054 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003055 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003056 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003057 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003058 // Selector already exists. Did it change?
3059 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003060 for (ObjCMethodList *M = &Data.Instance;
3061 !changed && M && M->getMethod(); M = M->getNext()) {
3062 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003063 changed = true;
3064 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003065 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003066 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003067 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003068 changed = true;
3069 }
3070 if (!changed)
3071 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003072 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003073 // A new method pool entry.
3074 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003075 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003076 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003077 }
3078
Douglas Gregorc78d3462009-04-24 21:10:55 +00003079 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003080 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003081 uint32_t BucketOffset;
3082 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003083 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003084
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003085 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003086 llvm::raw_svector_ostream Out(MethodPool);
3087 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003088 endian::write<uint32_t>(Out, 0, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003089 BucketOffset = Generator.Emit(Out, Trait);
3090 }
3091
3092 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003093 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003094 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003095 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003096 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003097 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003098 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003099
Douglas Gregor95c13f52009-04-25 17:48:32 +00003100 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003101 {
3102 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3103 NumTableEntries};
3104 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3105 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003106
3107 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003108 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003109 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003110 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003113 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003114
3115 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003116 {
3117 RecordData::value_type Record[] = {
3118 SELECTOR_OFFSETS, SelectorOffsets.size(),
3119 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3120 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3121 bytes(SelectorOffsets));
3122 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003123 }
3124}
3125
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003126/// Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003127void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003128 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003129
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003130 if (SemaRef.ReferencedSelectors.empty())
3131 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003132
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003133 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003134 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003135
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003136 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003137 // very tricky to fix, and given that @selector shouldn't really appear in
3138 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003139 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3140 Selector Sel = SelectorAndLocation.first;
3141 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003142 Writer.AddSelectorRef(Sel);
3143 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003144 }
Richard Smithe64e7452016-04-18 21:54:58 +00003145 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003146}
3147
Douglas Gregorc5046832009-04-27 18:38:38 +00003148//===----------------------------------------------------------------------===//
3149// Identifier Table Serialization
3150//===----------------------------------------------------------------------===//
3151
Richard Smithb3761912015-02-05 23:08:52 +00003152/// Determine the declaration that should be put into the name lookup table to
3153/// represent the given declaration in this module. This is usually D itself,
3154/// but if D was imported and merged into a local declaration, we want the most
3155/// recent local declaration instead. The chosen declaration will be the most
3156/// recent declaration in any module that imports this one.
3157static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3158 NamedDecl *D) {
3159 if (!LangOpts.Modules || !D->isFromASTFile())
3160 return D;
3161
3162 if (Decl *Redecl = D->getPreviousDecl()) {
3163 // For Redeclarable decls, a prior declaration might be local.
3164 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003165 // If we find a local decl, we're done.
3166 if (!Redecl->isFromASTFile()) {
3167 // Exception: in very rare cases (for injected-class-names), not all
3168 // redeclarations are in the same semantic context. Skip ones in a
3169 // different context. They don't go in this lookup table at all.
3170 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3171 D->getDeclContext()->getRedeclContext()))
3172 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003173 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003174 }
3175
Richard Smithfe620d22015-03-05 23:24:12 +00003176 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003177 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003178 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003179 break;
3180 }
3181 } else if (Decl *First = D->getCanonicalDecl()) {
3182 // For Mergeable decls, the first decl might be local.
3183 if (!First->isFromASTFile())
3184 return cast<NamedDecl>(First);
3185 }
3186
3187 // All declarations are imported. Our most recent declaration will also be
3188 // the most recent one in anyone who imports us.
3189 return D;
3190}
3191
Douglas Gregorc78d3462009-04-24 21:10:55 +00003192namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003193
Richard Smithcf97cf62015-04-19 01:34:23 +00003194class ASTIdentifierTableTrait {
3195 ASTWriter &Writer;
3196 Preprocessor &PP;
3197 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003198 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003199 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003200 ASTWriter::RecordData *InterestingIdentifierOffsets;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003202 /// Determines whether this is an "interesting" identifier that needs a
Richard Smithcf97cf62015-04-19 01:34:23 +00003203 /// full IdentifierInfo structure written into the hash table. Notably, this
3204 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3205 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003206 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003207 if (MacroOffset ||
3208 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003209 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003210 II->hasRevertedTokenIDToIdentifier() ||
Bruno Ricci366ba732018-09-21 12:53:22 +00003211 (NeedDecls && II->getFETokenInfo()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003212 return true;
3213
3214 return false;
3215 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003216
Douglas Gregore84a9da2009-04-20 20:36:09 +00003217public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003218 using key_type = IdentifierInfo *;
3219 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003220
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003221 using data_type = IdentID;
3222 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003223
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003224 using hash_value_type = unsigned;
3225 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003226
Richard Smithd7329392015-04-21 21:46:32 +00003227 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003228 IdentifierResolver &IdResolver, bool IsModule,
3229 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003230 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003231 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3232 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003233
Richard Smithd79514e2016-02-05 19:03:40 +00003234 bool needDecls() const { return NeedDecls; }
3235
Justin Bogner25463f12014-04-18 20:27:24 +00003236 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003237 return llvm::djbHash(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239
Richard Smith33e0f7e2015-07-22 02:08:40 +00003240 bool isInterestingIdentifier(const IdentifierInfo *II) {
3241 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3242 return isInterestingIdentifier(II, MacroOffset);
3243 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003244
Richard Smith9c254182015-07-19 21:41:12 +00003245 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3246 return isInterestingIdentifier(II, 0);
3247 }
3248
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003249 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003250 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003251 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003252 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003253 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3254 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003255 DataLen += 2; // 2 bytes for builtin ID
3256 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003257 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003258 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003259
Richard Smitha534a312015-07-21 23:54:07 +00003260 if (NeedDecls) {
3261 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3262 DEnd = IdResolver.end();
3263 D != DEnd; ++D)
3264 DataLen += 4;
3265 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003266 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003267
Justin Bognere1c147c2014-03-28 22:03:19 +00003268 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003269
Peter Collingbournee3f65292018-05-18 19:46:24 +00003270 endian::Writer LE(Out, little);
Justin Bognere1c147c2014-03-28 22:03:19 +00003271
Richard Smithdf8a8312015-03-13 04:05:01 +00003272 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003273 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003274 // We emit the key length after the data length so that every
3275 // string is preceded by a 16-bit length. This matches the PTH
3276 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003277 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003278 return std::make_pair(KeyLen, DataLen);
3279 }
Mike Stump11289f42009-09-09 15:08:12 +00003280
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003281 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003282 unsigned KeyLen) {
3283 // Record the location of the key data. This is used when generating
3284 // the mapping from persistent IDs to strings.
3285 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003286
3287 // Emit the offset of the key/data length information to the interesting
3288 // identifiers table if necessary.
3289 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3290 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3291
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003292 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003293 }
Mike Stump11289f42009-09-09 15:08:12 +00003294
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003295 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003296 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003297 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003298
Peter Collingbournee3f65292018-05-18 19:46:24 +00003299 endian::Writer LE(Out, little);
Richard Smithcf97cf62015-04-19 01:34:23 +00003300
Richard Smithd7329392015-04-21 21:46:32 +00003301 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3302 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003303 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003304 return;
3305 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003306
Justin Bognere1c147c2014-03-28 22:03:19 +00003307 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003308 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3309 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003310 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003311 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003312 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003313 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003314 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3315 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003316 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003317 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003318 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003319 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003320
Richard Smithd7329392015-04-21 21:46:32 +00003321 if (HadMacroDefinition)
3322 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003323
Richard Smitha534a312015-07-21 23:54:07 +00003324 if (NeedDecls) {
3325 // Emit the declaration IDs in reverse order, because the
3326 // IdentifierResolver provides the declarations as they would be
3327 // visible (e.g., the function "stat" would come before the struct
3328 // "stat"), but the ASTReader adds declarations to the end of the list
3329 // (so we need to see the struct "stat" before the function "stat").
3330 // Only emit declarations that aren't from a chained PCH, though.
3331 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3332 IdResolver.end());
3333 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3334 DEnd = Decls.rend();
3335 D != DEnd; ++D)
3336 LE.write<uint32_t>(
3337 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3338 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003339 }
3340};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003341
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003342} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003344/// Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003345///
3346/// The identifier table consists of a blob containing string data
3347/// (the actual identifiers themselves) and a separate "offsets" index
3348/// that maps identifier IDs to locations within the blob.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003349void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003350 IdentifierResolver &IdResolver,
3351 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003352 using namespace llvm;
3353
Richard Smith33e0f7e2015-07-22 02:08:40 +00003354 RecordData InterestingIdents;
3355
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003356 // Create and write out the blob that contains the identifier
3357 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003358 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003359 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003360 ASTIdentifierTableTrait Trait(
3361 *this, PP, IdResolver, IsModule,
3362 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003363
Douglas Gregore6648fb2009-04-28 20:33:11 +00003364 // Look for any identifiers that were named while processing the
3365 // headers, but are otherwise not needed. We add these to the hash
3366 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003367 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003368 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003369 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003370 for (const auto &ID : PP.getIdentifierTable())
3371 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003372 // Sort the identifiers lexicographically before getting them references so
3373 // that their order is stable.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00003374 llvm::sort(IIs, llvm::deref<std::less<>>());
Chandler Carruth8440c982015-03-26 23:54:15 +00003375 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003376 if (Trait.isInterestingNonMacroIdentifier(II))
3377 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003378
Sebastian Redlff4a2952010-07-23 23:49:55 +00003379 // Create the on-disk hash table representation. We only store offsets
3380 // for identifiers that appear here for the first time.
3381 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003382 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003383 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003384 IdentID ID = IdentIDPair.second;
3385 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003386 // Write out identifiers if either the ID is local or the identifier has
3387 // changed since it was loaded.
3388 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3389 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003390 (Trait.needDecls() &&
3391 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003392 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003393 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003394
Douglas Gregore84a9da2009-04-20 20:36:09 +00003395 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003396 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003397 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003398 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003399 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003400
Douglas Gregore84a9da2009-04-20 20:36:09 +00003401 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003402 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003403 endian::write<uint32_t>(Out, 0, little);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003404 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003405 }
3406
3407 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003408 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003409 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003410 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003411 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003412 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003413
3414 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003415 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003416 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003417 }
3418
3419 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003420 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003421 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003422 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003425 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003426
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003427#ifndef NDEBUG
3428 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3429 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3430#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003431
3432 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3433 IdentifierOffsets.size(),
3434 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003435 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003436 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003437
3438 // In C++, write the list of interesting identifiers (those that are
3439 // defined as macros, poisoned, or similar unusual things).
3440 if (!InterestingIdents.empty())
3441 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003442}
3443
Douglas Gregorc5046832009-04-27 18:38:38 +00003444//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003445// DeclContext's Name Lookup Table Serialization
3446//===----------------------------------------------------------------------===//
3447
3448namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003449
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003450// Trait used for the on-disk hash table used in the method pool.
3451class ASTDeclContextNameLookupTrait {
3452 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003453 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003454
3455public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003456 using key_type = DeclarationNameKey;
3457 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003458
Richard Smithd88a7f12015-09-01 20:35:42 +00003459 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003460 using data_type = std::pair<unsigned, unsigned>;
3461 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003462
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003463 using hash_value_type = unsigned;
3464 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003465
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003466 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003467
Richard Smithd88a7f12015-09-01 20:35:42 +00003468 template<typename Coll>
3469 data_type getData(const Coll &Decls) {
3470 unsigned Start = DeclIDs.size();
3471 for (NamedDecl *D : Decls) {
3472 DeclIDs.push_back(
3473 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3474 }
3475 return std::make_pair(Start, DeclIDs.size());
3476 }
3477
3478 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3479 unsigned Start = DeclIDs.size();
3480 for (auto ID : FromReader)
3481 DeclIDs.push_back(ID);
3482 return std::make_pair(Start, DeclIDs.size());
3483 }
3484
3485 static bool EqualKey(key_type_ref a, key_type_ref b) {
3486 return a == b;
3487 }
3488
Richard Smitha06c7e62015-08-26 23:55:49 +00003489 hash_value_type ComputeHash(DeclarationNameKey Name) {
3490 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003491 }
3492
Richard Smithd88a7f12015-09-01 20:35:42 +00003493 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3494 assert(Writer.hasChain() &&
3495 "have reference to loaded module file but no chain?");
3496
3497 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003498
Peter Collingbournee3f65292018-05-18 19:46:24 +00003499 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
Richard Smithd88a7f12015-09-01 20:35:42 +00003500 }
3501
Richard Smitha06c7e62015-08-26 23:55:49 +00003502 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3503 DeclarationNameKey Name,
3504 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003505 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003506
Peter Collingbournee3f65292018-05-18 19:46:24 +00003507 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003508 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003509 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003510 case DeclarationName::Identifier:
3511 case DeclarationName::ObjCZeroArgSelector:
3512 case DeclarationName::ObjCOneArgSelector:
3513 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003514 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003515 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003516 KeyLen += 4;
3517 break;
3518 case DeclarationName::CXXOperatorName:
3519 KeyLen += 1;
3520 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003521 case DeclarationName::CXXConstructorName:
3522 case DeclarationName::CXXDestructorName:
3523 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003524 case DeclarationName::CXXUsingDirective:
3525 break;
3526 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003527 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003528
Richard Smithf02662d2015-07-30 03:17:16 +00003529 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003530 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3531 assert(uint16_t(DataLen) == DataLen &&
3532 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003533 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003534
3535 return std::make_pair(KeyLen, DataLen);
3536 }
3537
Richard Smitha06c7e62015-08-26 23:55:49 +00003538 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003539 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003540
Peter Collingbournee3f65292018-05-18 19:46:24 +00003541 endian::Writer LE(Out, little);
Richard Smitha06c7e62015-08-26 23:55:49 +00003542 LE.write<uint8_t>(Name.getKind());
3543 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003544 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003545 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003546 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003547 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003548 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003549 case DeclarationName::ObjCZeroArgSelector:
3550 case DeclarationName::ObjCOneArgSelector:
3551 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003552 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003553 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003554 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003555 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003556 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003557 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003558 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003559 case DeclarationName::CXXConstructorName:
3560 case DeclarationName::CXXDestructorName:
3561 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003562 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003563 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003564 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003565
3566 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003567 }
3568
Richard Smitha06c7e62015-08-26 23:55:49 +00003569 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3570 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003571 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003572
Peter Collingbournee3f65292018-05-18 19:46:24 +00003573 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003574 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003575 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3576 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003577 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3578 }
3579};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003580
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003581} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003582
Chandler Carruthe972c362015-03-26 03:11:40 +00003583bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3584 DeclContext *DC) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003585 return Result.hasExternalDecls() &&
3586 DC->hasNeedToReconcileExternalVisibleStorage();
Chandler Carruthe972c362015-03-26 03:11:40 +00003587}
3588
3589bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3590 DeclContext *DC) {
3591 for (auto *D : Result.getLookupResult())
3592 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3593 return false;
3594
3595 return true;
3596}
3597
Richard Smithd88a7f12015-09-01 20:35:42 +00003598void
Chandler Carruthe972c362015-03-26 03:11:40 +00003599ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003600 llvm::SmallVectorImpl<char> &LookupTable) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003601 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3602 !ConstDC->hasLazyExternalLexicalLookups() &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003603 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003604
Chandler Carruthe972c362015-03-26 03:11:40 +00003605 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003606 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003607 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3608
3609 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003610 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3611 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003612 ASTDeclContextNameLookupTrait Trait(*this);
3613
Chandler Carruthe972c362015-03-26 03:11:40 +00003614 // The first step is to collect the declaration names which we need to
3615 // serialize into the name lookup table, and to collect them in a stable
3616 // order.
3617 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003618
Chandler Carruthe972c362015-03-26 03:11:40 +00003619 // We also build up small sets of the constructor and conversion function
3620 // names which are visible.
3621 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003622
Chandler Carruthe972c362015-03-26 03:11:40 +00003623 for (auto &Lookup : *DC->buildLookup()) {
3624 auto &Name = Lookup.first;
3625 auto &Result = Lookup.second;
3626
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003627 // If there are no local declarations in our lookup result, we
3628 // don't need to write an entry for the name at all. If we can't
3629 // write out a lookup set without performing more deserialization,
3630 // just skip this entry.
3631 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003632 isLookupResultEntirelyExternal(Result, DC))
3633 continue;
3634
3635 // We also skip empty results. If any of the results could be external and
3636 // the currently available results are empty, then all of the results are
3637 // external and we skip it above. So the only way we get here with an empty
3638 // results is when no results could have been external *and* we have
3639 // external results.
3640 //
3641 // FIXME: While we might want to start emitting on-disk entries for negative
3642 // lookups into a decl context as an optimization, today we *have* to skip
3643 // them because there are names with empty lookup results in decl contexts
3644 // which we can't emit in any stable ordering: we lookup constructors and
3645 // conversion functions in the enclosing namespace scope creating empty
3646 // results for them. This in almost certainly a bug in Clang's name lookup,
3647 // but that is likely to be hard or impossible to fix and so we tolerate it
3648 // here by omitting lookups with empty results.
3649 if (Lookup.second.getLookupResult().empty())
3650 continue;
3651
3652 switch (Lookup.first.getNameKind()) {
3653 default:
3654 Names.push_back(Lookup.first);
3655 break;
3656
Richard Smithcd45dbc2014-04-19 03:48:30 +00003657 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003658 assert(isa<CXXRecordDecl>(DC) &&
3659 "Cannot have a constructor name outside of a class!");
3660 ConstructorNameSet.insert(Name);
3661 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003662
3663 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003664 assert(isa<CXXRecordDecl>(DC) &&
3665 "Cannot have a conversion function name outside of a class!");
3666 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003667 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003668 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003669 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003670
Chandler Carruthe972c362015-03-26 03:11:40 +00003671 // Sort the names into a stable order.
Fangrui Song55fab262018-09-26 22:16:28 +00003672 llvm::sort(Names);
Chandler Carruthe972c362015-03-26 03:11:40 +00003673
Chandler Carruthffbf7052015-03-26 22:27:09 +00003674 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003675 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003676 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003677
Chandler Carruthffbf7052015-03-26 22:27:09 +00003678 // First we try the easy case by forming the current context's constructor
3679 // name and adding that name first. This is a very useful optimization to
3680 // avoid walking the lexical declarations in many cases, and it also
3681 // handles the only case where a constructor name can come from some other
3682 // lexical context -- when that name is an implicit constructor merged from
3683 // another declaration in the redecl chain. Any non-implicit constructor or
3684 // conversion function which doesn't occur in all the lexical contexts
3685 // would be an ODR violation.
3686 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3687 Context->getCanonicalType(Context->getRecordType(D)));
3688 if (ConstructorNameSet.erase(ImplicitCtorName))
3689 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003690
Chandler Carruthffbf7052015-03-26 22:27:09 +00003691 // If we still have constructors or conversion functions, we walk all the
3692 // names in the decl and add the constructors and conversion functions
3693 // which are visible in the order they lexically occur within the context.
3694 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3695 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3696 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3697 auto Name = ChildND->getDeclName();
3698 switch (Name.getNameKind()) {
3699 default:
3700 continue;
3701
3702 case DeclarationName::CXXConstructorName:
3703 if (ConstructorNameSet.erase(Name))
3704 Names.push_back(Name);
3705 break;
3706
3707 case DeclarationName::CXXConversionFunctionName:
3708 if (ConversionNameSet.erase(Name))
3709 Names.push_back(Name);
3710 break;
3711 }
3712
3713 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3714 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003715 }
3716
Chandler Carruthe972c362015-03-26 03:11:40 +00003717 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3718 "constructors by walking all the "
3719 "lexical members of the context.");
3720 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3721 "conversion functions by walking all "
3722 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003723 }
3724
Chandler Carruthe972c362015-03-26 03:11:40 +00003725 // Next we need to do a lookup with each name into this decl context to fully
3726 // populate any results from external sources. We don't actually use the
3727 // results of these lookups because we only want to use the results after all
3728 // results have been loaded and the pointers into them will be stable.
3729 for (auto &Name : Names)
3730 DC->lookup(Name);
3731
3732 // Now we need to insert the results for each name into the hash table. For
3733 // constructor names and conversion function names, we actually need to merge
3734 // all of the results for them into one list of results each and insert
3735 // those.
3736 SmallVector<NamedDecl *, 8> ConstructorDecls;
3737 SmallVector<NamedDecl *, 8> ConversionDecls;
3738
3739 // Now loop over the names, either inserting them or appending for the two
3740 // special cases.
3741 for (auto &Name : Names) {
3742 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3743
3744 switch (Name.getNameKind()) {
3745 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003746 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003747 break;
3748
3749 case DeclarationName::CXXConstructorName:
3750 ConstructorDecls.append(Result.begin(), Result.end());
3751 break;
3752
3753 case DeclarationName::CXXConversionFunctionName:
3754 ConversionDecls.append(Result.begin(), Result.end());
3755 break;
3756 }
3757 }
3758
3759 // Handle our two special cases if we ended up having any. We arbitrarily use
3760 // the first declaration's name here because the name itself isn't part of
3761 // the key, only the kind of name is used.
3762 if (!ConstructorDecls.empty())
3763 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003764 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003765 if (!ConversionDecls.empty())
3766 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003767 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003768
Richard Smithd88a7f12015-09-01 20:35:42 +00003769 // Create the on-disk hash table. Also emit the existing imported and
3770 // merged table if there is one.
3771 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3772 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003773}
3774
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003775/// Write the block containing all of the declaration IDs
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003776/// visible from the given DeclContext.
3777///
3778/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003779/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003780uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3781 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003782 // If we imported a key declaration of this namespace, write the visible
3783 // lookup results as an update record for it rather than including them
3784 // on this declaration. We will only look at key declarations on reload.
3785 if (isa<NamespaceDecl>(DC) && Chain &&
3786 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3787 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003788 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003789 Prev = Prev->getPreviousDecl())
3790 if (!Prev->isFromASTFile())
3791 return 0;
3792
3793 // Note that we need to emit an update record for the primary context.
3794 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3795
3796 // Make sure all visible decls are written. They will be recorded later. We
3797 // do this using a side data structure so we can sort the names into
3798 // a deterministic order.
3799 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3800 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3801 LookupResults;
3802 if (Map) {
3803 LookupResults.reserve(Map->size());
3804 for (auto &Entry : *Map)
3805 LookupResults.push_back(
3806 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3807 }
3808
Fangrui Song55fab262018-09-26 22:16:28 +00003809 llvm::sort(LookupResults, llvm::less_first());
Richard Smith5fc18a92015-07-12 23:43:21 +00003810 for (auto &NameAndResult : LookupResults) {
3811 DeclarationName Name = NameAndResult.first;
3812 DeclContext::lookup_result Result = NameAndResult.second;
3813 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3814 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3815 // We have to work around a name lookup bug here where negative lookup
3816 // results for these names get cached in namespace lookup tables (these
3817 // names should never be looked up in a namespace).
3818 assert(Result.empty() && "Cannot have a constructor or conversion "
3819 "function name in a namespace!");
3820 continue;
3821 }
3822
3823 for (NamedDecl *ND : Result)
3824 if (!ND->isFromASTFile())
3825 GetDeclRef(ND);
3826 }
3827
3828 return 0;
3829 }
3830
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003831 if (DC->getPrimaryContext() != DC)
3832 return 0;
3833
Chandler Carruthe972c362015-03-26 03:11:40 +00003834 // Skip contexts which don't support name lookup.
3835 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003836 return 0;
3837
3838 // If not in C++, we perform name lookup for the translation unit via the
3839 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003840 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003841 return 0;
3842
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003843 // Serialize the contents of the mapping used for lookup. Note that,
3844 // although we have two very different code paths, the serialized
3845 // representation is the same for both cases: a declaration name,
3846 // followed by a size, followed by references to the visible
3847 // declarations that have that name.
3848 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003849 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003850 if (!Map || Map->empty())
3851 return 0;
3852
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003853 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003854 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003855 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003856
3857 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003858 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003859 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003860 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003861 ++NumVisibleDeclContexts;
3862 return Offset;
3863}
3864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003865/// Write an UPDATE_VISIBLE block for the given context.
Sebastian Redla4071b42010-08-24 00:50:09 +00003866///
3867/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3868/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003869/// (in C++), for namespaces, and for classes with forward-declared unscoped
3870/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003871void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003872 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003873 if (!Map || Map->empty())
3874 return;
3875
Sebastian Redla4071b42010-08-24 00:50:09 +00003876 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003877 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003878 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003879
Richard Smith5fc18a92015-07-12 23:43:21 +00003880 // If we're updating a namespace, select a key declaration as the key for the
3881 // update record; those are the only ones that will be checked on reload.
3882 if (isa<NamespaceDecl>(DC))
3883 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3884
Sebastian Redla4071b42010-08-24 00:50:09 +00003885 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003886 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003887 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003888}
3889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003890/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003891void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Adam Nemet484aa452017-03-27 19:17:25 +00003892 RecordData::value_type Record[] = {Opts.getInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003893 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3894}
3895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003896/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003897void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003898 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003899 return;
3900
3901 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3902 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00003903 for (const auto &I:Opts.OptMap) {
3904 AddString(I.getKey(), Record);
3905 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00003906 Record.push_back(V.Supported ? 1 : 0);
3907 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00003908 Record.push_back(V.Avail);
3909 Record.push_back(V.Core);
3910 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003911 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3912}
3913
Yaxun Liu5b746652016-12-18 05:18:55 +00003914void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3915 if (!SemaRef.Context.getLangOpts().OpenCL)
3916 return;
3917
Bruno Ricci2751b692019-04-18 15:13:27 +00003918 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3919 // without copying them.
3920 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3921 SemaRef.OpenCLTypeExtMap;
3922 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3923 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3924 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3925
3926 for (const auto &I : OpenCLTypeExtMap)
3927 StableOpenCLTypeExtMap.emplace_back(
3928 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
3929
3930 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3931 return E1.first < E2.first;
3932 };
3933 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
3934
Yaxun Liu5b746652016-12-18 05:18:55 +00003935 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003936 for (const ElementTy &E : StableOpenCLTypeExtMap) {
3937 Record.push_back(E.first); // TypeID
3938 const std::set<std::string> *ExtSet = E.second;
3939 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3940 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003941 AddString(Ext, Record);
3942 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003943
Yaxun Liu5b746652016-12-18 05:18:55 +00003944 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3945}
3946
3947void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3948 if (!SemaRef.Context.getLangOpts().OpenCL)
3949 return;
3950
Bruno Ricci2751b692019-04-18 15:13:27 +00003951 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
3952 // without copying them.
3953 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
3954 SemaRef.OpenCLDeclExtMap;
3955 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
3956 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
3957 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
3958
3959 for (const auto &I : OpenCLDeclExtMap)
3960 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
3961
3962 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3963 return E1.first < E2.first;
3964 };
3965 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
3966
Yaxun Liu5b746652016-12-18 05:18:55 +00003967 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003968 for (const ElementTy &E : StableOpenCLDeclExtMap) {
3969 Record.push_back(E.first); // DeclID
3970 const std::set<std::string> *ExtSet = E.second;
3971 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3972 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003973 AddString(Ext, Record);
3974 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003975
Yaxun Liu5b746652016-12-18 05:18:55 +00003976 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
3977}
3978
Justin Lebar67a78a62016-10-08 22:15:58 +00003979void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3980 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3981 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3982 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
3983 }
3984}
3985
Douglas Gregor404cdde2012-01-27 01:47:08 +00003986void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003987 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003988 RecordData Categories;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003989
Douglas Gregor404cdde2012-01-27 01:47:08 +00003990 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3991 unsigned Size = 0;
3992 unsigned StartIndex = Categories.size();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003993
Douglas Gregor404cdde2012-01-27 01:47:08 +00003994 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003995
Douglas Gregor404cdde2012-01-27 01:47:08 +00003996 // Allocate space for the size.
3997 Categories.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003998
Douglas Gregor404cdde2012-01-27 01:47:08 +00003999 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004000 for (ObjCInterfaceDecl::known_categories_iterator
4001 Cat = Class->known_categories_begin(),
4002 CatEnd = Class->known_categories_end();
4003 Cat != CatEnd; ++Cat, ++Size) {
4004 assert(getDeclID(*Cat) != 0 && "Bogus category");
4005 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004006 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004007
Douglas Gregor404cdde2012-01-27 01:47:08 +00004008 // Update the size.
4009 Categories[StartIndex] = Size;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004010
Douglas Gregor404cdde2012-01-27 01:47:08 +00004011 // Record this interface -> category map.
4012 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4013 CategoriesMap.push_back(CatInfo);
4014 }
4015
4016 // Sort the categories map by the definition ID, since the reader will be
4017 // performing binary searches on this information.
4018 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4019
4020 // Emit the categories map.
4021 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004022
David Blaikieb44f0bf2017-01-04 22:36:43 +00004023 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004024 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4025 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4026 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004027 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004028
4029 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4030 Stream.EmitRecordWithBlob(AbbrevID, Record,
4031 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004032 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004033
Douglas Gregor404cdde2012-01-27 01:47:08 +00004034 // Emit the category lists.
4035 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4036}
4037
Richard Smithe40f2ba2013-08-07 21:41:30 +00004038void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4039 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4040
4041 if (LPTMap.empty())
4042 return;
4043
4044 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004045 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004046 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004047 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004048 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004049 AddDeclRef(LPT.D, Record);
4050 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004051
Justin Lebar28f09c52016-10-10 16:26:08 +00004052 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004053 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004054 }
4055 }
4056 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4057}
4058
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004059/// Write the state of 'pragma clang optimize' at the end of the module.
Dario Domizioli13a0a382014-05-23 12:13:25 +00004060void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4061 RecordData Record;
4062 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4063 AddSourceLocation(PragmaLoc, Record);
4064 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4065}
4066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004067/// Write the state of 'pragma ms_struct' at the end of the module.
Nico Weber779355f2016-03-02 23:22:00 +00004068void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4069 RecordData Record;
4070 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4071 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4072}
4073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004074/// Write the state of 'pragma pointers_to_members' at the end of the
Nico Weber42932312016-03-03 00:17:35 +00004075//module.
4076void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4077 RecordData Record;
4078 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4079 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4080 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4081}
4082
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004083/// Write the state of 'pragma pack' at the end of the module.
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004084void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004085 // Don't serialize pragma pack state for modules, since it should only take
4086 // effect on a per-submodule basis.
4087 if (WritingModule)
4088 return;
4089
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004090 RecordData Record;
4091 Record.push_back(SemaRef.PackStack.CurrentValue);
4092 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4093 Record.push_back(SemaRef.PackStack.Stack.size());
4094 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4095 Record.push_back(StackEntry.Value);
4096 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004097 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004098 AddString(StackEntry.StackSlotLabel, Record);
4099 }
4100 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4101}
4102
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004103void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4104 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004105 // Enter the extension block.
4106 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4107
4108 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004109 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004110 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4111 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4112 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4113 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4114 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4115 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004116 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004117
4118 // Emit the metadata record.
4119 RecordData Record;
4120 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4121 Record.push_back(EXTENSION_METADATA);
4122 Record.push_back(Metadata.MajorVersion);
4123 Record.push_back(Metadata.MinorVersion);
4124 Record.push_back(Metadata.BlockName.size());
4125 Record.push_back(Metadata.UserInfo.size());
4126 SmallString<64> Buffer;
4127 Buffer += Metadata.BlockName;
4128 Buffer += Metadata.UserInfo;
4129 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4130
4131 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004132 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004133
4134 // Exit the extension block.
4135 Stream.ExitBlock();
4136}
4137
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004138//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004139// General Serialization Routines
4140//===----------------------------------------------------------------------===//
4141
Richard Smithe43e2b32018-08-20 21:47:29 +00004142void ASTRecordWriter::AddAttr(const Attr *A) {
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004143 auto &Record = *this;
Richard Smithe43e2b32018-08-20 21:47:29 +00004144 if (!A)
4145 return Record.push_back(0);
4146 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
Erich Keane6a24e802019-09-13 17:39:31 +00004147
4148 Record.AddIdentifierRef(A->getAttrName());
4149 Record.AddIdentifierRef(A->getScopeName());
Richard Smithe43e2b32018-08-20 21:47:29 +00004150 Record.AddSourceRange(A->getRange());
Erich Keane6a24e802019-09-13 17:39:31 +00004151 Record.AddSourceLocation(A->getScopeLoc());
4152 Record.push_back(A->getParsedKind());
4153 Record.push_back(A->getSyntax());
4154 Record.push_back(A->getAttributeSpellingListIndexRaw());
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004155
4156#include "clang/Serialization/AttrPCHWrite.inc"
Richard Smithe43e2b32018-08-20 21:47:29 +00004157}
4158
4159/// Emit the list of attributes to the specified record.
4160void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4161 push_back(Attrs.size());
4162 for (const auto *A : Attrs)
4163 AddAttr(A);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004164}
4165
John McCallf413f5e2013-05-03 00:10:13 +00004166void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4167 AddSourceLocation(Tok.getLocation(), Record);
4168 Record.push_back(Tok.getLength());
4169
4170 // FIXME: When reading literal tokens, reconstruct the literal pointer
4171 // if it is needed.
4172 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4173 // FIXME: Should translate token kind to a stable encoding.
4174 Record.push_back(Tok.getKind());
4175 // FIXME: Should translate token flags to a stable encoding.
4176 Record.push_back(Tok.getFlags());
4177}
4178
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004179void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004180 Record.push_back(Str.size());
4181 Record.insert(Record.end(), Str.begin(), Str.end());
4182}
4183
Richard Smith7ed1bc92014-12-05 22:42:13 +00004184bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004185 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004186
Richard Smith54cc3c22014-12-11 20:50:24 +00004187 bool Changed =
4188 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004189
4190 // Remove a prefix to make the path relative, if relevant.
4191 const char *PathBegin = Path.data();
4192 const char *PathPtr =
4193 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4194 if (PathPtr != PathBegin) {
4195 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4196 Changed = true;
4197 }
4198
4199 return Changed;
4200}
4201
4202void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4203 SmallString<128> FilePath(Path);
4204 PreparePathForOutput(FilePath);
4205 AddString(FilePath, Record);
4206}
4207
Mehdi Amini57a41912015-09-10 01:46:39 +00004208void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004209 StringRef Path) {
4210 SmallString<128> FilePath(Path);
4211 PreparePathForOutput(FilePath);
4212 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4213}
4214
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004215void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4216 RecordDataImpl &Record) {
4217 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004218 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004219 Record.push_back(*Minor + 1);
4220 else
4221 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004222 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004223 Record.push_back(*Subminor + 1);
4224 else
4225 Record.push_back(0);
4226}
4227
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004228/// Note that the identifier II occurs at the given offset
Douglas Gregore84a9da2009-04-20 20:36:09 +00004229/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004230void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004231 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004232 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004233 // up earlier in the chain and thus don't need an offset.
4234 if (ID >= FirstIdentID)
4235 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004236}
4237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004238/// Note that the selector Sel occurs at the given offset
Douglas Gregor95c13f52009-04-25 17:48:32 +00004239/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004240void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004241 unsigned ID = SelectorIDs[Sel];
4242 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004243 // Don't record offsets for selectors that are also available in a different
4244 // file.
4245 if (ID < FirstSelectorID)
4246 return;
4247 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004248}
4249
David Blaikie61137e12017-01-05 18:23:18 +00004250ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004251 SmallVectorImpl<char> &Buffer,
4252 InMemoryModuleCache &ModuleCache,
David Blaikie61137e12017-01-05 18:23:18 +00004253 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4254 bool IncludeTimestamps)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004255 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004256 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004257 for (const auto &Ext : Extensions) {
4258 if (auto Writer = Ext->createExtensionWriter(*this))
4259 ModuleFileExtensionWriters.push_back(std::move(Writer));
4260 }
4261}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004262
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004263ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004264 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004265}
4266
Richard Smithb3761912015-02-05 23:08:52 +00004267const LangOptions &ASTWriter::getLangOpts() const {
4268 assert(WritingAST && "can't determine lang opts when not writing AST");
4269 return Context->getLangOpts();
4270}
4271
Richard Smithe75ee0f2015-08-17 07:13:32 +00004272time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4273 return IncludeTimestamps ? E->getModificationTime() : 0;
4274}
4275
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004276ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4277 const std::string &OutputFile,
4278 Module *WritingModule, StringRef isysroot,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004279 bool hasErrors,
4280 bool ShouldCacheASTInMemory) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004281 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004282
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004283 ASTHasCompilerErrors = hasErrors;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004284
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004285 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004286 Stream.Emit((unsigned)'C', 8);
4287 Stream.Emit((unsigned)'P', 8);
4288 Stream.Emit((unsigned)'C', 8);
4289 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004290
Chris Lattner28fa4e62009-04-26 22:26:21 +00004291 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004292
Douglas Gregoreda8e122011-08-09 15:13:55 +00004293 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004294 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004295 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004296 ASTFileSignature Signature =
4297 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004298 Context = nullptr;
4299 PP = nullptr;
4300 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004301 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004302
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004303 WritingAST = false;
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004304 if (ShouldCacheASTInMemory) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004305 // Construct MemoryBuffer and update buffer manager.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004306 ModuleCache.addBuiltPCM(OutputFile,
4307 llvm::MemoryBuffer::getMemBufferCopy(
4308 StringRef(Buffer.begin(), Buffer.size())));
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004309 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004310 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004311}
4312
Douglas Gregora94a1542011-07-27 21:45:57 +00004313template<typename Vector>
4314static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4315 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004316 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4317 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004318 Writer.AddDeclRef(*I, Record);
4319 }
4320}
4321
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004322ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4323 const std::string &OutputFile,
4324 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004325 using namespace llvm;
4326
Craig Toppera13603a2014-05-22 05:54:18 +00004327 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004328
Douglas Gregorcf68c582011-12-01 22:20:10 +00004329 // Make sure that the AST reader knows to finalize itself.
4330 if (Chain)
4331 Chain->finalizeForWriting();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004332
Sebastian Redl143413f2010-07-12 22:02:52 +00004333 ASTContext &Context = SemaRef.Context;
4334 Preprocessor &PP = SemaRef.PP;
4335
Douglas Gregordab42432011-08-12 00:15:20 +00004336 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004337 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4338 if (D) {
4339 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4340 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004341 }
4342 };
4343 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4344 PREDEF_DECL_TRANSLATION_UNIT_ID);
4345 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4346 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4347 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4348 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4349 PREDEF_DECL_OBJC_PROTOCOL_ID);
4350 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4351 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4352 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4353 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4354 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004355 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004356 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4357 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004358 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004359 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4360 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004361 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4362 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004363 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4364 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004365 RegisterPredefDecl(Context.TypePackElementDecl,
4366 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004367
Chris Lattner0c797362009-09-08 18:19:27 +00004368 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004369 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004370 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004371 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004372 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004373
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004374 // Build a record containing all of the file scoped decls in this file.
4375 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004376 if (!isModule)
4377 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4378 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004379
Douglas Gregor851443c2011-08-12 01:39:19 +00004380 // Build a record containing all of the delegating constructors we still need
4381 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004382 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004383 if (!isModule)
4384 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004385
Douglas Gregor851443c2011-08-12 01:39:19 +00004386 // Write the set of weak, undeclared identifiers. We always write the
4387 // entire table, since later PCH files in a PCH chain are only interested in
4388 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004389 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004390 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4391 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4392 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4393 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4394 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4395 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4396 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004397 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004398
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004399 // Build a record containing all of the ext_vector declarations.
4400 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004401 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004402
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004403 // Build a record containing all of the VTable uses information.
4404 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004405 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004406 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4407 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4408 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4409 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4410 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004411 }
4412
Nico Weber72889432014-09-06 01:25:55 +00004413 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4414 RecordData UnusedLocalTypedefNameCandidates;
4415 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4416 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4417
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004418 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004419 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004420 for (const auto &I : SemaRef.PendingInstantiations) {
4421 AddDeclRef(I.first, PendingInstantiations);
4422 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004423 }
4424 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4425 "There are local ones at end of translation unit!");
4426
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004427 // Build a record containing some declaration references.
4428 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004429 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004430 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4431 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004432 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004433 }
4434
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004435 RecordData CUDASpecialDeclRefs;
4436 if (Context.getcudaConfigureCallDecl()) {
4437 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4438 }
4439
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004440 // Build a record containing all of the known namespaces.
4441 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004442 for (const auto &I : SemaRef.KnownNamespaces) {
4443 if (!I.second)
4444 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004445 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004446
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004447 // Build a record of all used, undefined objects that require definitions.
4448 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004449
4450 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004451 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004452 for (const auto &I : Undefined) {
4453 AddDeclRef(I.first, UndefinedButUsed);
4454 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004455 }
4456
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004457 // Build a record containing all delete-expressions that we would like to
4458 // analyze later in AST.
4459 RecordData DeleteExprsToAnalyze;
4460
Richard Smithf5262c62018-06-28 01:57:04 +00004461 if (!isModule) {
4462 for (const auto &DeleteExprsInfo :
4463 SemaRef.getMismatchingDeleteExpressions()) {
4464 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4465 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4466 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4467 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4468 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4469 }
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004470 }
4471 }
4472
Douglas Gregor112b9072012-10-18 05:31:06 +00004473 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004474 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004475
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004476 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004477 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004478
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004479 // This is so that older clang versions, before the introduction
4480 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004481 {
4482 RecordData Record = {VERSION_MAJOR};
4483 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4484 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004485
Douglas Gregor851443c2011-08-12 01:39:19 +00004486 // Create a lexical update block containing all of the declarations in the
4487 // translation unit that do not come from other AST files.
4488 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004489 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4490 for (const auto *D : TU->noload_decls()) {
4491 if (!D->isFromASTFile()) {
4492 NewGlobalKindDeclPairs.push_back(D->getKind());
4493 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4494 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004495 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004496
David Blaikieb44f0bf2017-01-04 22:36:43 +00004497 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004498 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4499 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004500 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004501 {
4502 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4503 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4504 bytes(NewGlobalKindDeclPairs));
4505 }
4506
Douglas Gregor851443c2011-08-12 01:39:19 +00004507 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004508 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004509 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4510 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004511 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004512 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004513 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004514
4515 // If we have any extern "C" names, write out a visible update for them.
4516 if (Context.ExternCContext)
4517 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004518
Douglas Gregor851443c2011-08-12 01:39:19 +00004519 // If the translation unit has an anonymous namespace, and we don't already
4520 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004521 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004522 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4523 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004524 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004525 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004526 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004527
Richard Smith5652c0f2014-03-21 01:48:23 +00004528 // Add update records for all mangling numbers and static local numbers.
4529 // These aren't really update records, but this is a convenient way of
4530 // tagging this rare extra data onto the declarations.
4531 for (const auto &Number : Context.MangleNumbers)
4532 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004533 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4534 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004535 for (const auto &Number : Context.StaticLocalNumbers)
4536 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004537 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4538 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004539
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004540 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004541 // an AST file, are registered for serialization. Likewise for template
4542 // specializations added to imported templates.
4543 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004544 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004545 }
4546
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004547 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004548 // serialization, if we're storing decls with identifiers.
4549 if (!WritingModule || !getLangOpts().CPlusPlus) {
4550 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004551 for (const auto &ID : PP.getIdentifierTable()) {
4552 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004553 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4554 IIs.push_back(II);
4555 }
4556 // Sort the identifiers to visit based on their name.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00004557 llvm::sort(IIs, llvm::deref<std::less<>>());
Richard Smith79bf9202015-08-24 03:33:22 +00004558 for (const IdentifierInfo *II : IIs) {
4559 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4560 DEnd = SemaRef.IdResolver.end();
4561 D != DEnd; ++D) {
4562 GetDeclRef(*D);
4563 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004564 }
4565 }
4566
Manman Rena0f31a02016-04-29 19:04:05 +00004567 // For method pool in the module, if it contains an entry for a selector,
4568 // the entry should be complete, containing everything introduced by that
4569 // module and all modules it imports. It's possible that the entry is out of
4570 // date, so we need to pull in the new content here.
4571
4572 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4573 // safe, we copy all selectors out.
4574 llvm::SmallVector<Selector, 256> AllSelectors;
4575 for (auto &SelectorAndID : SelectorIDs)
4576 AllSelectors.push_back(SelectorAndID.first);
4577 for (auto &Selector : AllSelectors)
4578 SemaRef.updateOutOfDateSelector(Selector);
4579
Douglas Gregor5204bde2011-08-02 16:26:37 +00004580 // Form the record of special types.
4581 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004582 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004583 AddTypeRef(Context.getFILEType(), SpecialTypes);
4584 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4585 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4586 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4587 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004588 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004589 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004590
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004591 if (Chain) {
4592 // Write the mapping information describing our module dependencies and how
4593 // each of those modules were mapped into our own offset/ID space, so that
4594 // the reader can build the appropriate mapping to its own offset/ID space.
4595 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004596 // *(module-kind:i8
4597 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004598 // source-location-offset:i32
4599 // identifier-id:i32
4600 // preprocessed-entity-id:i32
4601 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004602 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004603 // selector-id:i32
4604 // declaration-id:i32
4605 // c++-base-specifiers-id:i32
4606 // type-id:i32)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004607 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004608 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4609 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4610 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004611 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004612 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004614 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004615 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004616 {
4617 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004618 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004619 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004620
Peter Collingbournee3f65292018-05-18 19:46:24 +00004621 endian::Writer LE(Out, little);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004622 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4623 StringRef Name =
4624 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4625 ? M.ModuleName
4626 : M.FileName;
4627 LE.write<uint16_t>(Name.size());
4628 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004629
Ben Langmuir785180e2014-10-20 16:27:30 +00004630 // Note: if a base ID was uint max, it would not be possible to load
4631 // another module after it or have more than one entity inside it.
4632 uint32_t None = std::numeric_limits<uint32_t>::max();
4633
4634 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4635 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4636 if (ShouldWrite)
4637 LE.write<uint32_t>(BaseID);
4638 else
4639 LE.write<uint32_t>(None);
4640 };
4641
Ben Langmuirfe971d92014-08-16 04:54:18 +00004642 // These values should be unique within a chain, since they will be read
4643 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004644 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4645 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4646 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4647 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4648 M.NumPreprocessedEntities);
4649 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4650 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4651 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4652 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004653 }
4654 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004655 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004656 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4657 Buffer.data(), Buffer.size());
4658 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004659
Richard Smithb9eab6d2014-03-20 19:44:17 +00004660 RecordData DeclUpdatesOffsetsRecord;
4661
Richard Smith59442b42014-03-20 20:07:19 +00004662 // Keep writing types, declarations, and declaration update records
4663 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004664 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4665 WriteTypeAbbrevs();
4666 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004667 do {
4668 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4669 while (!DeclTypesToEmit.empty()) {
4670 DeclOrType DOT = DeclTypesToEmit.front();
4671 DeclTypesToEmit.pop();
4672 if (DOT.isType())
4673 WriteType(DOT.getType());
4674 else
4675 WriteDecl(Context, DOT.getDecl());
4676 }
4677 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004678 Stream.ExitBlock();
4679
Richard Smithb9eab6d2014-03-20 19:44:17 +00004680 DoneWritingDeclsAndTypes = true;
4681
4682 // These things can only be done once we've written out decls and types.
4683 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004684 if (!DeclUpdatesOffsetsRecord.empty())
4685 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004686 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004687 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004688 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004689 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004690 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004691 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004692 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004693 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004694 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004695 WriteFPPragmaOptions(SemaRef.getFPOptions());
4696 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004697 WriteOpenCLExtensionTypes(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004698 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004699
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004700 // If we're emitting a module, write out the submodule information.
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004701 if (WritingModule)
4702 WriteSubmodules(WritingModule);
4703
Andrew Savonichev52d674d2018-10-29 11:14:01 +00004704 // We need to have information about submodules to correctly deserialize
4705 // decls from OpenCLExtensionDecls block
4706 WriteOpenCLExtensionDecls(SemaRef);
4707
Douglas Gregor5204bde2011-08-02 16:26:37 +00004708 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4709
Douglas Gregord4df8652009-04-22 22:02:47 +00004710 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004711 if (!EagerlyDeserializedDecls.empty())
4712 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004713
David Blaikief63556d2017-04-12 20:58:33 +00004714 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004715 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4716
Douglas Gregord4df8652009-04-22 22:02:47 +00004717 // Write the record containing tentative definitions.
4718 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004719 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004720
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004721 // Write the record containing unused file scoped decls.
4722 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004723 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004724
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004725 // Write the record containing weak undeclared identifiers.
4726 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004727 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004728 WeakUndeclaredIdentifiers);
4729
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004730 // Write the record containing ext_vector type names.
4731 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004732 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004733
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004734 // Write the record containing VTable uses information.
4735 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004736 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004737
Nico Weber72889432014-09-06 01:25:55 +00004738 // Write the record containing potentially unused local typedefs.
4739 if (!UnusedLocalTypedefNameCandidates.empty())
4740 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4741 UnusedLocalTypedefNameCandidates);
4742
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004743 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004744 if (!PendingInstantiations.empty())
4745 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004746
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004747 // Write the record containing declaration references of Sema.
4748 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004749 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004750
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004751 // Write the record containing CUDA-specific declaration references.
4752 if (!CUDASpecialDeclRefs.empty())
4753 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004754
Alexis Hunt27a761d2011-05-04 23:29:54 +00004755 // Write the delegating constructors.
4756 if (!DelegatingCtorDecls.empty())
4757 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004758
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004759 // Write the known namespaces.
4760 if (!KnownNamespaces.empty())
4761 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004762
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004763 // Write the undefined internal functions and variables, and inline functions.
4764 if (!UndefinedButUsed.empty())
4765 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004766
4767 if (!DeleteExprsToAnalyze.empty())
4768 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4769
Douglas Gregor851443c2011-08-12 01:39:19 +00004770 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004771 for (auto *DC : UpdatedDeclContexts)
4772 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004773
Douglas Gregor959bb062011-12-03 01:15:29 +00004774 if (!WritingModule) {
4775 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004776 struct ModuleInfo {
4777 uint64_t ID;
4778 Module *M;
4779 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4780 };
Richard Smith56be7542014-03-21 00:33:59 +00004781 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004782 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004783 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004784 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4785 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004786 }
Richard Smith56be7542014-03-21 00:33:59 +00004787
4788 if (!Imports.empty()) {
4789 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4790 return A.ID < B.ID;
4791 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004792 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4793 return A.ID == B.ID;
4794 };
Richard Smith56be7542014-03-21 00:33:59 +00004795
4796 // Sort and deduplicate module IDs.
Fangrui Song55fab262018-09-26 22:16:28 +00004797 llvm::sort(Imports, Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004798 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004799 Imports.end());
4800
4801 RecordData ImportedModules;
4802 for (const auto &Import : Imports) {
4803 ImportedModules.push_back(Import.ID);
4804 // FIXME: If the module has macros imported then later has declarations
4805 // imported, this location won't be the right one as a location for the
4806 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004807 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004808 }
4809
Douglas Gregor959bb062011-12-03 01:15:29 +00004810 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4811 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004812 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004813
Douglas Gregor404cdde2012-01-27 01:47:08 +00004814 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004815 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004816 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004817 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004818 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004819 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004820 WritePackPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004821
Douglas Gregor08f01292009-04-17 22:13:46 +00004822 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004823 RecordData::value_type Record[] = {
4824 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004825 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004826 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004827
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004828 // Write the module file extension blocks.
4829 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004830 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004831
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004832 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004833}
4834
Richard Smithb9eab6d2014-03-20 19:44:17 +00004835void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004836 if (DeclUpdates.empty())
4837 return;
4838
Richard Smith59442b42014-03-20 20:07:19 +00004839 DeclUpdateMap LocalUpdates;
4840 LocalUpdates.swap(DeclUpdates);
4841
Richard Smith6ef42932014-03-20 21:02:00 +00004842 for (auto &DeclUpdate : LocalUpdates) {
4843 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004844
Richard Smithd28ac5b2014-03-22 23:33:22 +00004845 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004846 RecordData RecordData;
4847 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004848 for (auto &Update : DeclUpdate.second) {
4849 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4850
Richard Smith69c82bf2016-04-01 22:52:03 +00004851 // An updated body is emitted last, so that the reader doesn't need
4852 // to skip over the lazy body to reach statements for other records.
4853 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4854 HasUpdatedBody = true;
4855 else
4856 Record.push_back(Kind);
4857
Richard Smith6ef42932014-03-20 21:02:00 +00004858 switch (Kind) {
4859 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4860 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4861 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004862 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004863 Record.push_back(GetDeclRef(Update.getDecl()));
4864 break;
4865
Richard Smith4d235792014-08-07 18:53:08 +00004866 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004867 break;
4868
Richard Smith891fc7f2017-12-05 01:31:47 +00004869 case UPD_CXX_POINT_OF_INSTANTIATION:
4870 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00004871 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00004872 break;
4873
4874 case UPD_CXX_ADDED_VAR_DEFINITION: {
4875 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00004876 Record.push_back(VD->isInline());
4877 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00004878 if (VD->getInit()) {
4879 Record.push_back(!VD->isInitKnownICE() ? 1
4880 : (VD->isInitICE() ? 3 : 2));
4881 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4882 } else {
4883 Record.push_back(0);
4884 }
Richard Smith4d235792014-08-07 18:53:08 +00004885 break;
Richard Smith05a21352017-06-22 22:18:46 +00004886 }
Richard Smith4d235792014-08-07 18:53:08 +00004887
John McCall32791cc2016-01-06 22:34:54 +00004888 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004889 Record.AddStmt(const_cast<Expr *>(
4890 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004891 break;
4892
Richard Smith4b054b22016-08-24 21:25:37 +00004893 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4894 Record.AddStmt(
4895 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4896 break;
4897
Richard Smithcd45dbc2014-04-19 03:48:30 +00004898 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4899 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004900 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00004901 Record.push_back(RD->isParamDestroyedInCallee());
Akira Hatanakae6313ac2018-04-09 22:48:22 +00004902 Record.push_back(RD->getArgPassingRestrictions());
Richard Smith69c82bf2016-04-01 22:52:03 +00004903 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004904 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004905 *Context, const_cast<CXXRecordDecl *>(RD)));
4906
4907 // This state is sometimes updated by template instantiation, when we
4908 // switch from the specialization referring to the template declaration
4909 // to it referring to the template definition.
4910 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4911 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004912 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004913 } else {
4914 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4915 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004916 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004917
4918 // The instantiation might have been resolved to a partial
4919 // specialization. If so, record which one.
4920 auto From = Spec->getInstantiatedFrom();
4921 if (auto PartialSpec =
4922 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4923 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004924 Record.AddDeclRef(PartialSpec);
4925 Record.AddTemplateArgumentList(
4926 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004927 } else {
4928 Record.push_back(false);
4929 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004930 }
4931 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004932 Record.AddSourceLocation(RD->getLocation());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004933 Record.AddSourceLocation(RD->getBeginLoc());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004934 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004935
4936 // Instantiation may change attributes; write them all out afresh.
4937 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004938 if (D->hasAttrs())
4939 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004940
4941 // FIXME: Ensure we don't get here for explicit instantiations.
4942 break;
4943 }
4944
Richard Smithf8134002015-03-10 01:41:22 +00004945 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004946 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00004947 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00004948 break;
4949
John McCalld505e572019-12-13 21:54:44 -05004950 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4951 auto prototype =
4952 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
4953 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
Richard Smith564417a2014-03-20 21:47:22 +00004954 break;
John McCalld505e572019-12-13 21:54:44 -05004955 }
Richard Smith564417a2014-03-20 21:47:22 +00004956
Richard Smith6ef42932014-03-20 21:02:00 +00004957 case UPD_CXX_DEDUCED_RETURN_TYPE:
4958 Record.push_back(GetOrCreateTypeID(Update.getType()));
4959 break;
4960
4961 case UPD_DECL_MARKED_USED:
4962 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004963
4964 case UPD_MANGLING_NUMBER:
4965 case UPD_STATIC_LOCAL_NUMBER:
4966 Record.push_back(Update.getNumber());
4967 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004968
Alexey Bataev97720002014-11-11 04:05:39 +00004969 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004970 Record.AddSourceRange(
4971 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004972 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004973
Alexey Bataev27ef9512019-03-20 20:14:22 +00004974 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4975 auto *A = D->getAttr<OMPAllocateDeclAttr>();
4976 Record.push_back(A->getAllocatorType());
4977 Record.AddStmt(A->getAllocator());
4978 Record.AddSourceRange(A->getRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004979 break;
Alexey Bataev27ef9512019-03-20 20:14:22 +00004980 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004981
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004982 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
Alexey Bataevd01b7492018-08-15 19:45:12 +00004983 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004984 Record.AddSourceRange(
4985 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4986 break;
4987
Richard Smith65ebb4a2015-03-26 04:09:53 +00004988 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004989 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004990 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004991
4992 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004993 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004994 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004995 }
4996 }
4997
Richard Smithd28ac5b2014-03-22 23:33:22 +00004998 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004999 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005000 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005001 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005002 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005003 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005004 }
5005
Richard Smithcd45dbc2014-04-19 03:48:30 +00005006 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005007 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005008 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005009}
5010
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005011void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005012 uint32_t Raw = Loc.getRawEncoding();
5013 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005014}
5015
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005016void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005017 AddSourceLocation(Range.getBegin(), Record);
5018 AddSourceLocation(Range.getEnd(), Record);
5019}
5020
Richard Smithf144b542016-04-08 21:54:32 +00005021void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5022 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005023}
5024
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00005025static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5026 FixedPointSemantics FPSema) {
5027 Record.push_back(FPSema.getWidth());
5028 Record.push_back(FPSema.getScale());
5029 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5030 FPSema.hasUnsignedPadding() << 2);
5031}
5032
5033void ASTRecordWriter::AddAPValue(const APValue &Value) {
5034 APValue::ValueKind Kind = Value.getKind();
5035 push_back(static_cast<uint64_t>(Kind));
5036 switch (Kind) {
5037 case APValue::None:
5038 case APValue::Indeterminate:
5039 return;
5040 case APValue::Int:
5041 AddAPSInt(Value.getInt());
5042 return;
5043 case APValue::Float:
5044 push_back(static_cast<uint64_t>(
5045 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5046 AddAPFloat(Value.getFloat());
5047 return;
5048 case APValue::FixedPoint: {
5049 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5050 AddAPSInt(Value.getFixedPoint().getValue());
5051 return;
5052 }
5053 case APValue::ComplexInt: {
5054 AddAPSInt(Value.getComplexIntReal());
5055 AddAPSInt(Value.getComplexIntImag());
5056 return;
5057 }
5058 case APValue::ComplexFloat: {
5059 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5060 Value.getComplexFloatReal().getSemantics())));
5061 AddAPFloat(Value.getComplexFloatReal());
5062 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5063 Value.getComplexFloatImag().getSemantics())));
5064 AddAPFloat(Value.getComplexFloatImag());
5065 return;
5066 }
5067 case APValue::LValue:
5068 case APValue::Vector:
5069 case APValue::Array:
5070 case APValue::Struct:
5071 case APValue::Union:
5072 case APValue::MemberPointer:
5073 case APValue::AddrLabelDiff:
5074 // TODO : Handle all these APValue::ValueKind.
5075 return;
5076 }
5077 llvm_unreachable("Invalid APValue::ValueKind");
5078}
5079
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005080void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005081 Record.push_back(getIdentifierRef(II));
5082}
5083
Sebastian Redl539c5062010-08-18 23:57:32 +00005084IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005085 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005086 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005087
Sebastian Redl539c5062010-08-18 23:57:32 +00005088 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005089 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005090 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005091 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005092}
5093
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005094MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005095 // Don't emit builtin macros like __LINE__ to the AST file unless they
5096 // have been redefined by the header (in which case they are not
5097 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005098 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005099 return 0;
5100
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005101 MacroID &ID = MacroIDs[MI];
5102 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005103 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005104 MacroInfoToEmitData Info = { Name, MI, ID };
5105 MacroInfosToEmit.push_back(Info);
5106 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005107 return ID;
5108}
5109
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005110MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005111 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005112 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005113
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005114 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5115 return MacroIDs[MI];
5116}
5117
5118uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005119 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005120}
5121
Richard Smithe64e7452016-04-18 21:54:58 +00005122void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5123 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005124}
5125
Sebastian Redl539c5062010-08-18 23:57:32 +00005126SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005127 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005128 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005129 }
5130
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005131 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005132 if (SID == 0 && Chain) {
5133 // This might trigger a ReadSelector callback, which will set the ID for
5134 // this selector.
5135 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005136 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005137 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005138 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005139 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005140 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005141 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005142 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005143}
5144
Richard Smithe64e7452016-04-18 21:54:58 +00005145void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5146 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005147}
5148
Richard Smith290d8012016-04-06 17:06:00 +00005149void ASTRecordWriter::AddTemplateArgumentLocInfo(
5150 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005151 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005152 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005153 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005154 break;
5155 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005156 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005157 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005158 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005159 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5160 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005161 break;
5162 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005163 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5164 AddSourceLocation(Arg.getTemplateNameLoc());
5165 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005166 break;
John McCall0ad16662009-10-29 08:12:44 +00005167 case TemplateArgument::Null:
5168 case TemplateArgument::Integral:
5169 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005170 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005171 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005172 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005173 break;
5174 }
5175}
5176
Richard Smith290d8012016-04-06 17:06:00 +00005177void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5178 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005179
5180 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5181 bool InfoHasSameExpr
5182 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005183 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005184 if (InfoHasSameExpr)
5185 return; // Avoid storing the same expr twice.
5186 }
Richard Smith290d8012016-04-06 17:06:00 +00005187 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005188}
5189
Richard Smith290d8012016-04-06 17:06:00 +00005190void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005191 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005192 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005193 return;
5194 }
5195
Richard Smithc23d7342018-06-29 20:46:25 +00005196 AddTypeRef(TInfo->getType());
Richard Smith290d8012016-04-06 17:06:00 +00005197 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005198}
5199
Richard Smith290d8012016-04-06 17:06:00 +00005200void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
Richard Smith290d8012016-04-06 17:06:00 +00005201 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005202 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005203 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005204}
5205
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005206void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005207 Record.push_back(GetOrCreateTypeID(T));
5208}
5209
Richard Smith2095ffe2015-03-16 20:11:03 +00005210TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005211 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005212 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5213 if (T.isNull())
5214 return TypeIdx();
5215 assert(!T.getLocalFastQualifiers());
5216
5217 TypeIdx &Idx = TypeIdxs[T];
5218 if (Idx.getIndex() == 0) {
5219 if (DoneWritingDeclsAndTypes) {
5220 assert(0 && "New type seen after serializing all the types to emit!");
5221 return TypeIdx();
5222 }
5223
5224 // We haven't seen this type before. Assign it a new ID and put it
5225 // into the queue of types to emit.
5226 Idx = TypeIdx(NextTypeID++);
5227 DeclTypesToEmit.push(T);
5228 }
5229 return Idx;
5230 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005231}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005232
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005233TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005234 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005235 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5236 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005237 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005238 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005239
Richard Smith2095ffe2015-03-16 20:11:03 +00005240 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5241 assert(I != TypeIdxs.end() && "Type not emitted!");
5242 return I->second;
5243 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005244}
5245
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005246void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005247 Record.push_back(GetDeclRef(D));
5248}
5249
Sebastian Redl539c5062010-08-18 23:57:32 +00005250DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005251 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005252
5253 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005254 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005255 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005256
Douglas Gregorb3163e52012-01-05 22:33:30 +00005257 // If D comes from an AST file, its declaration ID is already known and
5258 // fixed.
5259 if (D->isFromASTFile())
5260 return D->getGlobalID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005261
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005262 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005263 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005264 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005265 if (DoneWritingDeclsAndTypes) {
5266 assert(0 && "New decl seen after serializing all the decls to emit!");
5267 return 0;
5268 }
5269
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005270 // We haven't seen this declaration before. Give it a new ID and
5271 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005272 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005273 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005274 }
5275
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005276 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005277}
5278
Sebastian Redl539c5062010-08-18 23:57:32 +00005279DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005280 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005281 return 0;
5282
Douglas Gregorb3163e52012-01-05 22:33:30 +00005283 // If D comes from an AST file, its declaration ID is already known and
5284 // fixed.
5285 if (D->isFromASTFile())
5286 return D->getGlobalID();
5287
Douglas Gregore84a9da2009-04-20 20:36:09 +00005288 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5289 return DeclIDs[D];
5290}
5291
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005292void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005293 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005294 assert(D);
5295
5296 SourceLocation Loc = D->getLocation();
5297 if (Loc.isInvalid())
5298 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005299
5300 // We only keep track of the file-level declarations of each file.
5301 if (!D->getLexicalDeclContext()->isFileContext())
5302 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005303 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5304 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005305 // TemplateTemplateParmDecls that are part of an alias template, should not
5306 // have TU as lexical context.
5307 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005308 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005309
5310 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005311 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005312 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005313 FileID FID;
5314 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005315 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005316 if (FID.isInvalid())
5317 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005318 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005319
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005320 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005321 if (!Info)
5322 Info = new DeclIDInFileInfo();
5323
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005324 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005325 LocDeclIDsTy &Decls = Info->DeclIDs;
5326
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005327 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005328 Decls.push_back(LocDecl);
5329 return;
5330 }
5331
Benjamin Kramer45025c02013-08-24 13:22:59 +00005332 LocDeclIDsTy::iterator I =
Fangrui Song7264a472019-07-03 08:13:17 +00005333 llvm::upper_bound(Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005334
5335 Decls.insert(I, LocDecl);
5336}
5337
Richard Smithd08aeb62014-08-28 01:33:39 +00005338unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5339 assert(needsAnonymousDeclarationNumber(D) &&
5340 "expected an anonymous declaration");
5341
5342 // Number the anonymous declarations within this context, if we've not
5343 // already done so.
5344 auto It = AnonymousDeclarationNumbers.find(D);
5345 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005346 auto *DC = D->getLexicalDeclContext();
5347 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5348 AnonymousDeclarationNumbers[ND] = Number;
5349 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005350
5351 It = AnonymousDeclarationNumbers.find(D);
5352 assert(It != AnonymousDeclarationNumbers.end() &&
5353 "declaration not found within its lexical context");
5354 }
5355
5356 return It->second;
5357}
5358
Richard Smith290d8012016-04-06 17:06:00 +00005359void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5360 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005361 switch (Name.getNameKind()) {
5362 case DeclarationName::CXXConstructorName:
5363 case DeclarationName::CXXDestructorName:
5364 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005365 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005366 break;
5367
5368 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005369 AddSourceLocation(SourceLocation::getFromRawEncoding(
5370 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005371 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005372 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005373 break;
5374
5375 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005376 AddSourceLocation(SourceLocation::getFromRawEncoding(
5377 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005378 break;
5379
5380 case DeclarationName::Identifier:
5381 case DeclarationName::ObjCZeroArgSelector:
5382 case DeclarationName::ObjCOneArgSelector:
5383 case DeclarationName::ObjCMultiArgSelector:
5384 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005385 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005386 break;
5387 }
5388}
5389
Richard Smith290d8012016-04-06 17:06:00 +00005390void ASTRecordWriter::AddDeclarationNameInfo(
5391 const DeclarationNameInfo &NameInfo) {
5392 AddDeclarationName(NameInfo.getName());
5393 AddSourceLocation(NameInfo.getLoc());
5394 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005395}
5396
Richard Smith290d8012016-04-06 17:06:00 +00005397void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5398 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5399 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005400 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005401 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005402}
5403
Richard Smith290d8012016-04-06 17:06:00 +00005404void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005405 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005406 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005407 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005408
5409 // Push each of the nested-name-specifiers's onto a stack for
5410 // serialization in reverse order.
5411 while (NNS) {
5412 NestedNames.push_back(NNS);
5413 NNS = NNS.getPrefix();
5414 }
5415
Richard Smith290d8012016-04-06 17:06:00 +00005416 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005417 while(!NestedNames.empty()) {
5418 NNS = NestedNames.pop_back_val();
5419 NestedNameSpecifier::SpecifierKind Kind
5420 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005421 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005422 switch (Kind) {
5423 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005424 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5425 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005426 break;
5427
5428 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005429 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5430 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005431 break;
5432
5433 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005434 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5435 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005436 break;
5437
5438 case NestedNameSpecifier::TypeSpec:
5439 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005440 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Richard Smithc23d7342018-06-29 20:46:25 +00005441 AddTypeRef(NNS.getTypeLoc().getType());
Richard Smith290d8012016-04-06 17:06:00 +00005442 AddTypeLoc(NNS.getTypeLoc());
5443 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005444 break;
5445
5446 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005447 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005448 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005449
5450 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005451 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5452 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005453 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005454 }
5455 }
5456}
5457
Richard Smithe64e7452016-04-18 21:54:58 +00005458void ASTRecordWriter::AddTemplateParameterList(
5459 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005460 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005461 AddSourceLocation(TemplateParams->getTemplateLoc());
5462 AddSourceLocation(TemplateParams->getLAngleLoc());
5463 AddSourceLocation(TemplateParams->getRAngleLoc());
Saar Raz0330fba2019-10-15 18:44:06 +00005464
Richard Smithe64e7452016-04-18 21:54:58 +00005465 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005466 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005467 AddDeclRef(P);
Saar Raz0330fba2019-10-15 18:44:06 +00005468 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5469 Record->push_back(true);
5470 AddStmt(const_cast<Expr*>(RequiresClause));
5471 } else {
5472 Record->push_back(false);
5473 }
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005474}
5475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005476/// Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005477void ASTRecordWriter::AddTemplateArgumentList(
5478 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005479 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005480 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005481 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005482 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005483}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005484
Richard Smith290d8012016-04-06 17:06:00 +00005485void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5486 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005487 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005488 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5489 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5490 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005491 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005492 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005493 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005494}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005495
Richard Smithe64e7452016-04-18 21:54:58 +00005496void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5497 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005498 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005499 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005500 AddDeclRef(I.getDecl());
5501 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005502 }
5503}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005504
Richard Smith290d8012016-04-06 17:06:00 +00005505// FIXME: Move this out of the main ASTRecordWriter interface.
5506void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5507 Record->push_back(Base.isVirtual());
5508 Record->push_back(Base.isBaseOfClass());
5509 Record->push_back(Base.getAccessSpecifierAsWritten());
5510 Record->push_back(Base.getInheritConstructors());
5511 AddTypeSourceInfo(Base.getTypeSourceInfo());
5512 AddSourceRange(Base.getSourceRange());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005513 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005514 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005515}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005516
Richard Smith645d2cf2016-04-14 00:29:55 +00005517static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5518 ArrayRef<CXXBaseSpecifier> Bases) {
5519 ASTWriter::RecordData Record;
5520 ASTRecordWriter Writer(W, Record);
5521 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005522
Richard Smith645d2cf2016-04-14 00:29:55 +00005523 for (auto &Base : Bases)
5524 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005525
Richard Smith645d2cf2016-04-14 00:29:55 +00005526 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005527}
5528
Richard Smith290d8012016-04-06 17:06:00 +00005529// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005530void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5531 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5532}
5533
Richard Smithaa165cf2016-04-13 21:57:08 +00005534static uint64_t
5535EmitCXXCtorInitializers(ASTWriter &W,
5536 ArrayRef<CXXCtorInitializer *> CtorInits) {
5537 ASTWriter::RecordData Record;
5538 ASTRecordWriter Writer(W, Record);
5539 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005540
Richard Smithaa165cf2016-04-13 21:57:08 +00005541 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005542 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005543 Writer.push_back(CTOR_INITIALIZER_BASE);
5544 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5545 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005546 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005547 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5548 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005549 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005550 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5551 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005552 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005553 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5554 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005555 }
Francois Pichetd583da02010-12-04 09:14:42 +00005556
Richard Smithaa165cf2016-04-13 21:57:08 +00005557 Writer.AddSourceLocation(Init->getMemberLocation());
5558 Writer.AddStmt(Init->getInit());
5559 Writer.AddSourceLocation(Init->getLParenLoc());
5560 Writer.AddSourceLocation(Init->getRParenLoc());
5561 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005562 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005563 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005564 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005565
5566 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005567}
5568
Richard Smithaa165cf2016-04-13 21:57:08 +00005569// FIXME: Move this out of the main ASTRecordWriter interface.
5570void ASTRecordWriter::AddCXXCtorInitializers(
5571 ArrayRef<CXXCtorInitializer *> CtorInits) {
5572 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005573}
5574
Richard Smith290d8012016-04-06 17:06:00 +00005575void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005576 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005577 Record->push_back(Data.IsLambda);
Richard Smith91aeacc2019-10-11 00:29:04 +00005578
5579 #define FIELD(Name, Width, Merge) \
5580 Record->push_back(Data.Name);
5581 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
Richard Trieufd1acbb2017-04-11 21:31:00 +00005582
5583 // getODRHash will compute the ODRHash if it has not been previously computed.
5584 Record->push_back(D->getODRHash());
David Blaikief63556d2017-04-12 20:58:33 +00005585 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
5586 Writer->WritingModule && !D->isDependentType();
5587 Record->push_back(ModulesDebugInfo);
5588 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00005589 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5590
Richard Smith561fb152012-02-25 07:33:38 +00005591 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005592
Richard Smith290d8012016-04-06 17:06:00 +00005593 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005594 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005595 AddCXXBaseSpecifiers(Data.bases());
5596
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005597 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005598 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005599 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005600 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005601
Richard Smith290d8012016-04-06 17:06:00 +00005602 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
Richard Smith91aeacc2019-10-11 00:29:04 +00005603 Record->push_back(Data.ComputedVisibleConversions);
5604 if (Data.ComputedVisibleConversions)
5605 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005606 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005607 AddDeclRef(D->getFirstFriend());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005608
Douglas Gregor99ae8062012-02-14 17:54:36 +00005609 // Add lambda-specific data.
5610 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005611 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005612 Record->push_back(Lambda.Dependent);
5613 Record->push_back(Lambda.IsGenericLambda);
5614 Record->push_back(Lambda.CaptureDefault);
5615 Record->push_back(Lambda.NumCaptures);
5616 Record->push_back(Lambda.NumExplicitCaptures);
Michael Liao243ebfb2019-10-19 00:15:19 +00005617 Record->push_back(Lambda.HasKnownInternalLinkage);
Richard Smith290d8012016-04-06 17:06:00 +00005618 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00005619 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00005620 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005621 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005622 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005623 AddSourceLocation(Capture.getLocation());
5624 Record->push_back(Capture.isImplicit());
5625 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005626 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005627 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005628 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005629 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005630 break;
5631 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005632 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005633 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005634 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005635 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005636 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005637 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005638 break;
5639 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005640 }
5641 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005642}
5643
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005644void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005645 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005646 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005647 assert(FirstDeclID == NextDeclID &&
5648 FirstTypeID == NextTypeID &&
5649 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005650 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005651 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005652 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005653 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005654
Sebastian Redl07a89a82010-07-30 00:29:29 +00005655 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005656
Richard Smith7f330cd2015-03-18 01:42:29 +00005657 // Note, this will get called multiple times, once one the reader starts up
5658 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005659 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5660 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5661 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005662 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005663 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005664 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005665 NextDeclID = FirstDeclID;
5666 NextTypeID = FirstTypeID;
5667 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005668 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005669 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005670 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005671}
5672
Sebastian Redl539c5062010-08-18 23:57:32 +00005673void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005674 // Always keep the highest ID. See \p TypeRead() for more information.
5675 IdentID &StoredID = IdentifierIDs[II];
5676 if (ID > StoredID)
5677 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005678}
5679
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005680void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005681 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005682 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005683 if (ID > StoredID)
5684 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005685}
5686
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005687void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005688 // Always take the highest-numbered type index. This copes with an interesting
5689 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005690 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005691 // keep the higher-numbered entry so that we can properly write it out to
5692 // the AST file.
5693 TypeIdx &StoredIdx = TypeIdxs[T];
5694 if (Idx.getIndex() >= StoredIdx.getIndex())
5695 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005696}
5697
Sebastian Redl539c5062010-08-18 23:57:32 +00005698void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005699 // Always keep the highest ID. See \p TypeRead() for more information.
5700 SelectorID &StoredID = SelectorIDs[S];
5701 if (ID > StoredID)
5702 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005703}
Douglas Gregor91096292010-10-02 19:29:26 +00005704
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005705void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005706 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005707 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005708 MacroDefinitions[MD] = ID;
5709}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005710
Douglas Gregore37a85a2011-12-02 17:30:13 +00005711void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5712 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5713 SubmoduleIDs[Mod] = ID;
5714}
5715
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005716void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005717 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005718 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005719 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005720 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005721 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005722 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005723 // A forward reference was mutated into a definition. Rewrite it.
5724 // FIXME: This happens during template instantiation, should we
5725 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005726 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5727 "completed a tag from another module but not by instantiation?");
5728 DeclUpdates[RD].push_back(
5729 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005730 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005731 }
5732}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005733
Richard Smithf983f7f2015-10-13 00:23:25 +00005734static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5735 if (D->isFromASTFile())
5736 return true;
5737
Richard Smithf983f7f2015-10-13 00:23:25 +00005738 // The predefined __va_list_tag struct is imported if we imported any decls.
5739 // FIXME: This is a gross hack.
5740 return D == D->getASTContext().getVaListTagDecl();
5741}
5742
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005743void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005744 if (Chain && Chain->isProcessingUpdateRecords()) return;
5745 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005746 "Should not add lookup results to non-lookup contexts!");
5747
Vassil Vassilev632eac32016-03-16 11:17:04 +00005748 // TU is handled elsewhere.
5749 if (isa<TranslationUnitDecl>(DC))
5750 return;
5751
5752 // Namespaces are handled elsewhere, except for template instantiations of
5753 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5754 // local instantiations are added to an imported context. Only happens when
5755 // adding ADL lookup candidates, for example templated friends.
5756 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5757 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005758 return;
5759
Richard Smithf983f7f2015-10-13 00:23:25 +00005760 // We're only interested in cases where a local declaration is added to an
5761 // imported context.
5762 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5763 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005764
Richard Smith0f4e2c42015-08-06 04:23:48 +00005765 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005766 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005767 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005768 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5769 // We're adding a visible declaration to a predefined decl context. Ensure
5770 // that we write out all of its lookup results so we don't get a nasty
5771 // surprise when we try to emit its lookup table.
5772 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00005773 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00005774 }
Richard Smithc26d9742016-10-06 20:30:51 +00005775 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005776}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005777
5778void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005779 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005780 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005781
5782 // We're only interested in cases where a local declaration is added to an
5783 // imported context.
5784 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5785 return;
5786
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005787 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005788 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005789
5790 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005791 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005792 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005793 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005794}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005795
Richard Smith564417a2014-03-20 21:47:22 +00005796void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005797 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005798 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5799 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005800 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005801 // If we don't already know the exception specification for this redecl
5802 // chain, add an update record for it.
5803 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5804 ->getType()
5805 ->castAs<FunctionProtoType>()
5806 ->getExceptionSpecType()))
5807 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5808 });
Richard Smith564417a2014-03-20 21:47:22 +00005809}
5810
Richard Smith1fa5d642013-05-11 05:45:24 +00005811void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005812 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005813 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005814 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005815 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005816 DeclUpdates[D].push_back(
5817 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5818 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005819}
5820
Richard Smithf8134002015-03-10 01:41:22 +00005821void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00005822 const FunctionDecl *Delete,
5823 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005824 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005825 assert(!WritingAST && "Already writing the AST!");
5826 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005827 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005828 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005829 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5830 });
Richard Smithf8134002015-03-10 01:41:22 +00005831}
5832
Sebastian Redlab238a72011-04-24 16:28:06 +00005833void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005834 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005835 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005836 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005837 return; // Declaration not imported from PCH.
5838
Richard Smith4d235792014-08-07 18:53:08 +00005839 // Implicit function decl from a PCH was defined.
5840 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005841}
5842
Richard Smith891fc7f2017-12-05 01:31:47 +00005843void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5844 if (Chain && Chain->isProcessingUpdateRecords()) return;
5845 assert(!WritingAST && "Already writing the AST!");
5846 if (!D->isFromASTFile())
5847 return;
5848
5849 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5850}
5851
Richard Smithd28ac5b2014-03-22 23:33:22 +00005852void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005853 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005854 assert(!WritingAST && "Already writing the AST!");
5855 if (!D->isFromASTFile())
5856 return;
5857
Richard Smith9e2341d2015-03-23 03:25:59 +00005858 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005859}
5860
Richard Smith891fc7f2017-12-05 01:31:47 +00005861void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005862 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005863 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005864 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005865 return;
5866
5867 // Since the actual instantiation is delayed, this really means that we need
5868 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00005869 SourceLocation POI;
5870 if (auto *VD = dyn_cast<VarDecl>(D))
5871 POI = VD->getPointOfInstantiation();
5872 else
5873 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5874 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005875}
5876
John McCall32791cc2016-01-06 22:34:54 +00005877void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005878 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005879 assert(!WritingAST && "Already writing the AST!");
5880 if (!D->isFromASTFile())
5881 return;
5882
5883 DeclUpdates[D].push_back(
5884 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5885}
5886
Richard Smith4b054b22016-08-24 21:25:37 +00005887void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5888 assert(!WritingAST && "Already writing the AST!");
5889 if (!D->isFromASTFile())
5890 return;
5891
5892 DeclUpdates[D].push_back(
5893 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5894}
5895
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005896void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5897 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005898 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005899 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005900 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005901 return; // Declaration not imported from PCH.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005902
Douglas Gregor404cdde2012-01-27 01:47:08 +00005903 assert(IFD->getDefinition() && "Category on a class without a definition?");
5904 ObjCClassesWithCategories.insert(
5905 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005906}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005907
Eli Friedman276dd182013-09-05 00:02:25 +00005908void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005909 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00005910 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00005911
5912 // If there is *any* declaration of the entity that's not from an AST file,
5913 // we can skip writing the update record. We make sure that isUsed() triggers
5914 // completion of the redeclaration chain of the entity.
5915 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5916 if (IsLocalDecl(Prev))
5917 return;
Eli Friedman276dd182013-09-05 00:02:25 +00005918
Aaron Ballman4f45b712014-03-21 15:22:56 +00005919 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005920}
Alexey Bataev97720002014-11-11 04:05:39 +00005921
5922void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005923 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00005924 assert(!WritingAST && "Already writing the AST!");
5925 if (!D->isFromASTFile())
5926 return;
5927
5928 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5929}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005930
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005931void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
5932 if (Chain && Chain->isProcessingUpdateRecords()) return;
5933 assert(!WritingAST && "Already writing the AST!");
5934 if (!D->isFromASTFile())
5935 return;
5936
5937 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
5938}
5939
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005940void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5941 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005942 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005943 assert(!WritingAST && "Already writing the AST!");
5944 if (!D->isFromASTFile())
5945 return;
5946
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005947 DeclUpdates[D].push_back(
5948 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005949}
5950
Richard Smith4caa4492015-05-15 02:34:32 +00005951void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005952 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005953 assert(!WritingAST && "Already writing the AST!");
5954 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005955 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005956}
Alex Denisovfde64952015-06-26 05:28:36 +00005957
5958void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5959 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005960 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00005961 assert(!WritingAST && "Already writing the AST!");
5962 if (!Record->isFromASTFile())
5963 return;
5964 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5965}
Richard Smithc26d9742016-10-06 20:30:51 +00005966
5967void ASTWriter::AddedCXXTemplateSpecialization(
5968 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
5969 assert(!WritingAST && "Already writing the AST!");
5970
5971 if (!TD->getFirstDecl()->isFromASTFile())
5972 return;
5973 if (Chain && Chain->isProcessingUpdateRecords())
5974 return;
5975
5976 DeclsToEmitEvenIfUnreferenced.push_back(D);
5977}
5978
5979void ASTWriter::AddedCXXTemplateSpecialization(
5980 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5981 assert(!WritingAST && "Already writing the AST!");
5982
5983 if (!TD->getFirstDecl()->isFromASTFile())
5984 return;
5985 if (Chain && Chain->isProcessingUpdateRecords())
5986 return;
5987
5988 DeclsToEmitEvenIfUnreferenced.push_back(D);
5989}
5990
5991void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5992 const FunctionDecl *D) {
5993 assert(!WritingAST && "Already writing the AST!");
5994
5995 if (!TD->getFirstDecl()->isFromASTFile())
5996 return;
5997 if (Chain && Chain->isProcessingUpdateRecords())
5998 return;
5999
6000 DeclsToEmitEvenIfUnreferenced.push_back(D);
6001}
Kelvin Libe286f52018-09-15 13:54:15 +00006002
6003//===----------------------------------------------------------------------===//
6004//// OMPClause Serialization
6005////===----------------------------------------------------------------------===//
6006
6007void OMPClauseWriter::writeClause(OMPClause *C) {
6008 Record.push_back(C->getClauseKind());
6009 Visit(C);
6010 Record.AddSourceLocation(C->getBeginLoc());
6011 Record.AddSourceLocation(C->getEndLoc());
6012}
6013
6014void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006015 Record.push_back(uint64_t(C->getCaptureRegion()));
Kelvin Libe286f52018-09-15 13:54:15 +00006016 Record.AddStmt(C->getPreInitStmt());
6017}
6018
6019void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6020 VisitOMPClauseWithPreInit(C);
6021 Record.AddStmt(C->getPostUpdateExpr());
6022}
6023
6024void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6025 VisitOMPClauseWithPreInit(C);
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006026 Record.push_back(uint64_t(C->getNameModifier()));
Kelvin Libe286f52018-09-15 13:54:15 +00006027 Record.AddSourceLocation(C->getNameModifierLoc());
6028 Record.AddSourceLocation(C->getColonLoc());
6029 Record.AddStmt(C->getCondition());
6030 Record.AddSourceLocation(C->getLParenLoc());
6031}
6032
6033void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +00006034 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006035 Record.AddStmt(C->getCondition());
6036 Record.AddSourceLocation(C->getLParenLoc());
6037}
6038
6039void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6040 VisitOMPClauseWithPreInit(C);
6041 Record.AddStmt(C->getNumThreads());
6042 Record.AddSourceLocation(C->getLParenLoc());
6043}
6044
6045void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6046 Record.AddStmt(C->getSafelen());
6047 Record.AddSourceLocation(C->getLParenLoc());
6048}
6049
6050void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6051 Record.AddStmt(C->getSimdlen());
6052 Record.AddSourceLocation(C->getLParenLoc());
6053}
6054
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00006055void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6056 Record.AddStmt(C->getAllocator());
6057 Record.AddSourceLocation(C->getLParenLoc());
6058}
6059
Kelvin Libe286f52018-09-15 13:54:15 +00006060void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6061 Record.AddStmt(C->getNumForLoops());
6062 Record.AddSourceLocation(C->getLParenLoc());
6063}
6064
6065void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6066 Record.push_back(C->getDefaultKind());
6067 Record.AddSourceLocation(C->getLParenLoc());
6068 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6069}
6070
6071void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6072 Record.push_back(C->getProcBindKind());
6073 Record.AddSourceLocation(C->getLParenLoc());
6074 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6075}
6076
6077void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6078 VisitOMPClauseWithPreInit(C);
6079 Record.push_back(C->getScheduleKind());
6080 Record.push_back(C->getFirstScheduleModifier());
6081 Record.push_back(C->getSecondScheduleModifier());
6082 Record.AddStmt(C->getChunkSize());
6083 Record.AddSourceLocation(C->getLParenLoc());
6084 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6085 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6086 Record.AddSourceLocation(C->getScheduleKindLoc());
6087 Record.AddSourceLocation(C->getCommaLoc());
6088}
6089
6090void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6091 Record.push_back(C->getLoopNumIterations().size());
6092 Record.AddStmt(C->getNumForLoops());
6093 for (Expr *NumIter : C->getLoopNumIterations())
6094 Record.AddStmt(NumIter);
6095 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
Mike Rice0ed46662018-09-20 17:19:41 +00006096 Record.AddStmt(C->getLoopCounter(I));
Kelvin Libe286f52018-09-15 13:54:15 +00006097 Record.AddSourceLocation(C->getLParenLoc());
6098}
6099
6100void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6101
6102void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6103
6104void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6105
6106void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6107
6108void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6109
6110void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
6111
6112void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6113
6114void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6115
6116void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6117
6118void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6119
6120void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6121
6122void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6123 Record.push_back(C->varlist_size());
6124 Record.AddSourceLocation(C->getLParenLoc());
6125 for (auto *VE : C->varlists()) {
6126 Record.AddStmt(VE);
6127 }
6128 for (auto *VE : C->private_copies()) {
6129 Record.AddStmt(VE);
6130 }
6131}
6132
6133void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6134 Record.push_back(C->varlist_size());
6135 VisitOMPClauseWithPreInit(C);
6136 Record.AddSourceLocation(C->getLParenLoc());
6137 for (auto *VE : C->varlists()) {
6138 Record.AddStmt(VE);
6139 }
6140 for (auto *VE : C->private_copies()) {
6141 Record.AddStmt(VE);
6142 }
6143 for (auto *VE : C->inits()) {
6144 Record.AddStmt(VE);
6145 }
6146}
6147
6148void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6149 Record.push_back(C->varlist_size());
6150 VisitOMPClauseWithPostUpdate(C);
6151 Record.AddSourceLocation(C->getLParenLoc());
6152 for (auto *VE : C->varlists())
6153 Record.AddStmt(VE);
6154 for (auto *E : C->private_copies())
6155 Record.AddStmt(E);
6156 for (auto *E : C->source_exprs())
6157 Record.AddStmt(E);
6158 for (auto *E : C->destination_exprs())
6159 Record.AddStmt(E);
6160 for (auto *E : C->assignment_ops())
6161 Record.AddStmt(E);
6162}
6163
6164void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6165 Record.push_back(C->varlist_size());
6166 Record.AddSourceLocation(C->getLParenLoc());
6167 for (auto *VE : C->varlists())
6168 Record.AddStmt(VE);
6169}
6170
6171void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6172 Record.push_back(C->varlist_size());
6173 VisitOMPClauseWithPostUpdate(C);
6174 Record.AddSourceLocation(C->getLParenLoc());
6175 Record.AddSourceLocation(C->getColonLoc());
6176 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6177 Record.AddDeclarationNameInfo(C->getNameInfo());
6178 for (auto *VE : C->varlists())
6179 Record.AddStmt(VE);
6180 for (auto *VE : C->privates())
6181 Record.AddStmt(VE);
6182 for (auto *E : C->lhs_exprs())
6183 Record.AddStmt(E);
6184 for (auto *E : C->rhs_exprs())
6185 Record.AddStmt(E);
6186 for (auto *E : C->reduction_ops())
6187 Record.AddStmt(E);
6188}
6189
6190void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6191 Record.push_back(C->varlist_size());
6192 VisitOMPClauseWithPostUpdate(C);
6193 Record.AddSourceLocation(C->getLParenLoc());
6194 Record.AddSourceLocation(C->getColonLoc());
6195 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6196 Record.AddDeclarationNameInfo(C->getNameInfo());
6197 for (auto *VE : C->varlists())
6198 Record.AddStmt(VE);
6199 for (auto *VE : C->privates())
6200 Record.AddStmt(VE);
6201 for (auto *E : C->lhs_exprs())
6202 Record.AddStmt(E);
6203 for (auto *E : C->rhs_exprs())
6204 Record.AddStmt(E);
6205 for (auto *E : C->reduction_ops())
6206 Record.AddStmt(E);
6207}
6208
6209void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6210 Record.push_back(C->varlist_size());
6211 VisitOMPClauseWithPostUpdate(C);
6212 Record.AddSourceLocation(C->getLParenLoc());
6213 Record.AddSourceLocation(C->getColonLoc());
6214 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6215 Record.AddDeclarationNameInfo(C->getNameInfo());
6216 for (auto *VE : C->varlists())
6217 Record.AddStmt(VE);
6218 for (auto *VE : C->privates())
6219 Record.AddStmt(VE);
6220 for (auto *E : C->lhs_exprs())
6221 Record.AddStmt(E);
6222 for (auto *E : C->rhs_exprs())
6223 Record.AddStmt(E);
6224 for (auto *E : C->reduction_ops())
6225 Record.AddStmt(E);
6226 for (auto *E : C->taskgroup_descriptors())
6227 Record.AddStmt(E);
6228}
6229
6230void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6231 Record.push_back(C->varlist_size());
6232 VisitOMPClauseWithPostUpdate(C);
6233 Record.AddSourceLocation(C->getLParenLoc());
6234 Record.AddSourceLocation(C->getColonLoc());
6235 Record.push_back(C->getModifier());
6236 Record.AddSourceLocation(C->getModifierLoc());
6237 for (auto *VE : C->varlists()) {
6238 Record.AddStmt(VE);
6239 }
6240 for (auto *VE : C->privates()) {
6241 Record.AddStmt(VE);
6242 }
6243 for (auto *VE : C->inits()) {
6244 Record.AddStmt(VE);
6245 }
6246 for (auto *VE : C->updates()) {
6247 Record.AddStmt(VE);
6248 }
6249 for (auto *VE : C->finals()) {
6250 Record.AddStmt(VE);
6251 }
6252 Record.AddStmt(C->getStep());
6253 Record.AddStmt(C->getCalcStep());
Alexey Bataev195ae902019-08-08 13:42:45 +00006254 for (auto *VE : C->used_expressions())
6255 Record.AddStmt(VE);
Kelvin Libe286f52018-09-15 13:54:15 +00006256}
6257
6258void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6259 Record.push_back(C->varlist_size());
6260 Record.AddSourceLocation(C->getLParenLoc());
6261 Record.AddSourceLocation(C->getColonLoc());
6262 for (auto *VE : C->varlists())
6263 Record.AddStmt(VE);
6264 Record.AddStmt(C->getAlignment());
6265}
6266
6267void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6268 Record.push_back(C->varlist_size());
6269 Record.AddSourceLocation(C->getLParenLoc());
6270 for (auto *VE : C->varlists())
6271 Record.AddStmt(VE);
6272 for (auto *E : C->source_exprs())
6273 Record.AddStmt(E);
6274 for (auto *E : C->destination_exprs())
6275 Record.AddStmt(E);
6276 for (auto *E : C->assignment_ops())
6277 Record.AddStmt(E);
6278}
6279
6280void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6281 Record.push_back(C->varlist_size());
6282 Record.AddSourceLocation(C->getLParenLoc());
6283 for (auto *VE : C->varlists())
6284 Record.AddStmt(VE);
6285 for (auto *E : C->source_exprs())
6286 Record.AddStmt(E);
6287 for (auto *E : C->destination_exprs())
6288 Record.AddStmt(E);
6289 for (auto *E : C->assignment_ops())
6290 Record.AddStmt(E);
6291}
6292
6293void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6294 Record.push_back(C->varlist_size());
6295 Record.AddSourceLocation(C->getLParenLoc());
6296 for (auto *VE : C->varlists())
6297 Record.AddStmt(VE);
6298}
6299
6300void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6301 Record.push_back(C->varlist_size());
6302 Record.push_back(C->getNumLoops());
6303 Record.AddSourceLocation(C->getLParenLoc());
6304 Record.push_back(C->getDependencyKind());
6305 Record.AddSourceLocation(C->getDependencyLoc());
6306 Record.AddSourceLocation(C->getColonLoc());
6307 for (auto *VE : C->varlists())
6308 Record.AddStmt(VE);
6309 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6310 Record.AddStmt(C->getLoopData(I));
6311}
6312
6313void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6314 VisitOMPClauseWithPreInit(C);
6315 Record.AddStmt(C->getDevice());
6316 Record.AddSourceLocation(C->getLParenLoc());
6317}
6318
6319void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6320 Record.push_back(C->varlist_size());
6321 Record.push_back(C->getUniqueDeclarationsNum());
6322 Record.push_back(C->getTotalComponentListNum());
6323 Record.push_back(C->getTotalComponentsNum());
6324 Record.AddSourceLocation(C->getLParenLoc());
Kelvin Lief579432018-12-18 22:18:41 +00006325 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
6326 Record.push_back(C->getMapTypeModifier(I));
6327 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6328 }
Michael Kruse4304e9d2019-02-19 16:38:20 +00006329 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6330 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006331 Record.push_back(C->getMapType());
6332 Record.AddSourceLocation(C->getMapLoc());
6333 Record.AddSourceLocation(C->getColonLoc());
6334 for (auto *E : C->varlists())
6335 Record.AddStmt(E);
Michael Kruse4304e9d2019-02-19 16:38:20 +00006336 for (auto *E : C->mapperlists())
6337 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006338 for (auto *D : C->all_decls())
6339 Record.AddDeclRef(D);
6340 for (auto N : C->all_num_lists())
6341 Record.push_back(N);
6342 for (auto N : C->all_lists_sizes())
6343 Record.push_back(N);
6344 for (auto &M : C->all_components()) {
6345 Record.AddStmt(M.getAssociatedExpression());
6346 Record.AddDeclRef(M.getAssociatedDeclaration());
6347 }
6348}
6349
Alexey Bataeve04483e2019-03-27 14:14:31 +00006350void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6351 Record.push_back(C->varlist_size());
6352 Record.AddSourceLocation(C->getLParenLoc());
6353 Record.AddSourceLocation(C->getColonLoc());
6354 Record.AddStmt(C->getAllocator());
6355 for (auto *VE : C->varlists())
6356 Record.AddStmt(VE);
6357}
6358
Kelvin Libe286f52018-09-15 13:54:15 +00006359void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6360 VisitOMPClauseWithPreInit(C);
6361 Record.AddStmt(C->getNumTeams());
6362 Record.AddSourceLocation(C->getLParenLoc());
6363}
6364
6365void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6366 VisitOMPClauseWithPreInit(C);
6367 Record.AddStmt(C->getThreadLimit());
6368 Record.AddSourceLocation(C->getLParenLoc());
6369}
6370
6371void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +00006372 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006373 Record.AddStmt(C->getPriority());
6374 Record.AddSourceLocation(C->getLParenLoc());
6375}
6376
6377void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +00006378 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006379 Record.AddStmt(C->getGrainsize());
6380 Record.AddSourceLocation(C->getLParenLoc());
6381}
6382
6383void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +00006384 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006385 Record.AddStmt(C->getNumTasks());
6386 Record.AddSourceLocation(C->getLParenLoc());
6387}
6388
6389void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6390 Record.AddStmt(C->getHint());
6391 Record.AddSourceLocation(C->getLParenLoc());
6392}
6393
6394void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6395 VisitOMPClauseWithPreInit(C);
6396 Record.push_back(C->getDistScheduleKind());
6397 Record.AddStmt(C->getChunkSize());
6398 Record.AddSourceLocation(C->getLParenLoc());
6399 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6400 Record.AddSourceLocation(C->getCommaLoc());
6401}
6402
6403void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6404 Record.push_back(C->getDefaultmapKind());
6405 Record.push_back(C->getDefaultmapModifier());
6406 Record.AddSourceLocation(C->getLParenLoc());
6407 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6408 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6409}
6410
6411void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6412 Record.push_back(C->varlist_size());
6413 Record.push_back(C->getUniqueDeclarationsNum());
6414 Record.push_back(C->getTotalComponentListNum());
6415 Record.push_back(C->getTotalComponentsNum());
6416 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse01f670d2019-02-22 22:29:42 +00006417 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6418 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006419 for (auto *E : C->varlists())
6420 Record.AddStmt(E);
Michael Kruse01f670d2019-02-22 22:29:42 +00006421 for (auto *E : C->mapperlists())
6422 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006423 for (auto *D : C->all_decls())
6424 Record.AddDeclRef(D);
6425 for (auto N : C->all_num_lists())
6426 Record.push_back(N);
6427 for (auto N : C->all_lists_sizes())
6428 Record.push_back(N);
6429 for (auto &M : C->all_components()) {
6430 Record.AddStmt(M.getAssociatedExpression());
6431 Record.AddDeclRef(M.getAssociatedDeclaration());
6432 }
6433}
6434
6435void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6436 Record.push_back(C->varlist_size());
6437 Record.push_back(C->getUniqueDeclarationsNum());
6438 Record.push_back(C->getTotalComponentListNum());
6439 Record.push_back(C->getTotalComponentsNum());
6440 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse0336c752019-02-25 20:34:15 +00006441 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6442 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006443 for (auto *E : C->varlists())
6444 Record.AddStmt(E);
Michael Kruse0336c752019-02-25 20:34:15 +00006445 for (auto *E : C->mapperlists())
6446 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006447 for (auto *D : C->all_decls())
6448 Record.AddDeclRef(D);
6449 for (auto N : C->all_num_lists())
6450 Record.push_back(N);
6451 for (auto N : C->all_lists_sizes())
6452 Record.push_back(N);
6453 for (auto &M : C->all_components()) {
6454 Record.AddStmt(M.getAssociatedExpression());
6455 Record.AddDeclRef(M.getAssociatedDeclaration());
6456 }
6457}
6458
6459void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6460 Record.push_back(C->varlist_size());
6461 Record.push_back(C->getUniqueDeclarationsNum());
6462 Record.push_back(C->getTotalComponentListNum());
6463 Record.push_back(C->getTotalComponentsNum());
6464 Record.AddSourceLocation(C->getLParenLoc());
6465 for (auto *E : C->varlists())
6466 Record.AddStmt(E);
6467 for (auto *VE : C->private_copies())
6468 Record.AddStmt(VE);
6469 for (auto *VE : C->inits())
6470 Record.AddStmt(VE);
6471 for (auto *D : C->all_decls())
6472 Record.AddDeclRef(D);
6473 for (auto N : C->all_num_lists())
6474 Record.push_back(N);
6475 for (auto N : C->all_lists_sizes())
6476 Record.push_back(N);
6477 for (auto &M : C->all_components()) {
6478 Record.AddStmt(M.getAssociatedExpression());
6479 Record.AddDeclRef(M.getAssociatedDeclaration());
6480 }
6481}
6482
6483void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6484 Record.push_back(C->varlist_size());
6485 Record.push_back(C->getUniqueDeclarationsNum());
6486 Record.push_back(C->getTotalComponentListNum());
6487 Record.push_back(C->getTotalComponentsNum());
6488 Record.AddSourceLocation(C->getLParenLoc());
6489 for (auto *E : C->varlists())
6490 Record.AddStmt(E);
6491 for (auto *D : C->all_decls())
6492 Record.AddDeclRef(D);
6493 for (auto N : C->all_num_lists())
6494 Record.push_back(N);
6495 for (auto N : C->all_lists_sizes())
6496 Record.push_back(N);
6497 for (auto &M : C->all_components()) {
6498 Record.AddStmt(M.getAssociatedExpression());
6499 Record.AddDeclRef(M.getAssociatedDeclaration());
6500 }
6501}
Kelvin Li1408f912018-09-26 04:28:39 +00006502
6503void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
Patrick Lyster4a370b92018-10-01 13:47:43 +00006504
6505void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6506 OMPUnifiedSharedMemoryClause *) {}
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00006507
6508void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Patrick Lyster3fe9e392018-10-11 14:41:10 +00006509
6510void
6511OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6512}
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00006513
6514void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6515 OMPAtomicDefaultMemOrderClause *C) {
6516 Record.push_back(C->getAtomicDefaultMemOrderKind());
6517 Record.AddSourceLocation(C->getLParenLoc());
6518 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6519}